[英]Tell if Python is in interactive mode
在 Python 腳本中,有沒有辦法判斷解釋器是否處於交互模式? 這將很有用,例如,當您運行交互式 Python 會話並導入模塊時,執行的代碼略有不同(例如,關閉日志記錄)。
我查看了告訴 python 是否處於 -i 模式並在那里嘗試了代碼,但是,該函數僅在使用 -i 標志調用 Python 時才返回 true,而不是在用於調用交互模式的命令是python
時不返回 true論據。
我的意思是這樣的:
if __name__=="__main__":
#do stuff
elif __pythonIsInteractive__:
#do other stuff
else:
exit()
__main__.__file__
在交互式解釋器中不存在:
import __main__ as main
print hasattr(main, '__file__')
這也適用於通過python -c
運行的代碼,但不適用於python -m
。
使用sys.flags
:
if sys.flags.interactive:
#interactive
else:
#not interactive
來自TFM :如果沒有給出接口選項,則隱含 -i,sys.argv[0] 是一個空字符串 (""),當前目錄將被添加到 sys.path 的開頭。
如果用戶使用python
調用解釋器並且沒有參數,如您所提到的,您可以使用if sys.argv[0] == ''
。 如果以python -i
開頭,這也會返回 true ,但根據文檔,它們在功能上是相同的。
以下內容在使用和不使用 -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'
這是有用的東西。 將以下代碼片段放入文件中,並將該文件的路徑分配給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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.