Date created: 09/07/18 09:36:37. Last modified: 05/23/21 10:13:52

--Python Notes--

Help:

Import a module in order to load it's help text:


>>> import json
>>> help(json)

Help on package json:
NAME
json
MODULE REFERENCE
https://docs.python.org/3.6/library/json
...
DESCRIPTION
JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.

>>> help(json.loads)
Help on function loads in module json:

loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
containing a JSON document) to a Python object.

 

Linting:

https://black.readthedocs.io/en/stable/

 

Modules:

Get the module path/location:

>>> import google.protobuf
>>> google.protobuf.__file__
'/home/bensley/.local/lib/python3.6/site-packages/google/protobuf/__init__.py'

>>> import google.protobuf
>>> import inspect
>>> inspect.getfile(google.protobuf)
'/home/bensley/.local/lib/python3.6/site-packages/google/protobuf/__init__.py'

 

Paths:

What is the current script name and location (__file__ doesn't exist in an interactive shell but 'os.getcwd()' will work):

$ cat path.py 
#!/usr/bin/env python3
import os
print(os.getcwd())
print(__file__)

$ ./path.py
/home/bensley/Python
./path.py

 

Pip:

List installed packages with:

pip3 freeze

or

pip3 list

 

Upgrade pip:

sudo -H pip3 install --upgrade pip

or

sudo -H pip install --upgrade pi

On Mac with brew installed Python3:

/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 -m pip install --upgrade pip

 

Python Guides:

https://github.com/crazyguitar/pysheeet

https://treyhunner.com/2019/05/python-builtins-worth-learning/

 

Style Guides:

https://google.github.io/styleguide/pyguide.html

https://github.com/google/styleguide/blob/gh-pages/pyguide.md

 

venv:

$ sudo apt-get install virtualenv
$ virtualenv -p `which python3` v1
$ cd v1/
$ source bin/activate
...
$ deactivate

 

Testing a specific branch in a venv:

$ mkdir napalm-text
$ git clone -b confirm_username_fix https://github.com/napalm-automation/napalm.git ./napalm-text/
$ cd napalm-text/
$ virtualenv -p `which python3` ./
$ source bin/activate
$ sudo -H pip3 install ./
...
$ deactivate
$ cd ../
$ rm -rf napalm-text/

 


Previous page: Problem 20
Next page: Basic Netmiko Example