代码之家  ›  专栏  ›  技术社区  ›  Chinmay Kanchi

告诉Python是否处于交互模式

  •  40
  • Chinmay Kanchi  · 技术社区  · 14 年前

    我看过 tell whether python is in -i mode 并且在那里尝试了代码,但是,该函数仅在使用-i标志调用Python时返回true,而在调用交互模式的命令为 python 没有争论。

    我的意思是这样的:

    if __name__=="__main__":
        #do stuff
    elif __pythonIsInteractive__:
        #do other stuff
    else:
        exit()
    
    6 回复  |  直到 7 年前
        1
  •  69
  •   Ignacio Vazquez-Abrams    14 年前

    __main__.__file__

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

    这也适用于通过 python -c python -m .

        2
  •  27
  •   Cristian Ciupitu    10 年前

    sys.ps1 sys.ps2 仅在交互模式下定义。

        3
  •  17
  •   pyjamas    4 年前

    我比较了我找到的所有方法,并制作了一个结果表。最好的是:

    hasattr(sys, 'ps1')
    

    enter image description here

        4
  •  12
  •   Cristian Ciupitu    10 年前

    使用 sys.flags :

    if sys.flags.interactive:
        #interactive
    else:
        #not interactive 
    
        5
  •  7
  •   wersimmon    14 年前

    从…起 TFM :如果未提供接口选项,则暗示-i,sys.argv[0]为空字符串(“”),当前目录将添加到sys.path的开头。

    如果用户使用 python 正如你提到的,没有参数,你可以用 if sys.argv[0] == '' . 如果以开头,则返回true python -i ,但根据文档,它们在功能上是相同的。

        6
  •  1
  •   jdines    10 年前

    以下内容在使用和不使用-i开关时均有效:

    #!/usr/bin/python
    import sys
    # Set the interpreter bool
    try:
        if sys.ps1: interpreter = True
    except AttributeError:
        interpreter = False
        if sys.flags.interactive: interpreter = True
    
    # Use the interpreter bool
    if interpreter: print 'We are in the Interpreter'
    else: print 'We are running from the command line'
    
        7
  •  -4
  •   JAB    13 年前

    这是一个可行的办法。将以下代码段放入文件中,并将该文件的路径指定给 PYTHONSTARTUP 环境变量。

    __pythonIsInteractive__ = None
    

    然后你可以使用

    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