kjo
kjo

Reputation: 35301

How to get "canonical unix shell" for Python

According to the documentation for the subprocess module, its default shell is /bin/sh, but I have an ingrained, and probably irrational, aversion to hard-coding such constants.

Therefore, I much prefer to refer to some constant defined in subprocess. I have not been able to find any way to interrogate subprocess directly for this constant. The best I've managed is

def _getshpath():
    return subprocess.check_output('which sh', shell=True).strip()

or

def _getshpath():
    return subprocess.check_output('echo "$0"', shell=True).strip()

...both of which look pathetically fragile, since their validity ultimately depend on precisely the specific value I'm trying to determine in the first place. (I.e., if the value of this executable is not "/bin/sh", either definition could easily be nonsensical.)

What's best-practice for getting this path (without hard-coding it as "/bin/sh")?

Thanks!

Upvotes: 4

Views: 120

Answers (2)

bmu
bmu

Reputation: 36184

You could try

>>> import os
>>> shell = os.environ['SHELL']
>>> print shell
'/bin/bash'

You can use this to set the executable argument of subprocess.Popen.

Upvotes: 1

John Zwinck
John Zwinck

Reputation: 249133

Hard-coding it as /bin/sh is perfectly valid. If you look at the documentation for C's popen() you'll find it does this too. /bin/sh is, by construction, the system's standard shell.

Upvotes: 3

Related Questions