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

Mad*_*dno 4 python bash shell

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

现在的问题是,即使它真的完成,它也永远不会打印出"已完成".

Nik*_*off 8

正如文档所述:

这是通过调用标准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模块.

  • 我很确定`subprocess`模块是这种情况下的方法. (2认同)