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?
Edit: I've decided to use psutil
to find the name of the parent process. Thanks to everyone who helped in the comments.
To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World!
Make Sure Your Terminal or Command Prompt Can Run Python To do this, open the command prompt, type python and press 'Enter'. You should see a message that documents the Python version that is being used followed by >>> , which indicates the next code you type will be executed by the Python interpreter.
You just type in your code and run it. Let's try it! With your PowerShell command line open, enter python to run the Python 3 interpreter. (Some instructions prefer to use the command py or python3 , these should also work).
@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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With