Skip to content

Instantly share code, notes, and snippets.

@nmagee
Created February 18, 2021 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmagee/329baefb7066599d96af879c4836a95f to your computer and use it in GitHub Desktop.
Save nmagee/329baefb7066599d96af879c4836a95f to your computer and use it in GitHub Desktop.
How to call a bash command from within python3
#!/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