簡體   English   中英

判斷 Python 是否處於交互模式

[英]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.ps1sys.ps2僅在交互模式下定義。

我比較了我找到的所有方法並制作了一個結果表。 最好的似乎是這樣的:

hasattr(sys, 'ps1')

在此處輸入圖片說明

如果有人有其他可能不同的場景,請發表評論,我會添加它

使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM