Skip to content

Instantly share code, notes, and snippets.

@githubutilities
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save githubutilities/1be6bf9a6e679353a543 to your computer and use it in GitHub Desktop.

Select an option

Save githubutilities/1be6bf9a6e679353a543 to your computer and use it in GitHub Desktop.
Python CheatSheet

Python Package Manager

The most comment package managers are pip and easy_install(replaced by its successor pip).

Python Development Isolation(Virtual Environment)

Python Modulation Design

By default, python module installed by pip is located in a site-packages folder(added to sys.path by default). Every time python wants to find a module, it looks in to sys.path.

Here is a snippet on adding module to sys.path:

import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), 'site-packages'))
# duplicated modules existed, use the following line instead to insert into the front of `sys.path`
# sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'site-packages'))

Python reflection

import sys
import inspect
# list all the fields and methods of `sys` object as a tuple
dir(sys)

# list all the fields and methods with their doc
inspect.getmembers(sys)
# list builtin function of `sys`
inspect.getmembers(sys.modules['os'], predicate=inspect.isbuiltin)

# try __dict__ property
sys.__dict__

# getting help
help(sys)

# using built-in functions
[method for method in dir(sys) if callable(getattr(sys, method))]

dir() and inspect.getmembers() include base class methods, while __dict__ does not.

Python sys module

# use `iteritems()` to avoid `too many value to unpack` ValueError because python can only unpack 5 values at most
[module for module, doc in sys.modules.iteritems()]

Python wsgi

wsgi(Python Web Server Gateway Interface) is a Python standard described by PEP(Python Enhancement Proposals). It's a python solution for ruby's rack.

Python in Terminal

add the following line to the header of python source file in order to run it on the terminal even without .py extension.

#!/usr/bin/python

or

#!/usr/bin/env python

this is considered better than the previous, because it uses python in the ENVIRONMENT variable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment