Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tell if Python is in interactive mode

In a Python script, is there any way to tell if the interpreter is in interactive mode? This would be useful so that, for instance, when you run an interactive Python session and import a module, slightly different code is executed (for example, logging is turned off).

I've looked at tell whether python is in -i mode and tried the code there, however, that function only returns true if Python has been invoked with the -i flag and not when the command used to invoke interactive mode is python with no arguments.

What I mean is something like this:

if __name__=="__main__":     #do stuff elif __pythonIsInteractive__:     #do other stuff else:     exit() 
like image 805
Chinmay Kanchi Avatar asked Mar 01 '10 14:03

Chinmay Kanchi


People also ask

Does Python have an interactive mode?

There are two modes through which we can create and run Python scripts: interactive mode and script mode. The interactive mode involves running your codes directly on the Python shell which can be accessed from the terminal of the operating system.

How do I get out of interactive mode in Python?

Go to File -> New Window (Ctrl+N) and a window where you can write your program will pop up.

How do you change from interactive mode to script mode in Python?

Step 1: Open the Python IDE and open the script file in Python IDE using the open option given. Or, we can even use the 'F5' button shortcut to run the script file in the Python IDE. That's how we can run or execute our Python script file using the Python IDE installed in our system.

What is the difference between interactive mode in Python?

Script Mode, is used when the user is working with more than one single code or a block of code. Interactive mode is used when an user wants to run one single line or one block of code. If one needs to write a long piece of Python code or if the Python script spans multiple files, interactive mode is not recommended.


1 Answers

__main__.__file__ doesn't exist in the interactive interpreter:

import __main__ as main print hasattr(main, '__file__') 

This also goes for code run via python -c, but not python -m.

like image 151
Ignacio Vazquez-Abrams Avatar answered Sep 21 '22 05:09

Ignacio Vazquez-Abrams