Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a shell command is over in Python

Tags:

python

bash

shell

Let's say that I have this simple line in python:

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

of course, apt-get will take some time untill it's finished, how can I check in python if the command had finished or not yet?

Edit: this is the code with 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"

Now the problem is, it never print "It finished" even when it really finish.

like image 798
Madno Avatar asked Jan 10 '23 07:01

Madno


2 Answers

As the documentation states it:

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

The C call to system simply runs the program until it exits. Calling os.system blocks your python code until the bash command has finished thus you'll know that it is finished when os.system returns. If you'd like to do other stuff while waiting for the call to finish, there are several possibilities. The preferred way is to use the subprocessing module.

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

Check the link above for more things you can do with Popen

For a more general approach at running code concurrently, you can run that in another thread or process. Here's example code:

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

Another option would be to use the concurrent.futures module.

like image 90
Nikola Dimitroff Avatar answered Jan 12 '23 21:01

Nikola Dimitroff


os.system will actually wait for the command to finish and return the exit status (format dependent format).

like image 24
nmaier Avatar answered Jan 12 '23 20:01

nmaier