1. 一个字符串不是一个list,这和shell script中不一样。
list=s是错的
如果你想从字符串得到一个list:
list = s.strip().splitlines()
2. with:
so to open a file, process its contents, and make sure to close it,you can simply do:
with open("x.txt") as f:
data = f.read()
do something with data
3. property functions
@property
def foo(self)
return self.foo
Is equivalent to:
def foo(self)
return self.foo
foo = property(foo)
The common proper solution is to return self._foo, this way you illustrate that the actual variable is private and the only way to deal with it is via the property.
4. 使用()进行字符接续:
In [1]: cmd=('cat ok'
...: '|head')
In [2]: print cmd
cat ok|head
5. get basename of a long file path:
os.path.basename('c:/windows/desktop/python.py')
6. ["c" if not a else a]
a="y"
b=["c" if not a else a]
print b
output: ['y']
a=None
print b
output:['c']
7. is there a way to have a method on an ExposedAPI not be part of the api?
Answer: make it _private, also consider adding a @hidden decorator
8. Capture Error 18-- invalid cross-device link:
try:
os.makedirs(os.path.dirname(cache_loc))
os.link(file_location, cache_loc)
except OSError, err:
#errno 18 is Invalid cross-device link
if err.errno == 18:
shutil.copy(file_location, cache_loc)
9. get() function:
get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
所以在json file中其实没有get, 可以做如下应用:
import simplejson as json
f=open("imx51evk.json")
j=f.read()
js=json.loads(j)
In [7]: print js.get('image_type')
None
In [9]: print js.get('image_type', "ssh")
ssh
In [10]: print js.get(None, 'image_type')
image_type
10. Create a directory:
30 + if not os.path.exists(config.tempdir_host):
31 + os.makedirs(config.tempdir_host)
11. TypeError: super() argument 1 must be type, not classobj
http://stackoverflow.com/questions/489269/python-super-raises-typeerror-why
The reason is that super() only operates on new-style classes, which in the 2.x series means extending from object.
基类需要继承object,即:
class A(object):
pass
12. re.escape(pattern)
Escape all non-alphanumeric characters in pattern.
13. 条件运算符形式(三目)
python里的条件运算符形式如下:
a if cond else b
它的优先级仅次于赋值符号,是倒数第二低的
此外还有人建议一个条件运算符的替代形式:
cond and a or b
14. Use specific python version:
Like if you want to use python2.6 not 2.7, use:
PIP="$PYTHON_VER `which pip`"