假设我在python中有这个简单的行:
os.system("sudo apt-get update")
Run Code Online (Sandbox Code Playgroud)
当然,apt-get需要一些时间直到它完成,如果命令已经完成或者还没有完成,我如何检查python?
编辑:这是Popen的代码:
os.environ['packagename'] = entry.get_text()
process = Popen(['dpkg-repack', '$packagename'])
if process.poll() is None:
print "It still working.."
else:
print "It finished"
Run Code Online (Sandbox Code Playgroud)
现在的问题是,即使它真的完成,它也永远不会打印出"已完成".
正如文档所述:
这是通过调用标准C函数系统()来实现的,并且具有相同的限制
C调用system只是运行程序直到它退出.调用os.system阻塞你的python代码,直到bash命令完成,这样你就会知道它在os.system返回时已经完成了.如果你想在等待电话结束时做其他事情,有几种可能性.首选方法是使用子处理模块.
from subprocess import Popen
...
# Runs the command in another process. Doesn't block
process = Popen(['ls', '-l'])
# Later
# Returns the return code of the command. None if it hasn't finished
if process.poll() is None:
# Still running
else:
# Has finished
Run Code Online (Sandbox Code Playgroud)
查看上面的链接,了解更多可以使用的内容 Popen
对于同时运行代码的更一般方法,您可以在另一个线程或进程中运行该方法.这是示例代码:
from threading import Thread
...
thread = Thread(group=None, target=lambda:os.system("ls -l"))
thread.run()
# Later
if thread.is_alive():
# Still running
else:
# Has finished
Run Code Online (Sandbox Code Playgroud)
另一种选择是使用该concurrent.futures模块.
| 归档时间: |
|
| 查看次数: |
2940 次 |
| 最近记录: |