简体   繁体   English

如何检测我的 Python 代码是否在 PowerShell 或命令提示符 (cmd) 中运行

[英]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.使用psutilos包获取父进程 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.

相关问题 运行提升的 cmd 提示符命令 python - Running a elevated cmd prompt command python 为什么我的 python 代码在命令提示符下运行良好,但在 sublime 中运行不正常? - Why is my python code is running fine on command prompt but not running in sublime? 如何使用 cmd 提示符检查我的设备上安装了多少个 Python 版本? - How do I check how many versions of Python I have installed on my device using the cmd prompt? 如何在不显示命令提示符的情况下运行 powershell 中的 python 代码? - How to run python code from powershell with no command prompt showing? 如何检测我的 Python 脚本是否在“Windows 终端”中运行 - How do I detect if my Python script is running in the 'Windows Terminal' 运行python代码时,如何在命令promt中并列显示我的列? - How do i get my columns to display side by side in the command promt when running python code? 运行 twilio python api doc 时,我的 cmd 提示中出现 KEY ERROR - I am having KEY ERROR in my cmd prompt while running twilio python api doc 为什么我在为我的 Django 项目激活虚拟环境后使用“python manage.py runserver”命令时,我的 CMD 提示不执行任何操作 - Why does my CMD prompt do nothing when I use the “python manage.py runserver” command after activating the virtual environment for my Django project 如何在 CMD 和 PowerShell 之间切换我的 python? - How can I switch my python between CMD and PowerShell? 运行 os.system 命令后,如何将输入传递给 cmd 提示符? - How do I pass inputs to cmd prompt after I have run the os.system command?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM