Python知识收藏

python标准库:subprocess

2017-05-31  本文已影响0人  Chenzongshu

subprocess意在替代其他几个老的模块或者函数,比如:os.system os.spawn* os.popen* popen2.* commands.*

subprocess的目的就是启动一个新的进程并且与之通信。

subprocess最简单的用法就是调用shell命令了,另外也可以调用程序,并且可以通过stdout,stdin和stderr进行交互。

subprocess主类

subprocess模块中只定义了一个类: Popen。可以使用Popen来创建进程,并与进程进行复杂的交互。

subprocess.Popen(
      args, 
      bufsize=0, 
      executable=None,
      stdin=None,
      stdout=None, 
      stderr=None, 
      preexec_fn=None, 
      close_fds=False, 
      shell=False, 
      cwd=None, 
      env=None, 
      universal_newlines=False, 
      startupinfo=None, 
      creationflags=0)

Popen方法

程序中运行其他程序

可以这样写

subprocess.Popen('脚本/shell', shell=True)

也可以这样

subprocess.call('脚本/shell', shell=True)

两者的区别是前者无阻塞,会和主程序并行运行,后者必须等待命令执行完毕,如果想要前者编程阻塞可以这样

s = subprocess.Popen('脚本/shell', shell=True)
s.wait()

程序返回运行结果

有时候我们需要程序的返回结果,可以这样做

>>> s = subprocess.Popen('ls -l', shell=True, stdout=subprocess.PIPE) 
>>> s.communicate() 
('\xe6\x80\xbb\xe7\x94\xa8\xe9\x87\x8f 152\n-rw------- 1 limbo limbo   808  7\xe6\x9c\x88  6 17:46 0000-00-00-welcome-to-jekyll.markd (......)')

它会返回一个元组:(stdoutdata, stderrdata)
subprocess还有另一种更简单方法,效果一样,它会返回stdout

>>> s = subprocess.check_output('ls -l', shell=True)
>>> s
('\xe6\x80\xbb\xe7\x94\xa8\xe9\x87\x8f 152\n-rw------- 1 limbo limbo   808  7\xe6\x9c\x88  6 17:46 0000-00-00-welcome-to-jekyll.markd (......)')

前者可以实现更多的交互,如stderr和stdin,但是在前面调用Popen的时候要实现定义Popen(stdin=subprocess.PIPE, stderr=subprocess)

上一篇 下一篇

猜你喜欢

热点阅读