问题描述
我最近在 Python 中注意到 subprocess.Popen()
有一个参数:
I recently noted in Python the subprocess.Popen()
has an argument:
stdout=None(default)
我还看到人们使用 stdout=subprocess.PIPE.
I also saw people using stdout=subprocess.PIPE.
有什么区别?我应该使用哪一个?
What is the difference? Which one should I use?
另一个问题是,为什么 wait() 函数有时不能等到进程真正完成?我用过:
Another question would be, why the wait() function can't wait until the process is really done sometimes? I used:
a = sp.Popen(....,shell=True)
a.wait()
a2 = sp.Popen(...,shell=True)
a2.wait()
有时 a2 命令在命令 a 完成之前执行.
sometimes the a2 command is executed before the command a is done.
推荐答案
stdout=None
的意思是,进程的stdout
-handle直接继承自父进程,用更简单的话来说,它基本上意味着,它被打印到控制台(同样适用于 stderr
).
stdout=None
means, the stdout
-handle from the process is directly inherited from the parent, in easier words it basically means, it gets printed to the console (same applies for stderr
).
然后你有选项stderr=STDOUT
,这会将stderr
重定向到stdout
,也就是stdout<的输出/code> 和
stderr
被转发到同一个文件句柄.
Then you have the option stderr=STDOUT
, this redirects stderr
to the stdout
, which means the output of stdout
and stderr
are forwarded to the same file handle.
如果设置stdout=PIPE
,Python会将数据从进程重定向到一个新的文件句柄,可以通过p.stdout
(p
作为一个 Popen
对象).您可以使用它来捕获进程的输出,或者对于 stdin
的情况,将数据(不断地)发送到 stdin
.但大多数情况下,您希望使用 p.communicate
,它允许您向进程发送一次数据(如果需要)并返回完整的 stderr
和 stdout
如果进程完成!
If you set stdout=PIPE
, Python will redirect the data from the process to a new file handle, which can be accessed through p.stdout
(p
beeing a Popen
object). You would use this to capture the output of the process, or for the case of stdin
to send data (constantly) to stdin
.
But mostly you want to use p.communicate
, which allows you to send data to the process once (if you need to) and returns the complete stderr
and stdout
if the process is completed!
另一个有趣的事实是,您可以将任何 file-object
传递给 stdin/stderr/stdout
,例如也是一个用 open
打开的文件(对象必须提供一个 fileno()
方法).
One more interesting fact, you can pass any file-object
to stdin/stderr/stdout
, e.g. also a file opened with open
(the object has to provide a fileno()
method).
到你的 wait
问题.这不应该是这样!作为解决方法,您可以使用 p.poll()
检查进程是否退出!wait
调用的返回值是多少?
To your wait
problem. This should not be the case! As workaround you could use p.poll()
to check if the process did exit! What is the return-value of the wait
call?
此外,您应该避免 shell=True
特别是如果您将用户输入作为第一个参数传递,恶意用户可能会使用它来利用您的程序!它还启动了一个 shell 进程,这意味着额外的开销.当然,有 1% 的情况下您确实需要 shell=True
,我无法用您的简约示例来判断.
Furthermore, you should avoid shell=True
especially if you pass user-input as first argument, this could be used by a malicious user to exploit your program! Also it launches a shell process which means additional overhead. Of course there is the 1% of cases where you actually need shell=True
, I can't judge this with your minimalistic example.
这篇关于如果我在 subprocess.Popen() 中不使用 stdout=subprocess.PIPE 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!