How do I detect if my python code is running in PowerShell or the Command Prompt (cmd)
@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())
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, subprocessrunning_shell = Nonemycheck='/usr/bin/md5sum' # full path is neededif 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:
$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"}