Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

    

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

Post a comment

Required
Required, but not displayed
Optional

Format using Markdown. (No HTML.)
  • Code blocks: prefix each line by at least 4 spaces or 1 tab (and a blank line before and after)
  • Code span: surround with backticks
  • Blockquotes: prefix lines to be quoted with >
  • Links: <URL>
  • Links w/ description: [description](URL)
Created with Django | Hosted by Linode