Python

Python related commands that I frequently use

Click's Shell completion

eval "$(_POLICY_SENTRY_COMPLETE=source_zsh policy_sentry)"
# https://click.palletsprojects.com/en/7.x/bashcomplete/#activation

Convert list of strings to all lowercase

actions_list = [x.lower() for x in actions_list]

Lists

Sort list in alphabetical order:

mylist.sort()

Remove duplicates from list:

mylist = list(dict.fromkeys(mylist)) # remove duplicates

Count number of times a string appears in a list

list.count(x)
# returns the number of times x appears in a list
# http://docs.python.org/tutorial/datastructures.html#more-on-lists

Virtualenv

# Python 3
virtualenv --python=/usr/local/bin/python3 ./.venv
source .venv/bin/activate
# Python 2.7
virtualenv --python=/usr/local/bin/python2.7 ./.venv
source .venv/bin/activate

PyPi upload

From your code directory that contains the setup.py script:

## Pipenv
pipenv shell
pipenv install
## Create the package files
python3 -m pip install --upgrade setuptools wheel
python3 setup.py sdist bdist_wheel
## PyPi test server
python3 -m pip install --upgrade twine
python3 -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*
python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps policy_sentry
## PyPi Prod
python3 -m pip install --upgrade twine
python3 -m twine upload dist/*
python3 -m pip install policy_sentry

Pep8

# Show ONLY instances of missing-function-docstring
pylint policy_sentry --disable=all -e missing-function-docstring
# Show instances of everything EXCEPT missing-function-docstring
pylint policy_sentry --disable=all -e missing-function-docstring
# Pycodestyle and autopep8 seem like they don't address everything that can come up from Pylint. Still useful though
pycodestyle --quiet --statistics policy_sentry
autopep8 --in-place --aggressive --aggressive --select=E501 -r policy_sentry --max-line-length 120

Things to add

  • chomp

  • split

  • list comprehensions

Install python version with pyenv on Mac

See this GitHub issue: https://github.com/pyenv/pyenv/issues/1219

CFLAGS="-I$(xcrun --show-sdk-path)/usr/include" pyenv install -v 3.7.0