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

标签 python bash shell

假设我在 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/

相关文章:

python - Python 中的分段 TCP 消息

Python PSD 图层?

linux - 如何使用变量格式存储 printf 的输出?

linux - 在所有 bash 命令之后自动运行命令?

linux - 用linux文件中的字符串替换字符串模式

python - 工厂方法与 Python 中的注入(inject)框架 - 什么更整洁?

python - Pandas date_range 行为不一致

linux - 如何使用awk读取每n个字符而不是每行的文件?

bash - 我如何才能使读取在 Shell 脚本中不显示其值(value)?

linux - 想使用排序命令在此时间戳 2019-06-29T12 :39:23. 428Z 上对我的日志文件进行排序,但由于有多个定界符而感到困惑