subprocess.popen 和 subprocess.run 有什么区别 [英] What is the difference between subprocess.popen and subprocess.run

查看:165
本文介绍了subprocess.popen 和 subprocess.run 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 subprocess 模块的新手,文档让我想知道 subprocess.popensubprocess.run 之间有什么区别.命令的作用有什么不同吗?一个只是更新?哪个更好用?

I'm new to the subprocess module and the documentation leaves me wondering what the difference is between subprocess.popen and subprocess.run. Is there a difference in what the command does? Is one just newer? Which is better to use?

推荐答案

subprocess.run 在 Python 3.5 中添加,作为对 subprocess.Popen 的简化,当您只想执行命令并等待它完成时,但您不这样做同时不想做任何其他事情.其他情况还是需要使用subprocess.Popen.

subprocess.run was added in Python 3.5 as a simplification over subprocess.Popen when you just want to execute a command and wait until it finishes, but you don't want to do anything else meanwhile. For other cases, you still need to use subprocess.Popen.

主要区别在于 subprocess.run 执行命令并等待完成,而使用 subprocess.Popen 你可以继续在流程完成时做您的事情,然后自己重​​复调用 subprocess.communicate 以将数据传递和接收到您的流程.

The main difference is that subprocess.run executes a command and waits for it to finish, while with subprocess.Popen you can continue doing your stuff while the process finishes and then just repeatedly call subprocess.communicate yourself to pass and receive data to your process.

请注意,subprocess.run 实际上是在为您调用 Popencommunicate,因此您不需要进行循环以传递/接收数据或等待进程完成.

Note that, what subprocess.run is actually doing is invoking for you the Popen and communicate, so you don't need to make a loop to pass/receive data nor wait for the process to finish.

查看官方文档了解哪些参数subprocess.run 被传递给 Popencommunicate.

Check the official documentation for information of which parameters of subprocess.run are passed to Popen and which to communicate.

这篇关于subprocess.popen 和 subprocess.run 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆