[英]How do I detect if my python code is running in PowerShell or the Command Prompt (cmd)
I have a python application that has a shell that needs to do some setup based on whether the shell it's running in is the Windows Command Prompt (cmd)
or Powershell
.我有一个 python 应用程序,它有一个 shell,需要根据它运行的 shell 是Windows Command Prompt (cmd)
还是Powershell
进行一些设置。
I haven't been able to figure out how to detect if the application is running in powershell
or cmd
.我一直无法弄清楚如何检测应用程序是在powershell
还是cmd
运行。
From my searches on stackoverflow and Google, it seems the only way to do this is to use psutil
to find the name of the parent process.从我在 stackoverflow 和 Google 上的搜索来看,似乎唯一的方法是使用psutil
来查找父进程的名称。
Is there a nicer way?有更好的方法吗?
Edit: I've decided to use psutil
to find the name of the parent process.编辑:我决定使用psutil
来查找父进程的名称。 Thanks to everyone who helped in the comments.感谢所有在评论中提供帮助的人。
@Matt A. is right. @Matt A. 是对的。 Use psutil
and os
package to get the parent process id and the name.使用psutil
和os
包获取父进程 ID 和名称。
parent_pid = os.getppid()
print(psutil.Process(parent_pid).name())
The following snippet finds md5sum on args.file in bash/powershell, I usually use the first command to check what we are running in, so I can use it later on, using shell=True in subprocess is not very portable.下面的代码片段在 bash/powershell 中的 args.file 上找到 md5sum,我通常使用第一个命令来检查我们正在运行的内容,因此我可以稍后使用它,在子进程中使用 shell=True 不是很便携。
import os, subprocess
running_shell = None
mycheck='/usr/bin/md5sum' # full path is needed
if not os.path.isfile(mycheck):
try:
file_md5sum = subprocess.check_output("powershell.exe Get-FileHash -Algorithm MD5 {} | Select -expand Hash".format(args.file).split())
except FileNotFoundError as e:
log.fatal("unable to generate md5sum")
sys.exit(-1)
file_md5sum = file_md5sum.lower()
running_shell = 'powershell'
else:
file_md5sum = subprocess.check_output([mycheck, args.file])
running_shell = 'bash'
Here is a sample powershell
stub that can do the trick:这是一个可以解决问题的示例powershell
存根:
$SCR="block_ips.py"
$proc = $null
$procs = Get-WmiObject Win32_Process -Filter "name = 'python3.exe' or name = 'python.exe'" | Select-Object Description,ProcessId,CommandLine,CreationDate
$procs | ForEach-Object {
if ( $_.CommandLine.IndexOf($SCR) -ne -1 ) {
if ( $null -eq $proc ) {
$proc = $_
}
}
}
if ( $null -ne $proc ) {
Write-Host "Process already running: $proc"
} else {
Write-Host "$SCR is not running"
}
Based on this post , you should be able to run this CMD/PS command through the subprocess
module in your Python script:根据这篇文章,您应该能够通过 Python 脚本中的subprocess
模块运行此 CMD/PS 命令:
subprocess.call("(dir 2>&1 *`|echo CMD);&<# rem #>echo PowerShell", shell=True)
This will output CMD
if you're in CMD, and PowerShell
if you're in PS.如果您在 CMD 中,这将输出CMD
,如果您在 PS 中,这将输出PowerShell
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.