使用子进程 wait() 和 poll()
我正在尝试编写一个使用 subprocess
模块的小应用程序。
我的程序调用一个外部 Bash 命令,需要一些时间来处理。在此期间,我想向用户显示一系列如下消息:
正在处理。请稍等...
输出是 foo()
如何使用 Popen.wait()
或 Popen.poll()
执行此操作。我读到我需要使用 Popen.returncode
,但我不知道如何让它主动检查状态。
I am trying to write a small app that uses the subprocess
module.
My program calls an external Bash command that takes some time to process. During this time, I would like to show the user a series of messages like this:
Processing. Please wait...
The output is foo()
How can I do this using Popen.wait()
or Popen.poll()
. I have read that I need to use the Popen.returncode
, but how I can get it to actively check the state, I don't know.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
两者wait()
< /a> (指定了timeout
)和poll()
如果进程尚未完成,则返回None
;如果进程已经完成,则返回不同的内容(我认为一个整数,退出代码,希望为 0)。编辑:
wait()
和poll()
有不同的行为:wait
(没有超时参数)将阻塞并等待进程完成。wait
将等待timeout
秒以让进程完成。如果未完成,则会抛出TimeoutExpired
异常。如果您捕获到异常,欢迎您继续,或者再次等待
。poll
总是立即返回。它有效地执行超时为 0 的等待,捕获任何异常,并在进程尚未完成时返回None
。wait
或poll
,如果进程已完成,popen 对象的returncode
将被设置(否则它是 None - 您可以像调用wait
或poll
),函数的返回值也将是进程的返回码。所以我认为你应该这样做:
请注意,如果 bash 脚本创建大量输出,你必须使用
communicate()
或类似的东西防止 stdout 或 stderr 被塞满。Bothwait()
(withtimeout
specified) andpoll()
returnNone
if the process has not yet finished, and something different if the process has finished (I think an integer, the exit code, hopefully 0).Edit:
wait()
andpoll()
have different behaviors:wait
(without the timeout argument) will block and wait for the process to complete.wait
with the timeout argument will waittimeout
seconds for the process to complete. If it doesn't complete, it will throw theTimeoutExpired
exception. If you catch the exception, you're then welcome to go on, or towait
again.poll
always returns immediately. It effectively does a wait with a timeout of 0, catches any exception, and returnsNone
if the process hasn't completed.wait
orpoll
, if the process has completed, the popen object'sreturncode
will be set (otherwise it's None - you can check for that as easily as callingwait
orpoll
), and the return value from the function will also be the process's return code.</Edit>
So I think you should do something like:
Be aware that if the bash script creates a lot of output you must use
communicate()
or something similar to prevent stdout or stderr to become stuffed.@extraneon 的答案有点倒退。如果进程已完成,
wait()
和poll()
都会返回进程的退出代码。如果进程仍在运行,poll()
方法将返回None
,并且wait()
方法将阻塞,直到进程退出:查看以下页面: https://docs.python.org/3.4/library/subprocess.html# popen-objects
Popen.poll()
Popen.wait()
@extraneon's answer is a little backwards. Both
wait()
andpoll()
return the process's exit code if the process has finished. Thepoll()
method will returnNone
if the process is still running and thewait()
method will block until the process exits:Check out the following page: https://docs.python.org/3.4/library/subprocess.html#popen-objects
Popen.poll()
Popen.wait()