Tell if Python is in interactive mode

后端 未结 7 1018
北荒
北荒 2020-11-28 10:03

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 sessio

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 10:57

    Here's something that would work. Put the following code snippet in a file, and assign the path to that file to the PYTHONSTARTUP environment variable.

    __pythonIsInteractive__ = None
    

    And then you can use

    if __name__=="__main__":
        #do stuff
    elif '__pythonIsInteractive__' in globals():
        #do other stuff
    else:
        exit()
    

    http://docs.python.org/tutorial/interpreter.html#the-interactive-startup-file

提交回复
热议问题