subprocess 提供給我們與系統交互和管道的能力,
運行命令,返回的是命令運行的信息,如果運行良好就返回0否則返回1
import subprocess
subprocess.call(['ls','-l'])
Out[5]:
0
與call()是一樣的,但是如果返回的是1就將返回CalledProcessError(拋出錯誤)
subprocess.check_call('ls')
Out[7]:
0
check_output() 返回輸出的內容,就是shell的output,如果返回1就會拋出錯誤
subprocess.check_output(['echo','hello world!'])
Out[11]:
'hello world!\n'
也可以將標準錯誤導出
subprocess.check_output(
"ls hello;exit 0",
stderr=subprocess.STDOUT,
shell=True)
Out[16]:
'ls: hello: No such file or directory\n'
在新的進程中運行命令
In [32]:
import shlex
args = shlex.split('echo $HOME') # 切分命令行
print args
p = subprocess.Popen(args) # Success!
print(p.stdout)
None
None
['echo', '$HOME']
None
使用Pope代替 os.system 和 os.popen
p = subprocess.Popen('pwd')
import os
os.system('pwd')
# os.popen('pwd')
Out[45]:
0