Popen和子程序之间的区别是什么(如何使用它们)?
我想从Python调用一个外部程序。 我用Popen()和call()来做到这一点。
两者有什么区别?
我的具体目标是从Python运行以下命令。 我不确定redirect是如何工作的。
./my_script.sh > output
我读的文件 ,它说, call()是一个方便的function或快捷方式的function。 我们是否使用call()而不是Popen()来失去任何权力?
有两种方法可以进行redirect。 两者都适用于subprocess.Popen或subprocess.call 。
-
设置关键字参数
shell = True或者executable = /path/to/the/shell并且像在那里一样指定命令。 -
由于您只是将输出redirect到文件,请设置关键字参数
stdout = an_open_writeable_file_object对象指向
output文件的位置。
subprocess.Popen比subprocess.call更普遍。
Popen不会阻塞,允许您在运行过程中与stream程交互,也可以在Python程序中继续进行其他操作。 对Popen的调用返回一个Popen对象。
call 确实阻止。 虽然它支持所有与Popen构造函数相同的参数,所以仍然可以设置进程的输出,环境variables等,脚本等待程序完成, call返回代表进程退出状态的代码。
returncode = call(*args, **kwargs)
跟通话基本一样
returncode = Popen(*args, **kwargs).wait()
call只是一个方便的function。 它在CPython中的实现是在subprocess.py中 :
def call(*popenargs, timeout=None, **kwargs): """Run command with arguments. Wait for command to complete or timeout, then return the returncode attribute. The arguments are the same as for the Popen constructor. Example: retcode = call(["ls", "-l"]) """ with Popen(*popenargs, **kwargs) as p: try: return p.wait(timeout=timeout) except: p.kill() p.wait() raise
正如你所看到的,这是围绕着Popen的一个薄薄的包装。