Loading... 等待子进程完成 ``` child = subprocess.Popen('ping www.baidu.com') child.wait() print('End') ``` 标准输出 ``` import subprocess child = subprocess.Popen(['shell','python --version'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr= subprocess.PIPE) shell_out = child.stdout.read() # shell_out = child.communicate() 也可以使用communicate()方法输出 shell_error = child.stderr.read() print(shell_out) print(shell_error) ``` 其他方法 ``` child.poll() #检查子进程状态 child.kill() #终止子进程 child.send_signal() #向子进程发送信号 child.terminate() #终止子进程 ``` **subprocess.run()** subprocess.run()函数是Python3.5中新增的一个高级函数,其返回值是一个subprocess.CompletedPorcess类的实例。 ``` child = subprocess.run('python --version', shell =True) print(child) #CompletedProcess(args='python --version', returncode=0) ``` **subprocess.call()** 父进程等待子进程完成 执行成功返回0 执行失败returncode=2,不会主动抛error ``` child = subprocess.call('python --version', shell =True) print(child) ``` **subprocess.check_call()** 父进程等待子进程完成 执行成功返回0 returncode不为0,抛出subprocess.CalledProcessError:error信息只有returncode ``` child = subprocess.check_call('python --version', shell =True) print(child) ``` **subprocess.check_output()** 父进程等待子进程完成 执行成功返回output信息 returncode不为0,抛出subprocess.CalledProcessError:error信息包含returncode和output信息 ``` child = subprocess.check_output('python --version', shell =True) print(child) #b'Python 3.6.4\r\n' ``` 最后修改:2022 年 04 月 09 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 如果觉得我的文章对你有用,请随意赞赏