简体   繁体   中英

Determine calling executable in Python

I'm developing a command-line application that launches a sub-shell with a pre-generated environment.

subprocess.call(subshell, shell=True, env=custom_environment)

It launches subshell.bat or subshell.sh depending on which is the current os.

subshell = "subshell.bat" if os.name == "nt" else "subshell.sh"

But I'm looking to support Cygwin, Git Bash and others running on Windows, and they each need to be given subshell.sh instead, even though the OS is Windows.

I figured that if there was a way of determining the calling executable of a Python process, I could instead check against that.

if calling_executable in ("bash", "sh"):
  subshell = "subshell.sh"
elif calling_executable in ("cmd", "powershell"):
  subshell = "subshell.bat"
else:
  sys.exit()  # unsupported shell

But I'm not sure how to do that. Any ideas or suggestions for how to go about it differently?

Usage example

$ mytool --enter
Entering subshell for bash.exe

ps. this question is phrased exactly the same, but doesn't involve a similar problem, so it didn't feel right to add an unrelated problem to it.

You can use psutil to do that.

import psutil, os
Parent=psutil.Process(os.getpid()).parent()
ParentName=Parent.name() # e.g. bash, cmd.exe, etc

See that answer for another example. You can get the process' name with psutil.Process(os.getpid()).parent().name() as well.

I would suggest adding command line parameters to indicate the version if you cannot rely on just checking the operating system. It would probably make the program more "Pythonic" because 'explicit is better than implicit'.

Python Docs argparse

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM