Skip to content

Instantly share code, notes, and snippets.

@jlant
Last active April 19, 2019 14:26
Show Gist options
  • Save jlant/908eec0c894b170a6972 to your computer and use it in GitHub Desktop.
Save jlant/908eec0c894b170a6972 to your computer and use it in GitHub Desktop.
Python - small snippets and commands.

Python reference

The Zen of Python

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.  
Sparse is better than dense
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Shebang

Use the following shebang because the program /usr/bin/env can be used to "activate" the desired command without a full path. Otherwise, the full path of the Python interpreter must be specified, which can vary on different computers. If the Python interpreter is in /usr/bin/python or in /usr/local/bin/python or in your home directory, using the following will work:

#!/usr/bin/env python

Create a distribution file

$ python3 setup.py sdist
  • sdist is the source distribution
  • in the setup.py file, you need a list of *.py files to include in package
    • py_modules = ["file1", "file2", ...]

Install package with pip - puts your package in your Python distributions site-packages directory

$ sudo
$ sudo python3 -m pip install <your-tar-gzipped-package>.tar.gz

Testing with py.test

Run tests in verbose mode and allow printing to console from within your tests

$ py.test -vs tests_dir/

Run test on specific function

$ py.test -v tests_dir/test_module::test_function

Using pep8

$ py.test --pep8 <your-code>.py

Start a simple builtin HTTP web server in port 8000

$ python -m http.server

Open browser and go to

http://127.0.0.1:8000/

or

http://192.168.1.2:8000

Start a simple builtin HTTP web server in port 8080 (Python 2.7)

$ python -m SimpleHTTPServer 8080

Start a virtual environment and activate the environment

$ virtualenv venv
$ source venv/bin/activate

Start a virtual environment using Python3

$ virtualenv -p python3 venv

$ ls venv/lib/
python3.4

$ source venv/bin/activate

(venv)
$ python --version
Python 3.4.0

PyQt4, QtDesigner, and pyuic4

Compile a user interface file from QtDesigner to python file using pyuic4 from PyQt4.

$ pyuic4 my_ui.ui -o my_ui.py

Requests library - download a USGS water data file

import requests

url = "http://waterdata.usgs.gov/nwis/dv?cb_00060=on&format=rdb&site_no=03287500&referred_module=sw&period=&begin_date=2014-06-12&end_date=2015-06-12"
filename = "usgs-discharge.txt"

# have requests get the data file
r = requests.get(url)

# save requests content to a file if status is ok, otherwise raise status exception
if r.status_code == requests.codes.ok:
    with open(filename, "w") as f:
        f.write(r.text)
        print("Downloaded data and saved as: {}".format(filename))

else:
    r.raise_for_status()

Sphinx

Adding links to other functions and classes within docstring

:func:`some_function`

:class:`some class`

See also and warning in docstring

.. seealso::
   :class:`~gagepy.parameter.Parameter`  # the link will only show Parameter and not the dot notation
   
.. warning::
   Some warning!

Code example in docstring

>>> print("Hello there!")

is_numeric() function

def is_numeric(value):
    try:
        float(value)
        return True
    except ValueError:
        return False

print("Is numeric?")
print("{}    {}").format("dog", is_numeric("hello"))
print("{}    {}").format(500, is_numeric(500))
print("{}    {}").format("3.5", is_numeric("3.5"))

Automatically assign kwargs in class instantiation using setattr

def __init__(self, name, **kwargs):
    self.name = name
    for key, value in kwargs.items():
        setattr(self, key, value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment