subprocess.call-runs a command and returns output and the exit code
subprocess.check_call-runs a command; if exit code is 0 returns output, otherwise CalledProcessError
Here are some simple example scripts to help get started using the subprocess inside python code:
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
import subprocess | |
# Call separated by quotes, first quote command others are interpreted as options | |
subprocess.call(["echo","Hello world!"]) | |
# No quotes needed with shell=True option | |
subprocess.call("ls -l | grep Music", shell=True) | |
# Exit code can be saved as a variable otherwise check_call produces error if non-zero | |
exit_code=subprocess.check_call("ls -l | grep .txt", shell=True) | |
# Run another program | |
subprocess.call("Rscript -e 2+2", shell=True) | |
# Output can be saved as a variable | |
output=subprocess.Popen("Rscript -e 2+2", shell=True, stdout=subprocess.PIPE).stdout.read() |
No comments:
Post a Comment