Bash Commands in Python

A Brief Example

I use fair bit of python and a bit of bash for my research. As a PhD graduate student, I have to figure out most coding on my own for as close to free as I can get.

Recently, I’ve found the need to write a python script that requires bash commands to be exicuted. This sent me down a rabit hole of how to do this.

I am by no means an expert and the following is what I figured out.

The first line imports subprocess and sysytem-specific parameters and functions. I ended up not using sys, so it could have been omitted.

Subprocess allows me to use subprocess.run() which is how I exicute the bash command.

Normally I would type mpirun -np 2 pw.x -nk2 < file.in > file.out into my terminal, and get what I want, when shell=False.

Through testing, I found that each “word” needs quatations around it and a comma to seperate the “words”.

pw_command is a variable with the bash command set to it.

When I get the actual python script with bash working, I’ll post it.


Leave a comment