-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmyutils.py
More file actions
executable file
·2354 lines (1857 loc) · 83.7 KB
/
myutils.py
File metadata and controls
executable file
·2354 lines (1857 loc) · 83.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "click",
# "cryptography",
# "geopy",
# "keyring",
# "opentelemetry-api",
# "opentelemetry-sdk",
# "psutil",
# "pyAesCrypt",
# "python-dotenv",
# "qrcode",
# "requests",
# # "timezonefinder",
# ]
# ///
# See https://docs.astral.sh/uv/guides/scripts/#using-a-shebang-to-create-an-executable-file
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MPL-2.0
#### SECTION 01: Define
"""myutils.py here.
This Python module provides utility functions called by my other custom programs running on macOS: openweather.py,
opentelemetry.py, gcp-services.py, etc.
Functions provided show OS properties, process directories, files, strings, etc.
For use by gcp-setup.sh, etc.
BEFORE RUNNING, on Terminal:
# cd to a folder to receive folder (such as github-wilson):
git clone https://github.com/wilsonmar/python-samples.git --depth 1
cd python-samples
# uv init was run to set pyproject.toml & .python-version
python3 -m pip install uv
python -m venv .venv # creates bin, include, lib, pyvenv.cfg
uv venv .venv
source .venv/bin/activate # on macOS & Linux
# ./scripts/activate # PowerShell only
# ./scripts/activate.bat # Windows CMD only
uv add contextlib getpass keyring subprocess --frozen
brew install fonttools keras pillow protobuf markdown
brew install bandit safety semgrep ruff
bandit -r ./github-wilsonmar/project-samples # Security linter for asserts
safety scan myutils.py # Check dependencies for CVEs (now requires login via internet)
semgrep --config=auto . # Pattern-based analysis
ruff check myutils.py
chmod +x myutils.py
uv run myutils.py -v
# -v for verbose
# -vv to trace
# Terminal should not freeze.
# Press control+C to cancel/interrupt run.
AFTER RUN:
deactivate # uv
rm -rf .venv .pytest_cache __pycache__
"""
#### SECTION 02: Dundar variables for git command gxp to git add, commit, push
# POLICY: Dunder (double-underline) variables readable from CLI outside Python
__commit_date__ = "2026-04-02"
__commit_msg__ = "26-04-02 v015 vulscan comments :myutils.py"
__repository__ = "https://github.com/bomonike/google/blob/main/myutils.py"
# __repository__ = "https://github.com/wilsonmar/python-samples/blob/main/myutils.py"
__status__ = "WORKING: ruff check myutils.py => All checks passed!"
# STATUS: Python 3.13.3 working on macOS Sequoia 15.3.1
# from https://github.com/trkonduri/myutils/blob/master/myutils.py
#### SECTION 02: Capture pgm start date/time from the earliest point:
# ruff: noqa: E402 Module level import not at top of file
# See https://bomonike.github.io/python-samples/#StartingTime
# Built-in libraries (no pip/conda install needed):
import time # for timestamp
from datetime import datetime, timezone
# POLICY: Display local wall clock date & time on program start.
# pgm_strt_datetimestamp = datetime.now() has been deprecated.
pgm_strt_timestamp = time.monotonic()
# from zoneinfo import ZoneInfo # For Python 3.9+ https://docs.python.org/3/library/zoneinfo.html
# TODO: Display Z (UTC/GMT) instead of local time
pgm_strt_epoch_timestamp = time.time()
pgm_strt_local_timestamp = time.localtime()
# NOTE: Can't display the dates until formatting code is run below
#### SECTION 03: Built-in Local Python libraries imports:
# POLICY: Capture start time for measuring standard python library load time.
# from time import perf_counter_ns
std_strt_timestamp = time.monotonic()
import argparse
import ast
import gc
import hashlib
# UNUSED: import http.client
import importlib.util
import inspect
import io
import json
# UNUSED: import logging # see https://realpython.com/python-logging/
# UNUSED: import math
import os
from pathlib import Path
import platform # https://docs.python.org/3/library/platform.html
import pwd # https://www.geeksforgeeks.org/pwd-module-in-python/
# UNUSED: import random
import resource
import secrets
import shlex
import shutil # for disk space calcs
import site
import smtplib
import socket
import string
import subprocess
import sys
# import boto3 # for aws python
# UNUSED: from collections import OrderedDict
from collections import defaultdict
from typing import Any, Dict
# UNUSED: import base64
import click
# UNUSED: import urllib.request
# UNUSED: from urllib import request
# UNUSED: from urllib import parse
# UNUSED: from urllib import error
# UNUSED: import uuid
# POLICY: Capture stop time for measuring standard python library load time.
std_stop_timestamp = time.monotonic()
#### SECTION 04: Third-party External Python libraries (requiring pip install):
# POLICY: Capture start time for measuring external python library load time.
xpt_strt_timestamp = time.monotonic()
# Each module should be in requirements.txt:
try:
# pylint: disable=wrong-import-position
# UNUSED: import statsd
# UNUSED: from tabulate import tabulate
import tracemalloc
from contextlib import redirect_stdout
from email.mime.text import MIMEText
# UNUSED: import pandas as pd
from pathlib import Path
import keyring # on macOS
import psutil # psutil-5.9.5
# UNUSED: from pythonping import ping
import pyAesCrypt # pip install pyAesCrypt
# UNUSED: import pytz # time zones
import qrcode
import requests
from cryptography.fernet import Fernet # pip install cryptography
from cryptography.hazmat.primitives import (
serialization, # uv pip install cryptography
)
from cryptography.hazmat.primitives.asymmetric import (
rsa, # uv pip install cryptography
)
from dotenv import load_dotenv # install python-dotenv
#◦ opentelemetry-api>=1.30.0
#◦ opentelemetry-sdk>=1.30.0
#◦ opentelemetry-instrumentation>=0.51b0
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
import shlex
except Exception as e:
print(f"Python module import failed: {e}")
# pyproject.toml file exists
# print_?() not used becuase they are defined after this line:
print("Please activate your virtual environment:\n python3 -m venv venv && source .venv/bin/activate")
exit(9)
# POLICY: Capture stop time for measuring external python library load time.
xpt_stop_timestamp = time.monotonic()
#### SECTION 05: Capture starting memory usage:
env_file = "~/python-samples.env"
def memory_used() -> float:
"""Return memory used."""
# import os, psutil # psutil-5.9.5
process = psutil.Process()
mem = process.memory_info().rss / (1024**2) # in bytes
print(str(process))
print("memory used()=" + str(mem) + " MiB")
return mem
def diskspace_free() -> float:
"""Return displace free."""
# import os, psutil # psutil-5.9.5
disk = psutil.disk_usage("/")
free_space_gb = disk.free / (1024 * 1024 * 1024) # = 1024 * 1024 * 1024
print(f"diskspace_free()={free_space_gb:.2f} GB")
return free_space_gb
pgm_strt_mem_used = memory_used()
pgm_strt_disk_free = diskspace_free()
#### SECTION 05: Time utility functions:
def day_of_week(local_time_obj) -> str:
"""Return day of week name from weekday() number."""
# str(days[local_time_obj.weekday()]) # Monday=0 ... Sunday=6
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
return str(days[local_time_obj.weekday()])
def test_datetime():
"""Test function to verify datetime functionality."""
current_time = datetime.now()
formatted_time = current_time.strftime("%Y-%m-%d-%H:%M")
return formatted_time
def get_user_local_time() -> str:
"""Return a string formatted with datetime stamp in local timezone.
Not used in logs which should be in UTC.
Example: "07:17 AM (07:17:54) 2025-04-21 MDT"
"""
now: datetime = datetime.now()
local_tz = datetime.now(timezone.utc).astimezone().tzinfo
return f"{now:%I:%M %p (%H:%M:%S) %Y-%m-%d} {local_tz}"
def get_user_local_timestamp(format_str: str = "yymmddhhmm") -> str:
"""Return a string formatted with datetime stamp in local timezone.
Not used in logs which should be in UTC.
Example: "07:17 AM (07:17:54) 2025-04-21 MDT"
"""
current_time = time.localtime() # localtime([secs])
year = str(current_time.tm_year)[-2:] # Last 2 digits of year
month = str(current_time.tm_mon).zfill(2) # .zfill(2) = zero fill
day = str(current_time.tm_mday).zfill(2) # Day with leading zero
hour = str(current_time.tm_hour).zfill(2) # Day with leading zero
minute = str(current_time.tm_min).zfill(2) # Day with leading zero
if format_str == "yymmdd":
return f"{year}{month}{day}"
if format_str == "yymmddhhmm":
return f"{year}{month}{day}{hour}{minute}"
# TODO: Google lasStepTimestamp": "2025-06-07T23:51:54.757-07:00",
def filetimestamp(filename):
"""Obtain file timestamp.
USAGE: print(f"File last modified: {myutils.filetimestamp("myutils.py")} ")
# TODO: Add time zone info. 📢
"""
created = os.path.getmtime(filename)
modified = os.path.getctime(filename)
if created == modified:
return f"{ctimestamp(filename)}"
else:
return f"{mtimestamp(filename)}"
def mtimestamp(filename):
"""Print mtime.
USAGE: print(f"File last modified: {myutils.mtimestamp("myutils.py")} ")
"""
t = os.path.getmtime(filename)
return datetime.fromtimestamp(t).strftime("%Y-%m-%d-%H:%M")
def ctimestamp(filename):
"""Print time.
USAGE: print(f"File created: {myutils.ctimestamp("myutils.py")}")
Fixed datetime import issue
"""
t = os.path.getctime(filename)
# Use the imported datetime class correctly
return datetime.fromtimestamp(t).strftime("%Y-%m-%d-%H:%M")
def list_files(basepath, validexts=None, contains=None):
"""List files.
USAGE: print(myutils.list_files("./"))
List files in a directory with optional filters.
Args:
basePath: Base directory to search for files
validExts: Optional tuple of valid file extensions
contains: Optional string to filter file names
Yields:
File paths that match the filters
"""
for rootdir, dirnames, filenames in os.walk(basepath):
for filename in filenames:
if contains is not None and filename.find(contains) == -1:
continue
# reverse find the "." from back wards
ext = filename[filename.rfind(".") :]
if validexts is None or ext.endswith(validexts):
file = os.path.realpath(os.path.join(rootdir, filename))
yield file
RUNID = get_user_local_timestamp() # "yymmddhhmm"
PROGRAM_NAME = os.path.basename(os.path.normpath(sys.argv[0]))
global_env_path = None
#### SECTION 03: Print utility globals and functions (as early in pgm as possible)
## Global variables: Colors Styles:
class Bcolors:
"""ANSI escape sequences.
See https://gist.github.com/JBlond/2fea43a3049b38287e5e9cefc87b2124
"""
BOLD = "\033[1m" # Begin bold text
UNDERLINE = "\033[4m" # Begin underlined text
INFO = "\033[92m" # [92 green
HEADING = "\033[37m" # [37 white
VERBOSE = "\033[91m" # [91 beige
WARNING = "\033[93m" # [93 yellow
ERROR = "\033[95m" # [95 purple
TRACE = "\033[35m" # CVIOLET
TODO = "\033[96m" # [96 blue/green
FAIL = "\033[31m" # [31 red
# [94 blue (bad on black background)
STATS = "\033[36m" # [36 cyan
CVIOLET = "\033[35m"
CBEIGE = "\033[36m"
CWHITE = "\033[37m"
GRAY = "\033[90m"
RESET = "\033[0m" # switch back to default color
# Starting settings:
show_secrets = False # Always False to not show
show_heading = True # -q Don't display step headings before attempting actions
show_fail = True # Always show
show_error = True # Always show
show_warning = True # Always show
show_trace = True # -vv Display responses from API calls for debugging code
show_verbose = True # -v Display technical program run conditions
show_sys_info = True
show_todo = True
show_info = True
SHOW_DEBUG = True
show_dates_in_logs = False
print_prefix = "***"
SHOW_SUMMARY_COUNTS = True
def no_newlines(in_string):
"""Strip new line from in_string."""
return "".join(in_string.splitlines())
def print_separator():
"""Print a blank line in CLI output.
Used in case the technique changes throughout this code.
"""
print(" ")
def print_heading(text_in):
"""Print underlined words for several additional lines to follow."""
if show_heading:
# Backhand Index Pointing Down Emoji highlights content below was approved as part of Unicode 6.0 in 2010 under the name "White Down Pointing Backhand Index" and added to Emoji 1.0 in 2015.
print("👇", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
print(Bcolors.HEADING + Bcolors.UNDERLINE, f"{text_in}", Bcolors.RESET)
def print_fail(text_in):
"""Print when program should stop."""
if show_fail: # typically a programming error.
# The ⛔ No Entry (Stop sign) Emoji indicates forbidden. approved as part of Unicode 5.2 in 2009 and added to Emoji 1.0 in 2015.
print("❌", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
print(Bcolors.FAIL, f"{text_in}", Bcolors.RESET)
# PROTIP: For easier debugging, use a program exit command at point of failure rather than here.
def print_error(text_in):
"""Print when a programming error is evident."""
if show_fail:
print("⭕", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
print(Bcolors.ERROR, f"{text_in}", Bcolors.RESET)
def print_warning(text_in):
"""Print warning about the conditions of data."""
if show_warning:
print("⚠️", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
print(Bcolors.WARNING, f"{text_in}", Bcolors.RESET)
def print_todo(text_in):
"""Print tasks programmer should remember to do."""
if show_todo:
# The 🛠️ hammer and wrench emoji is commonly used for various content concerning tools, building, construction, and work, both manual and digital
print("💡", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
print(Bcolors.TODO, f"{text_in}", Bcolors.RESET)
def print_info(text_in):
"""Print info for user."""
if show_info:
# Alternately: print("👍", end="")
print("✅", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
print(Bcolors.INFO + Bcolors.BOLD, f"{text_in}", Bcolors.RESET)
def print_verbose(text_in):
"""Print program operation internals."""
if show_verbose:
# The 📣 speaker emoji is used to represent sound, noise, or speech.
print("📢", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
print(Bcolors.VERBOSE, f"{text_in}", Bcolors.RESET)
def print_trace(text_in):
"""Print as each object is created in pgm."""
if show_trace:
# The 🔍 magnifying glass is a classic for searching, looking, inspecting, approved as part of Unicode 6.0 in 2010 under the name "Left-Pointing Magnifying Glass" and added to Emoji 1.0 in 2015.
print("⚙️", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
# The fingerprint emoji was approved as part of Unicode 16.0 in 2024 and added to Emoji 16.0 in 2024.
print(Bcolors.TRACE, f"{text_in}", Bcolors.RESET)
def print_secret(secret_in: str) -> None:
"""Output secrets discreetly as count of characters instead of the secret itself.
display only the first few characters (like Git) with dots replacing the rest.
"""
# See https://stackoverflow.com/questions/3503879/assign-output-of-os-system-to-a-variable-and-prevent-it-from-being-displayed-on
if show_secrets: # program parameter
# The triangular red flag on post emoji signals a problem or issue. Approved as part of Unicode 6.0 in 2010 added to Emoji 1.0 in 2015.
print("🚩", end="")
if show_dates_in_logs:
print(get_log_datetime(), end="")
secret_len = 3
if len(secret_in) <= 10: # slice
# Regardless of secret length, to reduce hacker ability to guess:
print(Bcolors.GRAY, "secret too small to print.", Bcolors.RESET)
# print(Bcolors.GRAY,"\"",secret_in,"\"", Bcolors.RESET)
else:
print(
Bcolors.WARNING,
"WARNING: Secret specified to be shown. POLICY VIOLATION: ",
Bcolors.RESET,
)
# WARNING NOTE: secrets should not be printed to logs.
secret_out = secret_in[0:4] + "." * (secret_len - 1)
print(Bcolors.GRAY, '"', secret_out, '..."', Bcolors.RESET)
return None
def show_print_samples() -> None:
"""Display what different type of output look like."""
# See https://wilsonmar.github.io/python-samples/#PrintColors
print_heading("print_heading( show_print_samples():")
print_fail("print_fail() -> sample fail")
print_error("print_error() -> sample error")
print_warning("print_warning() -> sample warning")
print_todo("print_todo() -> sample task to do")
print_info("print_info() -> sample info")
print_verbose("print_verbose() -> sample verbose")
print_trace("print_trace() -> sample trace")
print_secret("123456")
return None
def do_clear_cli() -> None:
"""Clear the CLI screen."""
print_trace(f"At {sys._getframe().f_code.co_name}()")
# import os
# QUESTION: What's the output variable?
lambda: os.system("cls" if os.name in ("nt", "dos") else "clear")
return None
#### SECTION 05: Python .env (environment) variables:
# See https://bomonike.github.io/python-samples/#ParseArguments
def open_env_file(global_env_path: str = None) -> str:
"""Load global variables from .env file based on hard-coded default location.
Args: global ENV_FILE
See https://wilsonmar.github.io/python-samples/#envLoad
See https://stackoverflow.com/questions/40216311/reading-in-environment-variables-from-an-environment-file
"""
# from pathlib import Path
# See https://wilsonmar.github.io/python-samples#run_env
if not global_env_path: # specified or None.
global_env_path = str(Path.home()) + "/" + "python-samples.env" # concatenate path
# PROTIP: Check if .env file on global_env_path is readable:
if not os.path.isfile(global_env_path):
global_env_path = None
print_error(f'{sys._getframe().f_code.co_name}(): global_env_path: not at "{global_env_path}" ')
return None
# import pathlib
# path = pathlib.Path(global_env_path)
# print_info(f"{sys._getframe().f_code.co_name}(): path: \"{path}\" ")
# Based on: pip3 install python-dotenv
# from dotenv import load_dotenv
# See https://www.python-engineer.com/posts/dotenv-python/
# See https://pypi.org/project/python-dotenv/
load_dotenv(global_env_path) # using load_dotenv
# Wait until variables for print_trace are retrieved:
print_verbose(f'{sys._getframe().f_code.co_name}(): at global_env_path: "{global_env_path}" ')
return global_env_path
def get_str_from_env_file(key_in) -> bool:
"""Return a value of string data type from OS environment or .env file.
(using pip python-dotenv)
"""
env_value = os.environ.get(key_in) # TODO
if not env_value: # yes, defined=True, use it:
print_trace(f'{sys._getframe().f_code.co_name}(): "{key_in}") not found in .env file.')
return None
print_info(f'{sys._getframe().f_code.co_name}(): {key_in}: "{env_value}" ')
# # PROTIP: Display only first characters of a potentially secret long string:
# if len(env_var) > 5:
# print_trace(key_in + "=\"" + str(env_var[:5]) +" (remainder removed)")
# else:
# print_trace(key_in + "=\"" + str(env_var) + "\" from .env")
# return str(env_var)
return env_value
def print_env_vars():
"""List all environment variables, one line each using pretty print (pprint)."""
# import os
# import pprint
environ_vars = os.environ
print_heading("User's Environment variable:")
print.pprint(dict(environ_vars), width=1)
def update_env_file(file_path, key, new_value) -> bool:
"""Update a specific key-value pair in a .env file.
Usage:
result = update_env_file("key", "new_value")
Args:
file_path (str): Path to the .env file
key (str): The key to update
new_value (str): The new value for the key
Returns bool: True if key was found and updated, False if key was not found
"""
# import os
# Read the current content:
try:
with open(file_path, "r") as file:
lines = file.readlines()
except FileNotFoundError:
print_error(f'{sys._getframe().f_code.co_name}(): File "{file_path}" not found.')
return False
key_found = False
updated_lines = []
for line in lines:
# Strip whitespace for comparison but preserve original formatting:
stripped_line = line.strip()
# Skip empty lines and comments:
if not stripped_line or stripped_line.startswith("#"):
updated_lines.append(line)
continue
# Check if this line contains our key:
if "=" in stripped_line:
line_key = stripped_line.split("=", 1)[0].strip()
if line_key == key:
safe_value = new_value.replace("\n", "").replace("\r", "")
updated_lines.append(f"{key}={safe_value}\n")
key_found = True
else:
updated_lines.append(line)
else:
updated_lines.append(line)
# If key wasn't found, add it to the end:
if not key_found:
safe_value = new_value.replace("\n", "").replace("\r", "")
updated_lines.append(f"{key}={safe_value}\n")
# Write the updated content back to the file:
try:
with open(file_path, "w") as file:
file.writelines(updated_lines)
print_info(f'{sys._getframe().f_code.co_name}(): "{key}" => "{new_value}" ')
return True
except Exception as e:
print_error(f"{sys._getframe().f_code.co_name}(): {e}")
return False
def update_env_with_quotes(file_path, key, new_value):
"""
Update a .env file with proper quoting for values containing spaces or special characters.
Args:
file_path (str): Path to the .env file
key (str): The key to update
new_value (str): The new value for the key
Returns bool: True if successful, False otherwise
"""
# import os
# Add quotes if value contains spaces or special characters
if " " in new_value or any(char in new_value for char in ["#", '"', "'"]):
new_value = f'"{new_value}"'
return update_env_file(file_path, key, new_value)
#### SECTION 07 - Read custom command line (CLI) arguments controlling this program run:
parser = argparse.ArgumentParser(description="gcp-services.py for Google Cloud Authentication")
parser.add_argument("-q", "--quiet", action="store_true", help="Quiet")
parser.add_argument("-v", "--verbose", action="store_true", help="Show each download")
parser.add_argument("-vv", "--debug", action="store_true", help="Show debug")
parser.add_argument("-l", "--log", help="Log to external file")
parser.add_argument("--project", "-p", help="Google Cloud project ID")
parser.add_argument("--service-account", "-acct", type=str, help="Path to service account key file")
parser.add_argument("--setup-adc", action="store_true", help="Set up Application Default Credentials")
parser.add_argument("--adc", action="store_true", help="Use Application Default Credentials (ADC)")
parser.add_argument("--user", action="store_true", help="Use interactive user authentication (email)")
parser.add_argument("--install", action="store_true", help="Install required packages")
parser.add_argument(
"--format",
"-fmt",
choices=["table", "csv", "json"],
default="table",
help="Output format (default: table)",
)
parser.add_argument("-do", "--delout", action="store_true", help="Delete output file")
# Load arguments from CLI:
args = parser.parse_args()
#### SECTION 08 - Override defaults and .env file with run-time parms:
SHOW_QUIET = args.quiet
SHOW_VERBOSE = args.verbose
SHOW_DEBUG = args.debug
# args.log
# args.project
# args.service_account
# args.setup_adc
# args.adc
# args.user
# args.install
# args.format
GEN_QR_CODE = False # TODO: Change in CLI parm
EMAIL_FROM = os.environ.get("EMAIL_FROM", "") # set EMAIL_FROM env var
EMAIL_TO = "???"
DELETE_OUTPUT_FILE = args.delout # -de --delout Delete output file
#### SECTION 04: Python program name:
def print_module_filenames() -> None:
"""Print module filenames.
USAGE: print_filename()
"""
print_trace(f"At {sys._getframe().f_code.co_name}()")
# import inspect
current_frame = inspect.currentframe()
filename = inspect.getfile(current_frame)
print(f"inspect.getfile(currentframe()): {os.path.basename(filename)}")
filename_no_ext = os.path.splitext(os.path.basename(__file__))[0]
print(f"__file__ without extension: {filename_no_ext} created: {ctimestamp(__file__)} ")
# import sys
current_module = sys.modules[__name__]
print(f"Filename only: {os.path.basename(__file__):>23} modified: {mtimestamp(__file__)}")
if hasattr(current_module, "__file__"):
print(f"os.path.basename(): {os.path.basename(current_module.__file__)} ")
print(f"current_module.__file__: {current_module.__file__}")
print(f"os.path.abspath(__file__): {os.path.abspath(__file__)} ")
return None
def is_macos() -> str:
"""Return true if the operating system is macOS."""
# import platform
# Instead of: return platform.system() == "Darwin"
patform_system = platform.system()
print_verbose(f"{sys._getframe().f_code.co_name}(): {patform_system} ")
if patform_system == "Darwin":
return True
else:
return False
# Alternative approach using specific environment checks:
def is_local_development():
"""Alternative method focusing on common deployment patterns."""
# Check for containerized environments (usually not local)
if os.path.exists("/.dockerenv") or os.getenv("KUBERNETES_SERVICE_HOST"):
return False
# Check for cloud platform environment variables
cloud_indicators = [
"HEROKU_APP_NAME",
"AWS_EXECUTION_ENV",
"GOOGLE_CLOUD_PROJECT",
"AZURE_FUNCTIONS_ENVIRONMENT",
"VERCEL",
"NETLIFY",
]
if any(os.getenv(var) for var in cloud_indicators):
return False
# If none of the above, likely local
return True
def get_str_from_os(varname: str) -> str:
"""Get string value from OS environment variable.
USAGE: api_key = get_str_from_os("OPENAI_API_KEY")
"""
api_key = os.environ.get(varname, None)
return api_key
def display_cli_parameters() -> str:
"""Display CLI parameters."""
args_str = "" # f"{len(sys.argv)} arguments: "
for index, arg in enumerate(sys.argv):
args_str = args_str + f" {arg} "
return args_str
# Like: CLI: ./mondrian-gen.py -v -vv -ai pgm -dc
def set_cli_parms(count):
"""Present menu and parameters to control program."""
# import click
@click.command()
@click.option("--count", default=1, help="Number of greetings.")
# @click.option('--name', prompt='Your name',
# help='The person to greet.')
def set_cli_parms(count):
for x in range(count):
click.echo("Hello!")
# Test by running: ./python-examples.py --help
#### SECTION 06: Logging utility functions:
def get_log_datetime() -> str:
"""Return a formatted datetime string in UTC (GMT) timezone so all logs are aligned.
Example: 2504210416UTC for a minimal with year, month, day, hour, minute, second and timezone code.
"""
# from datetime import datetime
# importing timezone from pytz module
# from pytz import timezone
# To get current time in (non-naive) UTC timezone
# instead of: now_utc = datetime.now(timezone('UTC'))
# Based on https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow
fts = datetime.fromtimestamp(time.time(), tz=timezone.utc)
time_str = fts.strftime("%y%m%d%H%M%Z") # EX: "...-250419" UTC %H%M%Z https://strftime.org
# See https://stackoverflow.com/questions/7588511/format-a-datetime-into-a-string-with-milliseconds
# time_str=datetime.utcnow().strftime('%F %T.%f')
# for ISO 8601-1:2019 like 2023-06-26 04:55:37.123456 https://www.iso.org/news/2017/02/Ref2164.html
# time_str=now_utc.strftime(MY_DATE_FORMAT)
# Alternative: Converting to Asia/Kolkata time zone using the .astimezone method:
# now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
# Format the above datetime using the strftime()
# print('Current Time in Asia/Kolkata TimeZone:',now_asia.strftime(format))
# if show_dates: https://medium.com/tech-iiitg/zulu-module-in-python-8840f0447801
return time_str
# TODO: OpTel (OpenTelemetry) spans and logging:
def export_optel():
"""Create and export a trace to your console.
https://www.perplexity.ai/search/python-code-to-use-opentelemet-bGjntbF4Sk6I6z3l5HBBSg#0
"""
# from opentelemetry import trace
# from opentelemetry.sdk.trace import TracerProvider
# from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
# Set up the tracer provider and exporter
trace.set_tracer_provider(TracerProvider())
span_processor = SimpleSpanProcessor(ConsoleSpanExporter())
trace.get_tracer_provider().add_span_processor(span_processor)
# Get a tracer:
tracer = trace.get_tracer(__name__)
# Create spans:
with tracer.start_as_current_span("parent-span"):
print_verbose("Doing some work in the parent span")
with tracer.start_as_current_span("child-span"):
print_verbose("Doing some work in the child span")
#### SECTION 07: Operating System properties
def mem_usage(tag):
"""Report memory usage.
USAGE: print(f"Memory used: {myutils.mem_usage("myutils.py")}")
"""
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
denom = 1024
if sys.platform == "darwin":
denom = denom**2
print(f"memory used is at {tag} : {round(mem / denom, 2)} MB")
def beautify_json(file, outfile=None):
"""Beautify JSON string.
USAGE: myutils.beautify_json("myutils.py"))
"""
js = json.loads(open(file).read())
if outfile is None:
outfile = file
with open(outfile, "w") as outfilep:
json.dump(js, outfilep, sort_keys=True, indent=4)
def get_fuid(filename):
"""Return user id (such as "johndoe").
USAGE: print(f"FUID: {myutils.get_fuid("myutils.py")}")
"""
return pwd.getpwuid(os.stat(filename).st_uid).pw_name
def execsh(command):
"""Execute CSH.
USAGE: myutils.execsh(["echo", "hello"])
"""
# import shlex
if isinstance(command, str):
command = shlex.split(command)
pipe = subprocess.PIPE
result = subprocess.run(command, stdout=pipe, stderr=pipe, universal_newlines=True, shell=False)
return result.stdout
def force_link(src, linkname):
"""Force link.
USAGE: myutils.force_link(???)
NOTE: os.replace() pattern eliminates TOCTOU race.
"""
tmp = linkname + f".tmp_{secrets.token_hex(8)}"
try:
os.symlink(src, tmp)
os.replace(tmp, linkname)
except Exception as e:
try:
os.unlink(tmp)
except OSError:
pass
print_error(f"{sys._getframe().f_code.co_name}(): {e}")
# See https://bomonike.github.io/python-samples/#run_env
def os_platform():
"""Return a friendly name for the operating system."""
# import platform # https://docs.python.org/3/library/platform.html
platform_system = str(platform.system())
# 'Linux', 'Darwin', 'Java', 'Windows'
print_trace("platform_system=" + str(platform_system))
if platform_system == "Darwin":
my_platform = "macOS"
elif platform_system == "linux" or platform_system == "linux2":
my_platform = "Linux"
elif platform_system == "win32": # includes 64-bit
my_platform = "Windows"
else:
print_fail("platform_system=" + platform_system + " is unknown!")
exit(1) # entire program
return my_platform
def macos_version_name(release_in):
"""Return the marketing name of macOS versions which are not available.
from the running macOS operating system.
"""
# NOTE: Return value is a list!
# This has to be updated every year, so perhaps put this in an external library so updated
# gets loaded during each run.
# Apple has a way of forcing users to upgrade, so this is used as an
# example of coding.
# FIXME: https://github.com/nexB/scancode-plugins/blob/main/etc/scripts/homebrew.py
# See https://support.apple.com/en-us/HT201260 and https://www.wikiwand.com/en/MacOS_version_history
macos_versions = {
"""Versions of macOS."""
"22.8": ["Next2025", 2025, "25"],
"22.7": ["Next2024", 2024, "24"],
"22.6": ["macOS Sonoma", 2023, "23"],
"22.5": ["macOS Ventura", 2022, "13"],