(1) os.system
# 僅僅在一個子終端執行系統命令,而不能獲取命令執行後的返回資訊
system(command) -> exit_status
Execute the command (a string) in a subshell.
# 如果再命令列下執行,結果直接列印出來
1 >>> os.system('ls') 2 3 04101419778.CHM bash document media py-django video 4 5 11.wmv books downloads Pictures python 6 7 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.
例如:
1 >>>tmp = os.popen('ls *.py').readlines() 2 3 >>>tmp 4 5 Out[]: 6 7 ['dump_db_pickle.py ', 8 9 'dump_db_pickle_recs.py ', 10 11 'dump_db_shelve.py ', 12 13 'initdata.py ', 14 15 '__init__.py ', 16 17 'make_db_pickle.py ', 18 19 'make_db_pickle_recs.py ', 20 21 'make_db_shelve.py ', 22 23 'peopleinteract_query.py ', 24 25 'reader.py ', 26 27 'testargv.py ', 28 29 'teststreams.py ', 30 31 'update_db_pickle.py ', 32 33 'writer.py ']
好處在於:將返回的結果賦於一變數,便於程式的處理。