Reputation: 201
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
.
I haven't been able to figure out how to detect if the application is running in powershell
or 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.
Is there a nicer way?
Upvotes: 19
Views: 5205
Reputation: 349
@Matt A. is right. Use psutil
and os
package to get the parent process id and the name.
parent_pid = os.getppid()
print(psutil.Process(parent_pid).name())
Upvotes: 3
Reputation: 3557
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.
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'
Upvotes: 1
Reputation: 734
Based on this post, you should be able to run this CMD/PS command through the subprocess
module in your Python script:
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.
Upvotes: -1