["python","interactive","read-eval-print-loop"]
Tell if Python is in interactive mode

In a Python script, is there any way to tell if the interpreter is running in interactive mode? This would be useful so that, for instance, when you run an interactive Python session and import a module, different code can be executed. What I mean is something like this: if __name__ == "__main__": # do stuff elif __pythonIsInteractive__: # do other stuff else: exit()
Python <= 3.12 __main__.__file__ doesn't exist in the interactive interpreter for Python versions <= 3.12: import __main__ print(hasattr(__main__, "__file__")) This also goes for code run via python -c, but not python -m.