Technology/Python/Learn

Bootstrap

Pip

Pip is an excellent tool for installing new Python packages.

$ wget https://bootstrap.pypa.io/get-pip.py
$ python get-pip.py
$ pip install xxx # or
$ python -m pip install xxx

Ignore installed:

$ pip install --ignore-installed <package>

virtualenv

virtualenv is a tool to create isolated Python environment.

Install via pip:

$ pip install virtualenv

Create a virtual environment:

$ cd /path/to/virtualenvs
$ virtualenv my_env

virtualenvwrapper

virtualenvwrapper provides a set of commands beyond virtualenv.

Install via pip:

$ pip install virtualenvwrapper
$ export WORKON_HOME=~/.virtualenvs
$ source /path/to/virtualenvwrapper.sh

Create a virtual environment:

$ cd /path/to/virtualenvs
$ mkvirtualenv my_env

Work on a virtual envonment:

$ workon my_env

Strings

Format

Input and Output

  1. Python2
import sys

print >> sys.stderr, 'print >> sys.stderr'
sys.stderr.write('sys.stderr.write\n')
  1. Python3
from __future__ import print_function
import sys

print('print(, file=sys.stderr)', file=sys.stderr)

Functions

def f(x):
  return x**2

g = lambda x: x**2

h = lambda: g(8)

Modules

Import Dynamically

import imp

mod = imp.load_source("bar","./foo/bar.py")

Paths

Get Script’s Path

import os

print(os.path.realpath(__file__))
print(os.path.dirname(os.path.realpath(__file__)))

Add Path to sys.path

import sys

sys.path.append(path)
sys.path.insert(0, path)

Headers

Python Interpreter

#!/usr/bin/env python

Encoding

# -*- coding: utf-8 -*-

Arguments

argparse

import argparse

def main(args):
  print(args.file)

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('src', help='Source file')
  args = parser.parse_args()

  for arg in vars(args):
    print('{}: {}'.format(arg, getattr(args, arg)))

  main(args)