這是一個系列文章,主要分享python的使用建議和技巧,每次分享3點,希望你能有所收穫。
1 排列組合
示例程序:
#!/usr/bin/env python
# coding=utf8
import itertools
for p in itertools.permutations('ABC', 2):
print p
'''
('A', 'B')
('A', 'C')
('B', 'A')
('B', 'C')
('C', 'A')
('C', 'B')
'''
for c in itertools.combinations('ABC', 2):
print c
'''
('A', 'B')
('A', 'C')
('B', 'C')
'''
通過itertools模塊,可以很方便實現元素的排列和組合。由示例中可以看到,分別從ABC三個字母中取2個字母,實現其排列和組合,itertools模塊還有很多有用功能,感興趣可以看看。
2 創建臨時文件
示例程序:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import tempfile
TEMP_FILE = tempfile.NamedTemporaryFile()
print 'temp file name: <{self.name}>\n'.format(self=TEMP_FILE)
with open(TEMP_FILE.name, 'w') as f:
f.write("line 1\nline 2\nline 3\n")
with open(TEMP_FILE.name) as f:
for line in f.readlines():
print line
運行示例:
$ python tmp_file_demo.py
temp file name: </tmp/tmpVSppeA>
line 1
line 2
line 3
$ ls /tmp/tmpVSppeA
ls: cannot access /tmp/tmpVSppeA: No such file or directory
藉助tempfile模塊,可以很方便的操作臨時文件。由示例中可以看到,創建的臨時文件/tmp/tmpVSppeA在使用完畢後會自動刪除,不需要手動刪除該文件,tempfile模塊還有很多有用功能,感興趣可以看看。
3 打印信息到標準錯誤
示例程序:
#!/usr/bin/env python
# coding=utf8
from __future__ import print_function
import sys
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
eprint("print to stderr")
print("print to stdout")
'''
print to stderr
print to stdout
'''
運行示例:
$ python print_stderr.py
print to stderr
print to stdout
$ python print_stderr.py > /tmp/stdout.log
print to stderr
$ python print_stderr.py 2> /tmp/stderr.log
print to stdout
$ python print_stderr.py > /tmp/stdout_and_stderr.log 2>&1
$ cat /tmp/stdout.log
print to stdout
$ cat /tmp/stderr.log
print to stderr
$ cat /tmp/stdout_and_stderr.log
print to stderr
print to stdout
通過導入future模塊的print_function,將print函數改造成python3的print,就可以實現將輸出打印到標準錯誤。由示例中可以看到,通過封裝一個新的函數eprint,實現類似print的打印功能,唯一區別就是eprint函數將輸出打印到標準錯誤,而不是標準輸出。