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.