以指定的最大运行时间运行外部程序
我想在多线程Python程序的每个线程中执行外部程序。
假设最大运行时间设置为 1 秒。如果启动的进程在 1 秒内完成,主程序将捕获其输出以进行进一步处理。如果它没有在 1 秒内完成,主程序就会终止它并启动另一个新进程。
如何实施?
I want to execute an external program in each thread of a multi-threaded python program.
Let's say max running time is set to 1 second. If started process completes within 1 second, main program capture its output for further processing. If it doesn't finishes in 1 second, main program just terminate it and start another new process.
How to implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以定期轮询它:
然后您可以将上述内容放入函数中并将其作为线程启动。
You could poll it periodically:
You can then just put the above in a function and start it as a thread.
这是我使用的辅助函数:
This is the helper function I use:
Linux 上的一个令人讨厌的黑客行为是使用
timeout
程序来运行命令。不过,您可以选择更好的全 Python 解决方案。A nasty hack on linux is to use the
timeout
program to run the command. You may opt for a nicer all Python solution, however.这是使用
pexpect
模块的解决方案(我需要在程序超时之前捕获程序的输出,我没有设法使用subprocess.Popen
来做到这一点):here is a solution using the
pexpect
module (I needed to capture the output of the program before it ran into the timeout, I did not manage to do this withsubprocess.Popen
):