告诉Python是否处于交互模式

时间:2010-03-01 14:20:57

标签: python interactive python-2.5 python-2.x

在Python脚本中,有没有办法判断解释器是否处于交互模式?这将非常有用,例如,当您运行交互式Python会话并导入模块时,会执行稍微不同的代码(例如,关闭日志记录)。

我查看了tell whether python is in -i mode并尝试了那里的代码,但是,如果使用-i标志调用Python,则该函数仅返回true,而当用于调用交互模式的命令为{{1没有参数。

我的意思是这样的:

python

7 个答案:

答案 0 :(得分:55)

交互式解释器中不存在

__main__.__file__

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

这也适用于通过python -c运行的代码,但不适用于python -m

答案 1 :(得分:20)

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

答案 2 :(得分:6)

TFM:如果没有给出接口选项,则暗示-i,sys.argv [0]为空字符串(“”),当前目录将添加到sys.path的开头

如果用户使用python并且没有参数调用解释器,如您所述,您可以使用if sys.argv[0] == ''对其进行测试。如果从python -i开始,这也会返回true,但根据文档,它们在功能上是相同的。

答案 3 :(得分:5)

使用sys.flags

if sys.flags.interactive:
    #interactive
else:
    #not interactive 

答案 4 :(得分:3)

我比较了发现的所有方法,并制成了结果表。最好的似乎是这样:

hasattr(sys, 'ps1')

enter image description here

如果任何人有可能会有所不同的其他情况,请发表评论,我将其添加

答案 5 :(得分:1)

以下是使用和不使用-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'

答案 6 :(得分:-4)

这是可行的。将以下代码段放在一个文件中,并将该文件的路径分配给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

相关问题