簡體   English   中英

如何在當前命名空間中獲取 Python 交互式控制台?

[英]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*
>>>

對於 Python 3.10.0:

code.InteractiveConsole(locals=locals()).interact()

有關詳細信息,請參閱Python 文檔

如何從 code.interact 改變 globals() 和 locals()

不幸的是, 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 558PEP 667 go 更詳細,並可能使locals()在 Python 的未來版本中表現得更加一致。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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