Created
April 10, 2018 09:42
-
-
Save raja-ashok/c5a4bc33fdeebef754b457d4f0a83104 to your computer and use it in GitHub Desktop.
Calling an external command or script in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import subprocess | |
import os | |
# 1) Calling an external command in Python | |
# Simple way to call external command is using os.system(...). And this funciton returns the exit value of the command. | |
# But the drawback is we wont get stdout and stderr. | |
ret = os.system('some_cmd.sh') | |
if ret != 0 : | |
print 'some_cmd.sh execution returned failure' | |
# 2) Calling an external command in Python in background | |
# subprocess.Popen provides more flexibility for running an external command rather than using os.system. | |
# We can start a command in background and wait for its finish. And after that we can get the stdout and stderr | |
proc = subprocess.Popen(["./some_cmd.sh"], stdout=subprocess.PIPE) | |
print 'waiting for ' + str(proc.pid) | |
proc.wait() | |
print 'some_cmd.sh execution finished' | |
(out, err) = proc.communicate() | |
print 'some_cmd.sh output : ' + out | |
# 3) Calling a long run external command in Python in background and stop after sometime | |
# Even we can start a long run process in backgroup using subprocess. Popen and kill it after sometime | |
# once its taks is done. | |
proc = subprocess.Popen(["./some_long_run_cmd.sh"], stdout=subprocess.PIPE) | |
# Do something else | |
# Now some_long_run_cmd.sh exeuction is no longer needed,so kill it | |
os.system('kill -15 ' + str(proc.pid)) | |
print 'Output : ' proc.communicate()[0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment