(1) os.system
僅在一個子終端運行系統命令,而不能獲取命令執行後的返回資訊
system(command) -> exit_status
Execute the command (a string) in a subshell.
04101419778.CHM bash doc books downloads Pictures python
all-20061022 Desktop Examples project tools
(2) os.popen
此方法不但執行指令也傳回執行後的訊息物件
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/ from a command returning a file object.
>>>tmp = os.popen('ls *.py').readlines()
Out[21]:
['dump_db_pickle.py ',
'dump_db_pickle_recs.py ',
'dump_db_shelve.py ',
'initdata.py ',
'__init__.py ',
'make_db_pickle.py ',
'make_db_pickleklerecs.. peopleinteract_query.py ',
'reader.py ',
'testargv.py ',
'teststreams.py ',
'update_db_pickle.py ',
'writer.py ']
好處在於賦予傳回的結果於一變量,便於程序的處理。
(3) 使用模組subprocess
>>> subprocess.call(["cmd", "arg1", "arg2"],shell=True)
:傳回
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
.wait()
(4) 使用模組commands
>>> import commands
>>> dir(commands)
['__all__', '_____ getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
'Wed Jun 10 19:39:57 CST 2009'
>>> >> commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')
注意: 當執行命令的參數或返回中包含了中文文字,那麼建議使用subprocess,如果使用os.popen則會出現下面的錯誤:
Traceback (most recent call last):
File "./test1.py", line 56, inmain()
File "./test1.py", line 45, in main
File "./mailfax/Fax.py", line 13, in sendFax
os.popen(cmd) ordinal not inrange(128)