关于python:python-subprocess

8次阅读

共计 2490 个字符,预计需要花费 7 分钟才能阅读完成。

Intro

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

即 subprocess 反对咱们从以后过程生成子过程来执行 command,尽管都是生成子程序,然而和 fork 不同,subprocess 更 specified 于执行一个执行 shell 命令的子程序。

Use

subprocess.run(args,*,stdin=None,stdout=None,stderr=None,shell=False,
text=None,cwd=None,input=None,timeout=None)
该函数会 spawn 一个用于执行 args 的子过程,并返回一个 CompletedProcess 对象.

  • args 能够是一个列表,也能够是一个 string,如: [“ls”,”-l”]或 ”pwd”. 留神当 args 为 string 时,它只能单纯的指定一个可执行文件,不能带任何参数,除非指定 shell 参数为 True.(If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.)
  • stdin、stdout、stderr 执行了子过程的规范输出、输入、谬误流,个别只有 stdout 和 stderr 会被用到,如不指定 stdout,则规范输入会被间接打印在屏幕上,个别应用 subprocess.PIPE 这个管道来指定 stdout,而对于 stderr 则是 subprocess.STDOUT,这样规范输入、谬误会被 暂存 在管道中,并可由 CompletedProcess 对象取出.
  • shell 参数则是配和 args 应用,如果 args 是 string 则最好把 shell 置为 True.
  • text 参数:If text mode is not used, stdin, stdout and stderr will be opened as binary streams. No encoding or line ending conversion is performed.
  • cwd 参数指定一个 path,使得子过程在 args 所代表的 shell 命令执行前先 cd 到指定的 path 下
  • input 传递给 Popen.communicate
  • timeout 传递给 Popen.communicate

对于 subprocess.run 返回的 CompletedProcess 对象,它有一些 attributes 能够不便咱们取得子过程执行命令的状况.

  • returncode 取得子过程的返回值,0 为胜利执行.
  • args 子过程对应的 args
  • stdout 如果在 subprocess.run 函数调用时指定 PIPE 的话,这里会从管道中失去 stdout 后果,否则为 None.
  • stderr 和 stdout 同理

不过,作为 module 级的函数,它本质上其实是通过 class level 的一些类和办法实现的,即是 subprocess.Popen 和 Popen.communicate 等.

subprocess.Popen(args,stdin=None,stdout=None,stderr=None,shell=False,
cwd=None,text=None)

应用该类时会创立一个子过程执行 args 并返回一个 Popen 实例对象. 上面介绍该类的一些 method:

  • poll 该办法 check 子过程是否完结,如果完结返回 returncode,否则返回 None.
  • terminate 该办法终结子过程
  • kill 该办法杀死子过程,与 terminate 的区别在于传递的 SIGNAL 的不同,terminate 的完结更加 politely,在 windows 上的两者则无区别.
  • wait(timeout=None) 父过程期待子过程完结,超过 timeout 则报错,raise a TimeExpired exception.
  • communicate(input=None,timeout=None) 该办法是与子过程进行沟通,即向 input 传递数据,timeout 和下面雷同,returns a tuple (stdout_data, stderr_data). The data will be strings if streams were opened in text mode; otherwise, bytes.

Popen 的一些 attributes:

  • stdin、stdout、stderr 和之前的 CompletedProcess 同理
  • returncode 实例对应的子过程的返回值
  • args 实例对应的子过程的命令
  • pid 实例对应的子过程的 pid

Cautions

Popen.wait will deadlock when using stdout=PIPE or stderr=PIPE and the child process generates enough output to a pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use Popen.communicate() when using pipes to avoid that. 即 Popen 应用 PIPE 的时候最好不要应用 wait 办法,否则可能会引起 deadlock,应用 communicate 会防止这一点。

对于 subprocess.run 函数所创立的子过程,父过程会主动期待子过程完结,而如果独自应用 subprocess.Popen,则父过程不会期待,能够应用 Popen.wait,不过上文曾经不倡议应用该函数,不过其实 Popen.communicate 除了 Interact with process 的作用,还有 Wait for process to terminate,所以上文才提到应用 commnunicate 代替 wait+Popen.stdout,Popen.stderr.

正文完
 0