Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

like image 955
user6371867 Avatar asked May 23 '16 15:05

user6371867


People also ask

How do I test Python code in CMD?

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!

Can we run Python code in command prompt?

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.

Can I run Python code in PowerShell?

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).


1 Answers

@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())
like image 122
Yash Gupta Avatar answered Sep 28 '22 03:09

Yash Gupta