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