Find the location of the bash executable on windows from python

Viewed 186

I'm writing a program that executes short shell one liners (potentially including pipes and background tasks etc), and I'd like to make it "just work" cross platform as much as possible.

For mac/linux the following seems to work well:

shell = os.environ.get("SHELL", "/bin/bash")
subprocess.Popen([shell, "-c", script_content])

However given that on windows:

  1. SHELL isn't usually set
  2. Assuming that bash is installed, a usable bash executable might be found in a variety of different places

What's the best way to make this work as reliably as possible in windows?

3 Answers

Are you looking for C:\Windows\System32\cmd.exe?

And if you are doing cross platorm you could use sys.platorm to find the platform the user is using.

On Window, 'COMSPEC' holds the name of the current command program. You can write unconditional lookup to lookup in the environemnt. Usually, better to take this approach, as in many cases, python script may be executed from 'git-bash', WSL or similar. No need to explicitly program for specific platform.

  1. First Using SHELL
  2. If none, use COMSPEC

See: https://en.wikipedia.org/wiki/COMSPEC

If you have Windows git client installed, you should have git bash, so in a CMD window:

set SHELL="c:\Program Files\Git\bin\bash.exe"

then you can run you python program.

Related