Python - tlam/Wiki GitHub Wiki

  1. Check a unicode name

     import unicodedata
     unicodedata.name(u'\u00c3')
     unicodedata.name(u'\u00a9')
    
  2. Check substring in string

     if 'Hi' in 'Hi There':
         print 'Success!'
    
  3. gaierror

     socket.gaierror: [Errno -2] Name or service not known
    

Make sure that your ethernet or wireless is connected to the network or internet.

  1. Tracing a script

     python -m trace --trace test.py
    
  2. Profile module not present

     sudo apt-get install python-profiler
    
  3. Set sys encoding to utf-8 on Python 2.7.5, OSX 10.8 in your virtualenv. Create .virtualenvs/compass/lib/python2.7/sitecustomize.py with:

     import sys
     sys.setdefaultencoding('utf-8')
    
  4. Printing JSON in the order the keys are originally ordered:

     import collections
     import json
     import pprint
    
     pprint.pprint(json.loads('{"hello": "world"}', object_pairs_hook=collections.OrderedDict).items())
    
  5. String format number of decimal places:

     >>> '{:.2f}'.format(3.145678)
     '3.14'
    
  6. String format date:

     >>> from datetime import datetime
     >>> '{:%Y-%m-%d}'.format(datetime.now())
     '2013-11-28'
    
  7. Rounding up to 2dp:

     import math
    
     value = 416.325
     print(math.ceil(value * 100) / 100.00)  # 416.33
    

Commands

  1. Install into a specific python version

     easy_install-2.6 south
    

virtualenv

  1. sudo apt-get install python-pip

  2. sudo pip install virtualenv

  3. sudo pip install virtualenvwrapper

  4. Update your environment with the following, .bashrc or .bash_profile:

     export WORKON_HOME=$HOME/.virtualenvs
     source /usr/local/bin/virtualenvwrapper.sh
    
  5. Create $HOME/.virtualenvs

  6. Create your dev environment:

     mkvirtualenv dev
    
  7. Alternate way to activate

     source .virtualenvs/django/bin/activate
    
  8. Create a virtualenv with python3 bin inside it

     mkvirtualenv -p `which python3` apython3virtualenv
    

pip

  1. Install requirements.txt

     pip install -r requirements.txt
    

    When installing from the requirements.txt, pip will download each package and build it. Once all the packages have been successfully downloaded and built will they all be installed in one go. If at any point, download failed or the build failed, none of the packages will be installed.

PyFlakes

PyFlakes is a great tool to clean up your code but it has some options lacking such as ignoring certain folders or warnings.

Nose

  1. Run a specific test in file test_something.py with class TestSomething specific test test_somewhere:

     nosetests test_something:TestSomething.test_somewhere
    
  2. Remove print suppression:

     nosetests --nocapture test_something:TestSomething.test_somewhere
     nosetests -s test_something:TestSomething.test_somewhere
    

pep8

  1. Ignoring a specific warning, for example E501 line too long (90 characters):

     pep8 --ignore=E501 models.py
    

SOAP with requests

from lxml import etree, objectify
import requests


def clean(content):
    root = objectify.fromstring(content)
    for elem in root.getiterator():
        i = elem.tag.find('}')
        if i >= 0:
            elem.tag = elem.tag[i + 1:]
    objectify.deannotate(root, cleanup_namespaces=True)
    return root

headers = {
    'Content-Type': 'text/xml; charset=utf-8',
    'SOAPAction': 'yoururl/YourAction',
}

url = 'soapurl'
msg = 'yourrequest'
response = requests.post(url, data=msg, headers=headers, verify=False)
root = clean(response.content)

SNI support for Python 2.7.3

SNI is currently only supported in Python 2.7.9 but we use 2.7.3

  1. Use Python OpenSSL

     pip install pyopenssl ndg-httpsclient pyasn1
    
    1. Additional dependency with the above, check if libffi-dev is installed:

       apt-cache policy libffi-dev
      

      If it is not present, you can install it with:

       sudo apt-get install libffi-dev
      
  2. Upgrade to latest requests 2.6.0 if your requests < 2.2.1

After installing all the above, python requests will use Python OpenSSL instead of the default SSL lib.