Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find out if a python script is running in IDLE or terminal/command prompt

Is there a way to find out if the python script is running in the IDLE interpreter or the terminal?

Works cross-platform if possible, or if needed a different way for each platform.

Work with Python 2 and Python 3 if possible, or if needed a different way for each version.

The only way I could think of is checking the processes running for IDLE but I don't know how to do that right.

If IDLE is open for another script and my script is running in the terminal, a process check would return true even if my script is not running in the IDLE.

My script needs to run differently depending on if it is running in IDLE or a terminal.

like image 720
freeforall tousez Avatar asked Jun 16 '13 13:06

freeforall tousez


People also ask

How do you know if Python script is running?

I usually use ps -fA | grep python to see what processes are running. The CMD will show you what python scripts you have running, although it won't give you the directory of the script.

How do I test a Python script in terminal?

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! If everything works okay, after you press Enter , you'll see the phrase Hello World!

Is IDLE the Python terminal?

Using IDLEIDLE is the standard Python development environment. Its name is an acronym of "Integrated DeveLopment Environment". It works well on both Unix and Windows platforms. It has a Python shell window, which gives you access to the Python interactive mode.


1 Answers

This seems to work on Python3/Linux

import sys

print("idlelib" in sys.modules)

If will return True if the script is run from Idle, False otherwise. Please test for other combination of Python/OS !

like image 68
Sylvain Leroux Avatar answered Sep 23 '22 07:09

Sylvain Leroux