[英]How to get Python interactive console in current namespace?
我想讓我的 Python 代碼在運行代碼的中間使用 code.interact() 之類的東西啟動 Python 交互式控制台 (REPL)。 但是 code.interact() 啟動的控制台看不到當前命名空間中的變量。 我該怎么做:
我的字符串=“你好”
代碼.interact()
...然后在啟動的交互式控制台中,我應該能夠鍵入 mystring 並獲得“hello”。 這可能嗎? 我是否需要將 code.interact() 的“本地”參數設置為某個值? 這會被設置成什么? 應該怎么稱呼?
嘗試:
code.interact(local=locals())
對於調試,我通常使用這個
from pdb import set_trace; set_trace()
它可能有幫助
另一種方法是啟動調試器,然后運行interact
:
import pdb
pdb.set_trace()
然后從調試器:
(Pdb) help interact
interact
Start an interactive interpreter whose global namespace
contains all the (global and local) names found in the current scope.
(Pdb) interact
*interactive*
>>>
不幸的是, code.interact
不允許您從當前命名空間同時傳遞globals()
和locals()
,除非您將它們復制到單個字典中,例如code.interact(local={**globals(), **locals()})
,但隨后您對globals()
和locals()
所做的更改將不會保留。
但是,您可以通過子類化控制台並覆蓋其runcode
方法來解決此問題:
import code
try:
import readline
except ImportError:
pass
class MyInteractiveConsole(code.InteractiveConsole):
"""Extends InteractiveConsole to also pass globals to exec."""
def __init__(self, globals, *args, **kwargs):
code.InteractiveConsole.__init__(*args, **kwargs)
self.globals = globals
def runcode(self, code):
try:
exec(code, self.globals, self.locals)
except SystemExit:
raise
except:
self.showtraceback()
在某處定義了它之后,您可以像code.interact
一樣使用它:
MyInteractiveConsole(globals(), locals()).interact()
除了這會讓你閱讀和改變全局變量和本地變量:
x = 7
將設置一個本地global x; x = 7
global x; x = 7
將設置全局當您使用 Ctrl+D(或 Ctrl+Z,然后在 Windows 上按 Enter)離開交互式控制台時,您所做的更改應該保留在您的globals()
和locals()
中。
警告: locals() 的文檔警告:
本詞典內容不得修改; 更改可能不會影響解釋器使用的局部變量和自由變量的值。
所以不要依賴locals()
的這些突變來完成任何關鍵任務。 PEP 558和PEP 667 go 更詳細,並可能使locals()
在 Python 的未來版本中表現得更加一致。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.