-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpython-samples.py
More file actions
executable file
·4829 lines (3884 loc) · 190 KB
/
python-samples.py
File metadata and controls
executable file
·4829 lines (3884 loc) · 190 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
# -*- coding: utf-8 -*-
# Copyright (c) 2023 JetBloom LLC
# SPDX-License-Identifier: MPL-2.0
"""python-samples.py within https://github.com/wilsonmar/python-samples/blob/master/python-samples/
Explained at https://wilsonmar.github.io/python-samples
This is sample code to provide a feature-rich base for new Python 3.9+ programs run from CLI.
It implements advice at https://www.linkedin.com/pulse/how-shine-coding-challenges-wilson-mar-/
This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
"""
# SECTION 01. Set metadata about this program
# Unlike regular comments, docstrings are available at runtime to the compiler:
__repository__ = "https://github.com/wilsonmar/python-samples"
__author__ = "Wilson Mar"
__copyright__ = "See the file LICENSE for copyright and license info"
__license__ = "See the file LICENSE for copyright and license info"
__linkedin__ = "https://linkedin.com/in/WilsonMar"
# Using semver.org format per PEP440: change on every commit:
__last_commit__ = "python-samples.py 0.3.13 Fix default logic from .env"
# SECTION 49. scan python to copy files from github to cloudinary
# login azure & retrieve secrets from hvault & azure resc list
# login aws with boto3
# fix y = x["main"] error
# click instead of argparse
# fix call of get_ipaddr etc without request
# localization results to weather
# fix zip code
# Add 3 retries to url
# login_gcp, gcp_resc_list
# FIXME: import azure , azure_login, azure_resc_list
# aws_resc_list
# SECTION 02: Capture pgm start date/time
# See https://wilsonmar.github.io/python-samples/#StartingTime
# Based on: pip3 install datetime
import datetime
# Based on: conda install -c conda-forge time
import time # for time.sleep(1.5)
# For wall time of program run:
pgm_strt_datetimestamp = datetime.datetime.now()
# the most accurate difference between two times. Used by timeit.
# pgm_strt_perf_counter = time.perf_counter()
# To display date & time of program start:
pgm_strt_timestamp = time.monotonic()
# 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. Import libraries (in alphabetical order)
# See https://wilsonmar.github.io/python-samples/#Imports
# For all below, based on: https://pypi.org/project/<import name>/
# The first of several external dependencies, and will error if not installed:
# (preferrably within a conda enviornment):
# requirements.txt
# Absolute imports using "from" are explicitly recommended by PEP 8. That's because
# absolute imports are least impacted by project sharing and changes in the current location of import statements.
# For wall time of std (standard) imports:
std_strt_datetimestamp = datetime.datetime.now()
# Python’s Standard library of built-in modules imported as
# listed at https://docs.python.org/3/library/*.html
import base64
import cmd
import collections # advanced data structures
import csv
import datetime
#from datetime import datetime
import decimal
import doctest # docstrings
import hashlib
import hmac
import ipaddress
import json
import locale
import logging
import math
import os # only on unix-like systems
# for os.getenv(), os.uname, os.getpid(), os.environ, os.import, os.path
import os.path
import pathlib
import platform
import pprint # pretty print
import pwd
import random
import re # regular expressions
import site
import sqlite3
import smtplib # to send email
# from stat import *
import socket
import subprocess # so CLI output don't show on Terminal
import sys # built-in # for sys.argv[0], sys.exit(), sys.version
from sys import platform
import timeit
# import tkinter # GUI https://pythonbasics.org/tkinter/
import unittest
import uuid
import venv
import webbrowser
# For wall time of standard imports:
std_stop_datetimestamp = datetime.datetime.now()
# For wall time of xpt imports:
xpt_strt_datetimestamp = datetime.datetime.now()
# See https://wilsonmar.github.io/python-samples.py/#PackagesInstalled
# Based on: conda install -c conda-forge azure-core
# import azure.core
# Based on: conda install -c conda-forge azure-cli-core
# https://anaconda.org/conda-forge/azure-cli-core
# from azure.cli.core import get_default_cli as azcli
import azure.cli.core
# Based on: conda install -c conda-forge azure-identity
import azure.identity
# Based on: conda install -c conda-forge azure-storage
import azure.storage.blob
# Based on: conda install -c conda-forge azure-cli-telemetry
# already installed so no need forimport azure.cli.telemetry
# for aws python
# Based on: conda install -c conda-forge boto3
import boto3
# For argparse replacement: https://click.palletsprojects.com/en/8.1.x/
# Based on: conda install -c conda-forge click
import click # argparse replacement
# from cryptography.fernet import Fernet
# NO import _datetime # because "datetime" doesn't work on Mac?
# conda install -c conda-forge _datetime # doesn't work
# FIXME: Not found: pip3 install _datetime
# from _datetime import timedelta
# NO conda install -c conda-forge datetime NOR conda install datetime
# from dateutil import tz # not found in conda
# See https://bobbyhadz.com/blog/python-no-module-named-dateutil
# Based on: conda install -c conda-forge load_dotenv
from dotenv import load_dotenv
# Based on: conda install python-dotenv # found!
# Based on: conda install -c conda-forge flask
# https://wilsonmar.github.io/python-api-flask/
import flask
# See https://anaconda.org/search?q=google+cloud
# Based on: conda install google-api-python-client
# import google.api.python.client ???
# Based on: conda install -c conda-forge google-auth
import google.auth
# Based on: conda install -c conda-forge google-auth-credentials
import google.auth.credentials
# https://google-auth.readthedocs.io/en/master/reference/google.auth.transport.requests.html
# Based on: conda install -c conda-forge google-auth-transport-requests
import google.auth.transport.requests
# https://github.com/googleapis/google-auth-library-python-oauthlib
# Based on: conda install -c conda-forge google-auth-oauthlib # found!
# import google.auth.oauthlib # FIXME: No module named 'google.auth.oauthlib'
# Based on: conda install google-auth-oauthlib # found!
import google.oauth2.credentials
# See https://github.com/googleapis/google-api-python-client/blob/main/googleapiclient/_helpers.py
# Based on: conda install -c conda-forge google-api-python-client
#import google.api.python.client # found
# https://snyk.io/advisor/python/google-auth-oauthlib
# https://github.com/googleapis/google-auth-library-python-oauthlib
# https://snyk.io/advisor/python/google-auth-httplib2
# conda install -c conda-forge google_auth_httplib2 # NOT FOUND
# pip3 install google_auth_httplib2
# import google_auth_httplib2
# google_auth_httplib2 = True
# Among https://cloud.google.com/apis/docs/overview
# Among https://cloud.google.com/python/docs/reference
# Based on:
# conda install google-api-python-client google-auth-httplib2 google-auth-oauthlib
# conda install google-auth-transport-requests requests
# Based on: conda install -c conda-forge google-cloud-core
#import google.cloud.core
# pip3 install --ignore-installed google-cloud-vision
# Based on: pip3 install httplib2
import httplib2
# Based on: conda install -c conda-forge hvac
# https://snyk.io/advisor/python/hvac # Top 5%
# HashiCorp Vault Python Client v23.1.2 from
# https://pypi.org/project/hvac/
import hvac
# Based on: pip3 install jwt
import jwt
# Based on: pip3 install jsonify # not found in conda
import jsonify # use with flask
# https://snyk.io/advisor/python/jsonify # Unable to verify the project's public source code repository.
# Based on: conda install -c conda-forge keyring
import keyring
# import keyring.util.platform_ as keyring_platform
# NOT FOUND on: conda install -c conda-forge locale
# NOT FOUND on: pip3 install locale
# https://phrase.com/blog/posts/beginners-guide-to-locale-in-python/
# import locale
# NOT FOUND on: conda install -c conda-forge logging
# ERROR
import logging # see https://realpython.com/python-logging/
# Based on: conda install oauth2client
# See https://snyk.io/advisor/python/oauth2client # Top 5%
import oauth2client
import oauth2client.client
# Based on: conda install -c conda-forge psutil
import psutil # psutil-5.9.5
# import pyjwt # pyjwt-2.7.0
# https://snyk.io/advisor/python/pytz # Top 5%
# Based on: conda install -c conda-forge pytz
import pytz # pytz-2021.3 for time zone handling
# regex # regular expression
# NOT FOUND: conda install -c conda-forge redis
# Based on: pip3 install redis
import redis
# Based on: conda install requests # already installed
import requests
# NOT FOUND: conda install -c conda-forge shutil
# Based on: pip3 install shutil # not found either
import shutil
# Based on: conda install -c conda-forge textblob
import textblob
#from textblob import TextBlob
import urllib.request
# Based on: pip3 install textblob # not found
# For wall time of xpt imports:
xpt_stop_datetimestamp = datetime.datetime.now()
# https://github.com/Tinmen/pyLUID LUID (Legible Unique ID)
# SECTION 04: Command-line arguments (in menu) to override verbosity settings:
## TODO: #import click
# The .env location can't be read in from .env:
use_env_file = True # -env "python-samples.env"
global ENV_FILE
ENV_FILE="python-samples.env"
# -clear Console before starting so output always appears at top of screen.
clear_cli = True # -clear
show_logging = False
global show_dates_in_logs
show_dates_in_logs = False
# PROTIP: Global variable referenced within functions:
# values obtained from .env file can be overriden in program call arguments:
show_fail = True # Always show
show_error = True # Always show
show_warning = True # -wx Don't display warning
show_todo = True # -td Display TODO item for developer
show_info = True # -qq Display app's informational status and results for end-users
show_heading = True # -q Don't display step headings before attempting actions
show_verbose = True # -v Display technical program run conditions
show_trace = True # -vv Display responses from API calls for debugging code
show_secrets = False # Never show
show_sys_info = True
show_config = True # not used?
use_flask = True # -flask
# SECTION 05. Use CLI menu to control program operation
# See https://wilsonmar.github.io/python-samples/#ParseArguments
def do_clear_cli():
if clear_cli:
import os
# QUESTION: What's the output variable?
lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')
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(f"Hello!")
# Test by running: ./python-examples.py --help
# SECTION 06: Define utilities for printing (in color with emojis)
# See https://wilsonmar.github.io/python-samples/#PrintColors
# QUESTION: How to pull in text_in containing {}.
class bcolors: # ANSI escape sequences:
BOLD = '\033[1m' # Begin bold text
UNDERLINE = '\033[4m' # Begin underlined text
HEADING = '\033[37m' # [37 white
FAIL = '\033[91m' # [91 red
ERROR = '\033[91m' # [91 red
WARNING = '\033[93m' # [93 yellow
INFO = '\033[92m' # [92 green
VERBOSE = '\033[95m' # [95 purple
TRACE = '\033[96m' # [96 blue/green
# [94 blue (bad on black background)
CVIOLET = '\033[35m'
CBEIGE = '\033[36m'
CWHITE = '\033[37m'
RESET = '\033[0m' # switch back to default color
def print_separator():
""" A function to put a blank line in CLI output. Used in case the technique changes throughout this code. """
print(" ")
def print_heading(text_in):
if show_heading:
if str(show_dates_in_logs) == "True":
print('\n***', get_log_datetime(), bcolors.HEADING+bcolors.UNDERLINE,f'{text_in}', bcolors.RESET)
else:
print('\n***', bcolors.HEADING+bcolors.UNDERLINE,f'{text_in}', bcolors.RESET)
def print_fail(text_in): # when program should stop
if show_fail:
if str(show_dates_in_logs) == "True":
print('***', get_log_datetime(), bcolors.FAIL, "FAIL:", f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.FAIL, "FAIL:", f'{text_in}', bcolors.RESET)
def print_error(text_in): # when a programming error is evident
if show_fail:
if str(show_dates_in_logs) == "True":
print('***', get_log_datetime(), bcolors.ERROR, "ERROR:", f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.ERROR, "ERROR:", f'{text_in}', bcolors.RESET)
def print_warning(text_in):
if show_warning:
if str(show_dates_in_logs) == "True":
print('***', get_log_datetime(), bcolors.WARNING, f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.WARNING, f'{text_in}', bcolors.RESET)
def print_todo(text_in):
if show_todo:
if str(show_dates_in_logs) == "True":
print('***', get_log_datetime(), bcolors.CVIOLET, "TODO:", f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.CVIOLET, "TODO:", f'{text_in}', bcolors.RESET)
def print_info(text_in):
if show_info:
if str(show_dates_in_logs) == "True":
print('***', get_log_datetime(), bcolors.INFO+bcolors.BOLD, f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.INFO+bcolors.BOLD, f'{text_in}', bcolors.RESET)
def print_verbose(text_in):
if show_verbose:
if str(show_dates_in_logs) == "True":
print('***', get_log_datetime(), bcolors.VERBOSE, f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.VERBOSE, f'{text_in}', bcolors.RESET)
def print_trace(text_in): # displayed as each object is created in pgm:
if show_trace:
if str(show_dates_in_logs) == "True":
print('***',get_log_datetime(), bcolors.TRACE, f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.TRACE, f'{text_in}', bcolors.RESET)
def print_secret(secret_in):
""" Outputs 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
if str(show_dates_in_logs) == "True":
now_utc=datetime.now(timezone('UTC'))
print('*** ',now_utc,bcolors.CBEIGE, "SECRET: ", f'{secret_in}', bcolors.RESET)
else:
print('***', bcolors.CBEIGE, "SECRET: ", f'{secret_in}', bcolors.RESET)
else:
# same length regardless of secret length to reduce ability to guess:
secret_len = 32
if len(secret_in) >= 20: # slice
secret_out = secret_in[0:4] + "."*(secret_len-4)
else:
secret_out = secret_in[0:4] + "."*(secret_len-1)
if str(show_dates_in_logs) == "True":
print('***', get_log_datetime(), bcolors.WARNING, f'{text_in}', bcolors.RESET)
else:
print('***', bcolors.CBEIGE, " SECRET: ", f'{secret_out}', bcolors.RESET)
# SECTION 07. Functions to manage data storage folders and files
# See https://wilsonmar.github.io/python-samples/#FileMgmt
def dir_remove(dir_path):
if os.path.exists(dir_path):
shutil.rmtree(dir_path) # deletes a directory and all its contents.
# os.remove(img_file_path) # single file
# Alternative: Path objects from the Python 3.4+ pathlib module also expose these instance methods:
# pathlib.Path.unlink() # removes a file or symbolic link.
# pathlib.Path.rmdir() # removes an empty directory.
def dir_tree(startpath):
# Thanks to
# https://stackoverflow.com/questions/9727673/list-directory-tree-structure-in-python
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 4 * (level)
print_trace('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level + 1)
for f in files:
print_trace('{}{}'.format(subindent, f))
# TODO: Hint that this returns list data type:
def about_disk_space():
statvfs = os.statvfs(".")
# Convert to bytes, multiply by statvfs.f_frsize and divide for Gigabyte
# representation:
GB = 1000000
disk_total = ((statvfs.f_frsize * statvfs.f_blocks) /
statvfs.f_frsize) / GB
disk_free = ((statvfs.f_frsize * statvfs.f_bfree) / statvfs.f_frsize) / GB
# disk_available = ((statvfs.f_frsize * statvfs.f_bavail ) / statvfs.f_frsize ) / GB
disk_list = [disk_total, disk_free]
return disk_list
# This returns date object:
def file_creation_date(path_to_file, my_os_platform):
"""
Get the datetime stamp that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
WARNING: Use of epoch time means resolution is to the seconds (not microseconds)
"""
if path_to_file is None:
print_trace("path_to_file="+path_to_file)
# print_trace("platform.system="+platform.system())
if platform.system() == 'Windows':
return os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
return stat.st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
return stat.st_mtime
def file_remove(file_path):
if os.path.exists(file_path):
os.remove(file_path) # deletes a directory and all its contents.
# TODO: Create, navigate to, and remove local working folders:
# SECTION 08. Obtain program enviornment metadata
# See https://wilsonmar.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):
""" Returns 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 = {
'22.7': ['Next2024', 2024, '24'],
'22.6': ['macOS Sonoma', 2023, '23'],
'22.5': ['macOS Ventura', 2022, '13'],
'12.1': ['macOS Monterey', 2021, '21'],
'11.1': ['macOS Big Sur', 2020, '20'],
'10.15': ['macOS Catalina', 2019, '19'],
'10.14': ['macOS Mojave', 2018, '18'],
'10.13': ['macOS High Sierra', 2017, '17'],
'10.12': ['macOS Sierra', 2016, '16'],
'10.11': ['OS X El Capitan', 2015, '15'],
'10.10': ['OS X Yosemite', 2014, '14'],
'10.9': ['OS X Mavericks', 2013, '10.9'],
'10.8': ['OS X Mountain Lion', 2012, '10.8'],
'10.7': ['OS X Lion', 2011, '10.7'],
'10.6': ['Mac OS X Snow Leopard', 2008, '10.6'],
'10.5': ['Mac OS X Leopard', 2007, '10.5'],
'10.4': ['Mac OS X Tiger', 2005, '10.4'],
'10.3': ['Mac OS X Panther', 2004, '10.3'],
'10.2': ['Mac OS X Jaguar', 2003, '10.2'],
'10.1': ['Mac OS X Puma', 2002, '10.1'],
'10.0': ['Mac OS X Cheetah', 2001, '10.0'],
}
# WRONG: On macOS Monterey, platform.mac_ver()[0]) returns "10.16", which is Big Sur and thus wrong.
# See https://eclecticlight.co/2020/08/13/macos-version-numbering-isnt-so-simple/
# and https://stackoverflow.com/questions/65290242/pythons-platform-mac-ver-reports-incorrect-macos-version/65402241
# and https://docs.python.org/3/library/platform.html
# So that is not a reliable way, especialy for Big Sur
# https://bandit.readthedocs.io/en/latest/blacklists/blacklist_imports.html#b404-import-subprocess
# import subprocess # built-in
# from subprocess import PIPE, run
# p = subprocess.Popen("sw_vers", stdout=subprocess.PIPE)
# result = p.communicate()[0]
macos_platform_release = platform.release()
# Alternately:
release = '.'.join(release_in.split(".")[:2]) # ['10', '15', '7']
macos_info = MACOS_VERSIONS[release] # lookup for ['Monterey', 2021]
print_trace("macos_info="+str(macos_info))
print_trace("macos_platform_release="+macos_platform_release)
return macos_platform_release
def sys_info():
if not show_sys_info: # defined among CLI arguments
return None
print_heading("In sys_info()")
# print_trace("env_file="+env_file)
print_trace("user_home_dir_path="+user_home_dir_path)
# the . in .secrets tells Linux that it should be a hidden file.
import platform # https://docs.python.org/3/library/platform.html
platform_system = platform.system()
# 'Linux', 'Darwin', 'Java', 'Win32'
print_trace("platform_system="+str(platform_system))
# my_os_platform=localize_blob("version")
print_trace("my_os_version="+str(platform.release()))
# " = "+str(macos_version_name(my_os_version)))
my_os_process = str(os.getpid())
print_trace("my_os_process="+my_os_process)
display_memory()
# or socket.gethostname()
my_platform_node = platform.node()
print_trace("my_platform_node="+my_platform_node)
my_os_uname = str(os.uname())
print_trace("my_os_uname="+my_os_uname)
# MacOS version=%s 10.14.6 # posix.uname_result(sysname='Darwin',
# nodename='NYC-192850-C02Z70CMLVDT', release='18.7.0', version='Darwin
# Kernel Version 18.7.0: Thu Jan 23 06:52:12 PST 2020;
# root:xnu-4903.278.25~1/RELEASE_X86_64', machine='x86_64')
pwuid_shell = pwd.getpwuid(os.getuid()).pw_shell # like "/bin/zsh" on MacOS
# preferred over os.getuid())[0]
# Instead of: conda install psutil # found
# import psutil
# machine_uid_pw_name = psutil.Process().username()
print_trace("pwuid_shell="+pwuid_shell)
# Obtain machine login name:
# This handles situation when user is in su mode.
# See https://docs.python.org/3/library/pwd.html
pwuid_gid = pwd.getpwuid(os.getuid()).pw_gid # Group number datatype
print_trace("pwuid_gid="+str(pwuid_gid)+" (process group ID number)")
pwuid_uid = pwd.getpwuid(os.getuid()).pw_uid
print_trace("pwuid_uid="+str(pwuid_uid)+" (process user ID number)")
pwuid_name = pwd.getpwuid(os.getuid()).pw_name
print_trace("pwuid_name="+pwuid_name)
pwuid_dir = pwd.getpwuid(os.getuid()).pw_dir # like "/Users/johndoe"
print_trace("pwuid_dir="+pwuid_dir)
# Several ways to obtain:
# See https://stackoverflow.com/questions/4152963/get-name-of-current-script-in-python
# this_pgm_name = sys.argv[0] # = ./python-samples.py
# this_pgm_name = os.path.basename(sys.argv[0]) # = python-samples.py
# this_pgm_name = os.path.basename(__file__) # = python-samples.py
# this_pgm_path = os.path.realpath(sys.argv[0]) # = python-samples.py
# Used by display_run_stats() at bottom:
this_pgm_name = os.path.basename(os.path.normpath(sys.argv[0]))
print_trace("this_pgm_name="+this_pgm_name)
this_pgm_last_commit = __last_commit__
# Adapted from https://www.python-course.eu/python3_formatted_output.php
print_trace("this_pgm_last_commit="+this_pgm_last_commit)
this_pgm_os_path = os.path.realpath(sys.argv[0])
print_trace("this_pgm_os_path="+this_pgm_os_path)
# Example: this_pgm_os_path=/Users/wilsonmar/github-wilsonmar/python-samples/python-samples.py
site_packages_path = site.getsitepackages()[0]
print_trace("site_packages_path="+site_packages_path)
this_pgm_last_modified_epoch = os.path.getmtime(this_pgm_os_path)
print_trace("this_pgm_last_modified_epoch="+str(this_pgm_last_modified_epoch))
#this_pgm_last_modified_datetime = datetime.fromtimestamp(
# this_pgm_last_modified_epoch)
#print_trace("this_pgm_last_modified_datetime=" +
# str(this_pgm_last_modified_datetime)+" (local time)")
# Default like: 2021-11-20 07:59:44.412845 (with space between date & time)
# Obtain to know whether to use new interpreter features:
python_ver = platform.python_version()
# 3.8.12, 3.9.16, etc.
print_trace("python_ver="+python_ver)
# python_info():
python_version = no_newlines(sys.version)
# 3.9.16 (main, Dec 7 2022, 10:16:11) [Clang 14.0.0 (clang-1400.0.29.202)]
# 3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]
print_trace("python_version="+python_version)
print_trace("python_version_info="+str(sys.version_info))
# Same as on command line: python -c "print_trace(__import__('sys').version)"
# 2.7.16 (default, Mar 25 2021, 03:11:28)
# [GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc-
if sys.version_info.major == 3 and sys.version_info.minor <= 6:
# major, minor, micro, release level, and serial: for sys.version_info.major, etc.
# Version info sys.version_info(major=3, minor=7, micro=6,
# releaselevel='final', serial=0)
print_fail("Python 3.6 or higher is required for this program. Please upgrade.")
sys.exit(1)
venv_base_prefix = sys.base_prefix
venv_prefix = sys.prefix
if venv_base_prefix == venv_prefix:
print_trace("venv at " + venv_base_prefix)
else:
print_fail("venv is different from venv_prefix "+venv_prefix)
print_trace("__name__="+__name__) # = __main__
# TODO: Make this function for call before & after run:
# disk_list = about_disk_space()
# disk_space_free = disk_list[1]:,.1f / disk_list[0]:,.1f
# print_info(localize_blob("Disk space free")+"="+disk_space_free+" GB")
# left-to-right order of fields are re-arranged from the function's output.
def no_newlines(in_string):
""" Strip new line from in_string
"""
return ''.join(in_string.splitlines())
# SECTION 09. Obtain run control data from .env file (in the user's $HOME folder)
# See https://wilsonmar.github.io/python-samples/#envFile
def open_env_file(env_file) -> str:
"""Return a Boolean obtained from .env file based on key provided.
"""
from pathlib import Path
# See https://wilsonmar.github.io/python-samples#run_env
global user_home_dir_path
user_home_dir_path = str(Path.home())
# example: /users/john_doe
global_env_path = user_home_dir_path + "/" + env_file # concatenate path
# PROTIP: Check if .env file on global_env_path is readable:
if not os.path.isfile(global_env_path):
print_error(global_env_path+" (global_env_path) not found!")
#else:
# print_info(global_env_path+" (global_env_path) readable.")
path = pathlib.Path(global_env_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_trace("env_file="+env_file)
#print_trace("user_home_dir_path="+user_home_dir_path)
#def last_mod_datetime(env_file) -> str:
"""
Return a Boolean obtained from .env file based on key provided.
"""
# Using import datetime import pathlib
# Instead of global_env_path_time = file_creation_date(global_env_path, my_os_platform)
# From https://www.geeksforgeeks.org/how-to-get-file-creation-and-modification-date-or-time-in-python/
# path = pathlib.Path(global_env_path)
# timestamp = path.stat().st_mtime
#dt = _datetime.datetime.utcfromtimestamp(timestamp)
# dt = datetime.utcfromtimestamp(timestamp)
# Z = UTC with no time zone
# formatted = dt.strftime('%A %d %b %Y %I:%M:%S %p Z')
# print_verbose(global_env_path+" last modified " + formatted)
# get creation time on windows
# current_timestamp = path.stat().st_ctime
# WARNING: Don't change the system's locale setting within a Python program because
# locale is global and affects other applications.
return True
def get_bool_from_env_file(key_in) -> bool:
"""Return a True/False boolean value data type from OS environment or .env file
(using pip python-dotenv)
See https://how.wtf/read-environment-variables-from-file-in-python.html
"""
env_var = os.environ.get(key_in)
if not env_var:
print_warning(key_in + " not found in OS nor .env file: " + ENV_FILE)
return None
else:
print_trace(key_in + "=" + str(env_var) + " from .env")
return env_var # bool
def get_str_from_env_file(key_in) -> str:
"""Return a value of string data type from OS environment or .env file
(using pip python-dotenv)
"""
env_var = os.environ.get(key_in)
if not env_var: # yes, defined=True, use it:
print_warning(key_in + " not found in OS nor .env file: " + ENV_FILE)
return None
else:
# PROTIP: Display only first 15 characters of a potentially secret long string:
if len(env_var) > 10:
print_trace(key_in + "=\"" + str(env_var[:10]) +" (remainder removed)")
else:
print_trace(key_in + "=\"" + str(env_var) + "\" from .env")
return str(env_var)
def get_secret_from_env_file(key_in) -> str:
"""Return a secret value of string data type from OS environment or .env file
(using pip python-dotenv)
"""
env_var = os.environ.get(key_in) # using pip python-dotenv
if not env_var: # yes, defined=True, use it:
print_warning(key_in + " not found in OS nor .env file " + ENV_FILE)
return None
else:
print_trace(key_in + " (secret) retrieved from .env")
return str(env_var)
def get_int_from_env_file(key_in) -> int:
"""Return an integer number data type from OS environment or .env file
(using pip python-dotenv)
"""
env_var = os.environ.get(key_in) # using pip python-dotenv
if not env_var: # yes, defined=True, use it:
print_warning(key_in+" not found in OS nor .env file " + ENV_FILE)
print_warning(key_in+" set to default False=0 ")
env_var=0
if str(env_var) == "False":
print_trace(key_in + "=False=0 from .env")
return 0
elif str(env_var) == "True":
print_trace(key_in + "=True=100 from .env")
return 100
elif int(env_var) > 100:
print_trace(key_in + "= 100, fix of " + str(env_var) + " from .env")
return 100
else:
print_trace(key_in + "=" + str(env_var) + " from .env")
return int(env_var)
# ffff
def get_float_from_env_file(key_in) -> float:
"""Return a floating-point number data type from OS environment or .env file
(using pip python-dotenv)
"""
env_var = os.environ.get(key_in) # using pip python-dotenv
# print("get_float DEBUGGING : env_var"+str(type(env_var))+"="+str(env_var))
if not env_var: # yes, defined=True, use it:
print_warning(key_in + " not found in OS nor .env file " + ENV_FILE)
return None
else:
print_trace(key_in + "=" + env_var + " from .env")
return float(env_var)
def read_env_file():
"""Read .env file containing variables and values.
See https://wilsonmar.github.io/python-samples/#envLoad
"""
# wait to display until vars are read in:
# print_heading("In read_env_file()")
# See https://stackoverflow.com/questions/40216311/reading-in-environment-variables-from-an-environment-file
global show_dates_in_logs
show_dates_in_logs = get_bool_from_env_file('show_dates_in_logs')
if show_dates_in_logs == None:
show_dates_in_logs = False
print_warning("show_dates_in_logs="+str(show_dates_in_logs)+" from default!")
global show_logging
show_logging = get_bool_from_env_file('show_logging')
if show_logging == None:
show_logging = True
print_warning("show_logging="+str(show_logging)+" from default!")
global show_heading
show_heading = get_bool_from_env_file('show_heading')
if show_heading == None:
show_heading = False
print_warning("show_heading="+str(show_heading)+" from default!")
global show_fail
show_fail = get_bool_from_env_file('show_fail')
if show_fail == None:
show_fail = True
print_warning("show_fail="+str(show_fail)+" from default!")
global show_error
show_error = get_bool_from_env_file('show_error')
if show_error == None:
show_error = True
print_warning("show_error="+str(show_error)+" from default!")
global show_warning
show_warning = get_bool_from_env_file('show_warning')
if show_warning == None:
show_warning = True
print_warning("show_warning="+str(show_warning)+" from default!")
global show_todo
show_todo = get_bool_from_env_file('show_todo')
if show_todo == None:
show_todo = True
print_warning("show_todo="+str(show_todo)+" from default!")
global show_info
show_info = get_bool_from_env_file('show_info')
if show_info == None:
show_info = True
print_warning("show_info="+str(show_info)+" from default!")
global show_verbose
show_verbose = get_bool_from_env_file('show_verbose')
if show_verbose == None:
show_verbose = False
print_warning("show_verbose="+str(show_verbose)+" from default!")
global show_trace
show_trace = get_bool_from_env_file('show_trace')
if show_trace == None:
show_trace = False
print_warning("show_trace="+str(show_trace)+" from default!")
global show_secrets
show_secrets = get_bool_from_env_file('show_secrets')
if show_secrets == None:
show_secrets = False
print_warning("show_secrets="+str(show_secrets)+" from default!")
global show_sys_info
show_sys_info = get_bool_from_env_file('show_sys_info')
if show_sys_info == None:
show_sys_info = True
print_warning("show_sys_info="+str(show_sys_info)+" from default!")
global show_print_samples
show_print_samples = get_bool_from_env_file('show_print_samples')
if show_print_samples == None:
show_print_samples = True
print_warning("show_print_samples="+str(show_print_samples)+" from default!")
global main_loop_runs_requested
main_loop_runs_requested = get_int_from_env_file('main_loop_runs_requested')
if main_loop_runs_requested == None:
# PROTIP: Define a data type at creation so it can contain a large number?
main_loop_runs_requested=int(1)
print_warning("main_loop_runs_requested="+str(main_loop_runs_requested)+" "+str(type(main_loop_runs_requested))+" from default!")
global main_loop_pause_seconds
main_loop_pause_seconds = get_float_from_env_file('main_loop_pause_seconds')
print("get_float DEBUGGING : main_loop_pause_seconds"+str(type(main_loop_pause_seconds))+"="+str(main_loop_pause_seconds))
if main_loop_pause_seconds == None:
main_loop_pause_seconds=float(0.0)
print_warning("main_loop_pause_seconds="+str(main_loop_pause_seconds)+" "+str(type(main_loop_pause_seconds))+" from default!")
global main_loop_run_pct
main_loop_run_pct = get_int_from_env_file('main_loop_run_pct')
if main_loop_run_pct == None:
main_loop_run_pct = 100
print_warning("main_loop_run_pct="+str(main_loop_run_pct)+" from default!")
# NOTE: Country code can also come from IP Address lookup
# "US" # For use in whether to use metric
global my_country
my_country = get_str_from_env_file('MY_COUNTRY')
if my_country == None:
my_country = "US"
print_warning("my_country="+str(my_country)+" from default!")
# CAUTION: PROTIP: LOCALE values are different on Windows than Linux/MacOS
# "ar_EG", "ja_JP", "zh_CN", "zh_TW", "hi" (Hindi), "sv_SE" #sweden/Swedish
global my_locale
my_locale = get_str_from_env_file('MY_LOCALE') # for translation
if my_locale == None:
# TODO: my_locale = locale_from_env
# print_verbose("my_locale="+my_locale+" from system.")
#else:
my_locale = "en_US"
print_warning("LOCALE="+my_locale+" from default!")
global my_encoding
my_encoding = get_str_from_env_file('MY_ENCODING') # "UTF-8"
if my_encoding == None:
my_encoding = "UTF-8"
print_warning("my_encoding="+my_encoding+" from default!")
global my_tz_name_from_env
my_tz_name_from_env = get_str_from_env_file('MY_TIMEZONE_NAME')
if my_tz_name_from_env == None:
my_tz_name = my_tz_name_from_env
else:
# Get time zone code from local operating system:
# import datetime # for Python 3.6+
#my_tz_name = str(_datetime.datetime.utcnow().astimezone().tzinfo)
# TODO: Fi _datetime
my_tz_name="whatever"
#my_tz_name = str(datetime.utcnow().astimezone().tzinfo)
# _datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo
# = "MST" for U.S. Mountain Standard Time, or 'Asia/Kolkata'