[英]Python - Execute Process -> Block till it exits & Suppress Output
I'm using the following to execute a process and hide its output from Python. 我正在使用以下内容执行进程并从Python隐藏其输出。 It's in a loop though, and I need a way to block until the sub process has terminated before moving to the next iteration.
它在循环中,我需要一种方法来阻止,直到子进程终止,然后才转到下一次迭代。
subprocess.Popen(["scanx", "--udp", host], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
Use subprocess.call()
. 使用
subprocess.call()
。 From the docs: 来自文档:
subprocess.call(*popenargs, **kwargs)
subprocess.call(* popenargs,** kwargs)
Run command with arguments.使用参数运行命令。 Wait for command to complete, then return the returncode attribute.
等待命令完成,然后返回returncode属性。 The arguments are the same as for the Popen constructor.
参数与Popen构造函数相同。
Edit: 编辑:
subprocess.call()
uses wait()
, and wait()
is vulnerable to deadlocks (as Tommy Herbert pointed out). subprocess.call()
使用wait()
,而wait()
容易受到死锁(正如Tommy Herbert指出的那样)。 From the docs: 来自文档:
Warning: This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data.
警告:如果子进程生成足够的输出到stdout或stderr管道,这会阻塞等待OS管道缓冲区接受更多数据,这将导致死锁。 Use communicate() to avoid that.
使用communic()来避免这种情况。
So if your command generates a lot of output, use communicate()
instead: 因此,如果您的命令生成大量输出,请使用
communicate()
代替:
p = subprocess.Popen(
["scanx", "--udp", host],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
If you don't need output at all you can pass devnull to stdout
and stderr
. 如果你根本不需要输出,你可以将devnull传递给
stdout
和stderr
。 I don't know if this can make a difference but pass a bufsize. 我不知道这是否有所作为,但通过bufsize。 Using devnull now
subprocess.call
doesn't suffer of deadlock anymore 使用devnull现在
subprocess.call
不吃亏的僵局了
import os
import subprocess
null = open(os.devnull, 'w')
subprocess.call(['ls', '-lR'], bufsize=4096, stdout=null, stderr=null)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.