Python - tlam/Wiki GitHub Wiki
-
Check a unicode name
import unicodedata unicodedata.name(u'\u00c3') unicodedata.name(u'\u00a9')
-
Check substring in string
if 'Hi' in 'Hi There': print 'Success!'
-
gaierror
socket.gaierror: [Errno -2] Name or service not known
Make sure that your ethernet or wireless is connected to the network or internet.
-
Tracing a script
python -m trace --trace test.py
-
Profile module not present
sudo apt-get install python-profiler
-
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')
-
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())
-
String format number of decimal places:
>>> '{:.2f}'.format(3.145678) '3.14'
-
String format date:
>>> from datetime import datetime >>> '{:%Y-%m-%d}'.format(datetime.now()) '2013-11-28'
-
Rounding up to 2dp:
import math value = 416.325 print(math.ceil(value * 100) / 100.00) # 416.33
Commands
-
Install into a specific python version
easy_install-2.6 south
virtualenv
-
sudo apt-get install python-pip
-
sudo pip install virtualenv
-
sudo pip install virtualenvwrapper
-
Update your environment with the following,
.bashrc
or.bash_profile
:export WORKON_HOME=$HOME/.virtualenvs source /usr/local/bin/virtualenvwrapper.sh
-
Create
$HOME/.virtualenvs
-
Create your
dev
environment:mkvirtualenv dev
-
Alternate way to activate
source .virtualenvs/django/bin/activate
-
Create a virtualenv with python3 bin inside it
mkvirtualenv -p `which python3` apython3virtualenv
pip
-
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
-
Run a specific test in file
test_something.py
with classTestSomething
specific testtest_somewhere
:nosetests test_something:TestSomething.test_somewhere
-
Remove print suppression:
nosetests --nocapture test_something:TestSomething.test_somewhere nosetests -s test_something:TestSomething.test_somewhere
pep8
-
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
-
Use Python OpenSSL
pip install pyopenssl ndg-httpsclient pyasn1
-
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
-
-
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.