How to use the bash shell with Python's subprocess module instead of /bin/sh
By default, running subprocess.Popen
with shell=True
uses /bin/sh
as the shell. If you want to change the shell to /bin/bash
, set the executable
keyword argument to /bin/bash
.
Solution thanks this great article: Working with Python subprocess - Shells, Processes, Streams, Pipes, Redirects and More
import subprocess
def bash_command(cmd):
subprocess.Popen(cmd, shell=True, executable='/bin/bash')
bash_command('a="Apples and oranges" && echo "${a/oranges/grapes}"')
Output:
Apples and grapes
For some reason, the above didn't work for my specific case, so I had to use the following instead:
import subprocess
def bash_command(cmd):
subprocess.Popen(['/bin/bash', '-c', cmd])
See also
Related posts
- How to capture stdout in real-time with Python — posted 2009-10-12
- How to get stdout and stderr using Python's subprocess module — posted 2008-09-23
- How to use python and popen4 to capture stdout and stderr from a command — posted 2007-03-12
Comments
Can /usr/bin/env bash be used?
disqus:2354674668