====== Python ======
"Eventually I got better -- I started making my own mistakes."
Fun reason to learn Python:- \\
[[https://www.4dbrix.com/documentation/python/]]
Python Game:- \\
https://www.twilio.com/quest
Rather more serious tutorial:- \\
[[https://docs.python.org/3/tutorial/]]
[[python:flask|Flask application framework]] \\
===== Install pip3 =====
# apt-cache search python3-pip
python3-pip - Python package installer
root@sysmgmt:~# apt-get install python3-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
binutils binutils-common binutils-x86-64-linux-gnu b
...edited...
===== Data Structures =====
[[python:python-data-struct|Python Data Structures]]
===== Python Code =====
[[python:python-code|Python code snippets]]
===== Print Formatting =====
>>> print ("this is a {LENGTH} {STRING} print").format(LENGTH='short', STRING='test')
this is a short test print
>>>
print("Creating '{}' role in account '{}'".format(role_name, event["account_id"]))
===== Date Time =====
from datetime import datetime
print("now", datetime.now().replace(microsecond=0))
now 2023-09-12 12:44:22
With format string:-
from datetime import datetime
raw_time = datetime.now().replace(microsecond=0)
now = raw_time.strftime("%d/%m/%Y %H:%M:%S")
Gives:- "04/10/2023 16:37:43"
===== Virtual Environment =====
python3 -m venv
eg.
$ python3 -m venv stuff-env
# EACH time you will need to run this to avtivate the virtual env:-
$ source stuff-env/bin/activate
(stuff-env) $
''pip freeze'' shows current modules, so echo this to ''requirements.txt'' to automatically load modules
pip freeze > requirements.txt
To quit the venv, use ''deactivate'' command (which venv adds to your path)
$ deactivate
$
===== requirements.txt file =====
Specific versions of packages can be installed from a ''requirements.txt'' file, this avoids pip installing a module in a venv which is a later release than the code was written for:-
$ cat requirements.txt
Jinja2==2.11.2
PyYAML==3.13
SQLAlchemy==1.3.16
$ pip install -r requirements.txt
===== Comments =====
[[https://realpython.com/python-comments-guide/]]\\
===== json.dumps =====
print(json.dumps(clusterinfo))
produced the following error because of 'LastModified': datetime.datetime(2021, 8, 10, 12, 59, 25, tzinfo=tzutc()):-
TypeError: Object of type datetime is not JSON serializable
Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.
Solution is to apply a default convert to str for anything unknown. But this will create an issue getting date.time string back to a date,time type obect.
print(json.dumps(clusterinfo, indent=4, sort_keys=True, default=str))