https://www.python.org/

Simple server

Serve current folder as webserver

1
$ python -m SimpleHTTPServer 8080
Reference:

Conditional operator

Normally in C we write:

1
int total += (foo == bar) ? foo : 0;

In python is look like:

1
total += foo if foo == bar else 0
Reference:

Detect Operating System

1
2
3
4
5
6
import platform

print platform.system()
"""
The output will be 'Linux', 'Windows', or 'Java'
"""
Reference:

Define your own module

1
2
3
4
5
6
7
8
#!/usr/bin/python
# Filename: foobar.py

def foo():
print "Hi, this is Foo"

def bar():
print "Hey, I'm Bar"

How to use?

1
2
3
4
5
#!/usr/bin/python
from foobar import foo, bar

foo()
bar()

Output will be

1
2
Hi, this is Foo
Hey, I'm Bar
Reference:

dump object

1
2
3
import pprint

pprint.pprint(obj);
Reference:

Parsing text with regex

This is equivalent to PHP: preg_match_all

1
2
3
4
import re

pattern = '(https?://\S+)'
urls = re.findall(pattern, text)
Reference:

Store chinese character in string

I had getting such an error:

1
SyntaxError: Non-ASCII character '\xe5' in file filename.py on line 13, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

Fortunately, I found a solution

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

Just have to add this line to the top of filename.py

Reference:

match all chinese character

1
2
3
4
5
6
7
import re

regex = re.compile(ur'([\u4e00-\ufaff]+)', re.UNICODE)
text = u'this is 中文 char'
matches = regex.findall(text)

print(matches[0])

output:

1
中文

NOTE: must indicate u in front of the string

Reference:

read content from web

1
2
3
4
import urllib

url = 'http://yoururl.com/'
content = urllib.urlopen(url).read()
Reference:

Loop through month

1
2
3
4
5
6
def month_year_iter(start_month, start_year, end_month, end_year):
ym_start= 12 * start_year + start_month - 1
ym_end= 12 * end_year + end_month - 1
for ym in range(ym_start, ym_end):
y, m = divmod(ym, 12)
yield y, m + 1
Reference:

datetime minus month

6 months ago

1
2
today = datetime.date.today()
until_date = today - relativedelta(months=6)
Reference:

Fabric

Store the bash command output in variable

1
2
3
4
5
from fabric.api import local

def foo(name):
result = local('cat file%s' % name, capture=True)
...

The output of the file will be stored in result variable.

Reference: