判断Python是否处于交互模式 [英] Tell if Python is in interactive mode

查看:276
本文介绍了判断Python是否处于交互模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python脚本中,是否有任何方法可以判断解释器是否处于交互模式?这将很有用,例如,当您运行交互式Python会话并导入模块时,将执行略有不同的代码(例如,关闭日志记录).

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 session and import a module, slightly different code is executed (for example, logging is turned off).

我查看了告诉python是否处于-i模式并尝试了其中的代码,但是,仅当使用-i标志调用Python时,该函数才返回true;否则,当用于调用交互模式的命令为python不带参数时,该函数将返回true.

I've looked at tell whether python is in -i mode and tried the code there, however, that function only returns true if Python has been invoked with the -i flag and not when the command used to invoke interactive mode is python with no arguments.

我的意思是这样的:

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

推荐答案

__main__.__file__在交互式解释器中不存在:

__main__.__file__ doesn't exist in the interactive interpreter:

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

这也适用于通过python -c而不是python -m运行的代码.

This also goes for code run via python -c, but not python -m.

这篇关于判断Python是否处于交互模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆