Created
February 18, 2021 19:24
-
-
Save nmagee/329baefb7066599d96af879c4836a95f to your computer and use it in GitHub Desktop.
How to call a bash command from within python3
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 python3 | |
# How to run a bash command from within a python3 script. | |
## ----------------------------------------------------------- | |
## BAD | |
## This solution looks good but is a bad practice. as os.system | |
## and os.spawn are older and being replaced. This may not work | |
## on newer systems. | |
import os | |
bashCommand = "cwm --rdf test.rdf --ntriples > test.nt" | |
os.system(bashCommand) | |
## ----------------------------------------------------------- | |
## GOOD | |
## A simple example with static quote-wrapped command and variables: | |
import subprocess | |
cmd = "bash detabify.sh mock_data.tsv output.csv" | |
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) | |
output, error = process.communicate() | |
## ----------------------------------------------------------- | |
## BETTER | |
## This allows you to pass variables into the bash command: | |
import subprocess | |
import os | |
# Set variables someplace | |
INPUT = 'mock_data.tsv' | |
OUTPUT = 'output.csv' | |
# Now use string substitution in the command | |
cmd = f'bash detabify.sh {INPUT} {OUTPUT}' | |
process = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE) | |
output, error = process.communicate() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment