二者均需 import os php
(1) os.system java
# 僅僅在一個子終端運行系統命令,而不能獲取命令執行後的返回信息 python
system(command) -> exit_status
Execute the command (a string) in a subshell. shell
# 若是再命令行下執行,結果直接打印出來 django
2 |
04101419778.CHM bash document media py-django video |
3 |
11.wmv books downloads Pictures python |
4 |
all-20061022 Desktop Examples project tools |
(2) os.popen bash
# 該方法不但執行命令還返回執行後的信息對象 ide
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object. ui
例如: spa
01 |
>>>tmp = os.popen('ls *.py').readlines() |
04 |
['dump_db_pickle.py ', |
05 |
'dump_db_pickle_recs.py ', |
10 |
'make_db_pickle_recs.py ', |
12 |
'peopleinteract_query.py ', |
16 |
'update_db_pickle.py ', |
好處在於:將返回的結果賦於一變量,便於程序的處理。 命令行
(3) 使用模塊subprocess
2 |
>>> subprocess.call (["cmd", "arg1", "arg2"],shell=True) |
獲取返回和輸出:
2 |
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
3 |
for line in p.stdout.readlines(): |
(4) 使用模塊commands模塊
3 |
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg'] |
4 |
>>> commands.getoutput("date") |
5 |
'Wed Jun 10 19:39:57 CST 2009' |
7 |
>>> commands.getstatusoutput("date") |
8 |
(0, 'Wed Jun 10 19:40:41 CST 2009') |
注意: 當執行命令的參數或者返回中包含了中文文字,那麼建議使用subprocess,若是使用os.popen則會出現下面的錯誤:
1 |
Traceback (most recent call last): |
2 |
File "./test1.py", line 56, in <module> |
4 |
File "./test1.py", line 45, in main |
6 |
File "./mailfax/Fax.py", line 13, in sendFax |
8 |
UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not inrange(128) |
關於本文更多的延伸閱讀地址:
http://zh-cn.how-to.mobi/index.php?id=89228
http://www.javaeye.com/topic/406623