Reputation: 615
I have some code to execute the unix shell command in background in python
import subprocess
process = subprocess.Popen('find / > tmp.txt &',shell=True)
I need to capture the scenario where i come to know that process has finished successful completion .
Please explain with sample code
Tazim
Upvotes: 2
Views: 2842
Reputation: 4817
Don't use shell=True. It is bad for your health.
proc = subprocess.Popen(['find', '/'], stdout=open('tmp.txt', 'w'))
if proc.wait() == 0:
pass
If you really need a file, use import tempfile
instead of a hard-coded temporary file name. If you don't need the file, use a pipe (see the subprocess docs as Thomas suggests).
Also, don't write shell scripts in Python. Use the os.walk
function instead.
Upvotes: 2
Reputation: 181785
There is no need for the &
: the command is launched in a separate process, and runs independently.
If you want to wait until the process terminates, use wait()
:
process = subprocess.Popen('find / > tmp.txt', shell = True)
exitcode = process.wait()
if exitcode == 0:
# successful completion
else:
# error happened
If your program can do something meaningful in the meantime, you can use poll()
to determine if the process has finished.
Furthermore, instead of writing the output to a temporary file and then reading it from your Python program, you can read from the pipe directly. See the subprocess
documentation for details.
Upvotes: 4