【问题标题】:How to get Python interactive console in current namespace?如何在当前命名空间中获取 Python 交互式控制台?
【发布时间】:2011-11-02 04:33:42
【问题描述】:

我想让我的 Python 代码在运行代码的过程中使用 code.interact() 之类的东西启动一个 Python 交互式控制台 (REPL)。但是 code.interact() 启动的控制台看不到当前命名空间中的变量。我该怎么做:

mystring="你好"

code.interact()

...然后在启动的交互式控制台中,我应该能够键入 mystring 并获得“hello”。这可能吗?我是否需要将 code.interact() 的“本地”参数设置为某些东西?这将设置为什么?应该怎么称呼?

【问题讨论】:

    标签: python variables namespaces console read-eval-print-loop


    【解决方案1】:

    试试:

    code.interact(local=locals())
    

    【讨论】:

    • 如果您还想要全局变量,请使用以下代码:code.interact(local=dict(globals(), **locals()))
    • 是否有机会将更改(从控制台,如 a=3232)反馈到调用者脚本?
    【解决方案2】:

    为了调试,我通常使用这个

    from pdb import set_trace; set_trace()
    

    可能有帮助

    【讨论】:

      【解决方案3】:

      另一种方法是启动调试器,然后运行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*
      >>>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-06
        • 2018-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-06
        • 2016-06-20
        • 1970-01-01
        相关资源
        最近更新 更多