使用子进程 wait() 和 poll() [英] Using subprocess wait() and poll()

查看:33
本文介绍了使用子进程 wait() 和 poll()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个使用 subprocess 模块的小应用程序.

I am trying to write a small app that uses the subprocess module.

我的程序调用一个需要一些时间来处理的外部 Bash 命令.在此期间,我想向用户展示一系列如下消息:

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:

处理.请稍等...
输出是 foo()

Processing. Please wait...
The output is foo()

如何使用 Popen.wait()Popen.poll() 执行此操作.我已经读到我需要使用 Popen.returncode,但是我不知道如何让它主动检查状态.

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.

推荐答案

Both wait()(指定了 timeout)和 poll() 如果进程尚未完成,则返回 None,并且如果进程已经完成了一些不同的东西(我认为是一个整数,退出代码,希望是 0).

Both wait() (with timeout specified) and poll() return None if the process has not yet finished, and something different if the process has finished (I think an integer, the exit code, hopefully 0).

编辑:

wait()poll() 有不同的行为:

wait() and poll() have different behaviors:

  • wait(不带超时参数)将阻塞并等待进程完成.
  • wait 和 timeout 参数将等待 timeout 秒让进程完成.如果它没有完成,它将抛出 TimeoutExpired 异常.如果您发现异常,欢迎您继续,或再次等待.
  • poll 总是立即返回.它有效地执行超时为 0 的等待,捕获任何异常,如果进程尚未完成,则返回 None.
  • 使用 waitpoll,如果过程已完成,popen 对象的 returncode 将被设置(否则它是 None - 你可以像调用 wait 一样轻松地检查它poll),函数的返回值也将是进程的返回码.
  • wait (without the timeout argument) will block and wait for the process to complete.
  • wait with the timeout argument will wait timeout seconds for the process to complete. If it doesn't complete, it will throw the TimeoutExpired exception. If you catch the exception, you're then welcome to go on, or to wait again.
  • poll always returns immediately. It effectively does a wait with a timeout of 0, catches any exception, and returns None if the process hasn't completed.
  • With either wait or poll, if the process has completed, the popen object's returncode will be set (otherwise it's None - you can check for that as easily as calling wait or poll), and the return value from the function will also be the process's return code.

</编辑>

所以我认为你应该这样做:

So I think you should do something like:

while myprocess.poll() is None:
    print("Still working...")
    # sleep a while

请注意,如果 bash 脚本创建了大量输出,您必须使用 communicate() 或类似的东西来防止 stdoutstderr变得塞满.

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.

这篇关于使用子进程 wait() 和 poll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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