avatar

Python-subprocess模块详解

Python-subprocess模块详解

subprocess模块是一个十分强大的模块,他几乎可以执行任何程序并且拿到它的stdin、stdout和stderr,这对我们实现自动化管理有非常大的帮助

代码格式

1
2
3
4
5
import subprocess
popen = subprocess.Popen(['python','test.py'])
popen = subprocess.Popen(['/bin/sh'],stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
popen = subprocess.Popen('/bin/sh',shell=True,stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
popen = subprocess.call(['python','test.py'])

若我们想把错误信息管道接到标准输出流上也是可以实现的

1
popen = subprocess.Popen(['/bin/sh'],stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.STDOUT)

若我们想要写入数据到被启动程序中,可以用以下代码

1
2
3
4
import subprocess
popen = subprocess.Popen(['/bin/sh'],stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
popen.stdin.write("ls\n")
print popen.stdout.readline()

从上面的代码上可以看到subprocess的通用性非常好

如果我想关闭subprocess启动的进程怎么办呢?

请参考以下代码

1
2
3
import subprocess
popen = subprocess.Popen(['/bin/sh'],stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
popen.terminate()

如果我想实现实时运行log输出呢

请参考以下代码

1
2
3
4
5
6
7
import subprocess
popen = subprocess.Popen(['/bin/sh'],stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE)
while True:
line = popen.stdout.readline()
print line
if line == '' and popen.poll is None:
break
文章作者: 咲夜南梦
文章链接: http://yoursite.com/2020/02/14/Python-subprocess%E6%A8%A1%E5%9D%97%E8%AF%A6%E8%A7%A3/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 咲夜南梦's 博客
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论