简体   繁体   English

在Python中确定调用可执行文件

[英]Determine calling executable in Python

I'm developing a command-line application that launches a sub-shell with a pre-generated environment. 我正在开发一个命令行应用程序,用于启动具有预生成环境的子shell。

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

It launches subshell.bat or subshell.sh depending on which is the current os. 它启动subshell.batsubshell.sh具体取决于当前的操作系统。

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. 但我希望支持Cygwin,Git Bash和其他在Windows上运行的人,他们每个人都需要获得subshell.sh ,即使操作系统是Windows。

I figured that if there was a way of determining the calling executable of a Python process, I could instead check against that. 我想如果有一种方法可以确定Python进程的调用可执行文件,我可以反而检查一下。

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. 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. 你可以使用psutil来做到这一点。

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. 您可以使用psutil.Process(os.getpid()).parent().name()来获取进程的名称。

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'. 它可能会使程序更“Pythonic”,因为“显式优于隐式”。

Python Docs argparse Python Docs argparse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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