Python 命令
獲取 os.system(cmd)的執行結果
由於os.system是沒有返回值的,獲取返回值有以下三種方式:
1.使用commands內置模塊
import commands
resp = commands.getoutput("hostname")
2.使用os.popen獲取返回值
resp = os.popen('ps -ef | grep sssss').readlines()
3.使用subprocess內置模塊
from subprocess import Popen,PIPE
resp = Popen("ps -ef | grep sssss",shell=True,stdout=PIPE,stderr=PIPE).stdout.readlines()
print 同行替換輸出 輸出信息再同一行 進度條顯示
# python3
>>> import time
>>> for x in range(10):
... time.sleep(1)
... print("Progress {:2.1%}".format(x / 10), end="\r")
# 下列三行信息輸出在同一行
Progress 30.0%
Progress 50.0%
>>> ress 90.0%
# python2
import time
import sys
for x in range(5):
time.sleep(1)
msg = ">>>> %s\r"%str(x)
sys.stdout.write(msg)
sys.stdout.flush()
python 文件傳入 參數
#! /bin/python
import sys
for arg in sys.argv:
print arg
Python 生成 md5
import md5
src = 'this is a md5 test.'
m1 = md5.new()
m1.update(src)
print m1.hexdigest()
Excel 處理
在用 xlrd.open_workbook 時,添加對應的參數 formatting_info=True,就可以保留原有格式了
python 通過字符串調用對象屬性或方法的實例講解
# eval
def getmethod(x,char='just for test'):
return eval('str.%s' % x)(char)
In [635]: getmethod('upper')
Out[635]: 'JUST FOR TEST'
# getattr
In [650]: def getmethod2(x, char='just for test'):...:
return getattr(char, x)()...:
In [651]: getmethod2('upper')
Out[651]: 'JUST FOR TEST'
# 利用內置庫operator
In [648]: def getmethod3(x, char='just for test'):...:
return operator.methodcaller(x, char)(str)...:
In [649]: getmethod3('upper')
Out[649]: 'JUST FOR TEST'
使用 traceback 獲取棧信息
traceback.print_exc()
獲取詳細的程序異常信息。
程序運行異常時會輸出完整的棧信息,包括調用順序、異常發生的語句、錯誤類型等。
import tarceback
try:
f()
except IndexError as ex:
print “程序異常”
print ex
print traceback.print_exc()#1.錯誤類型(IndexError)、錯誤對應的值(list index out of range)、具體的 trace 信息(文件名 行號 函數名 對應的代碼)
sys.exc_info()
使用 dir 獲取模塊的方法 dir()
dir(traceback)