gpt4 book ai didi

python - 如何在 Python 中检查 shell 命令是否结束

转载 作者:太空狗 更新时间:2023-10-30 02:04:05 28 4
gpt4 key购买 nike

假设我在 python 中有这个简单的行:

os.system("sudo apt-get update")

当然,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"

现在的问题是,即使它真的完成了,它也从不打印“It finished”。

最佳答案

正如文档所述:

This is implemented by calling the Standard C function system(), and has the same limitations

system 的 C 调用只是运行程序直到它退出。调用 os.system 会阻塞您的 python 代码,直到 bash 命令完成,因此当 os.system 返回时您将知道它已完成。如果您想在等待通话结束时做其他事情,有几种可能性。首选方法是使用 subprocessing模块。

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

查看上面的链接,了解您可以使用 Popen

做的更多事情

对于更通用的并发运行代码的方法,您可以在另一个 thread 中运行它或 process .这是示例代码:

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

另一种选择是使用 concurrent.futures模块。

关于python - 如何在 Python 中检查 shell 命令是否结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24470561/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com