【问题标题】:Is there a way to make python become interactive in the middle of a script?有没有办法让 python 在脚本中间变得可交互?
【发布时间】:2011-02-06 05:10:38
【问题描述】:

我想做这样的事情:

do lots of stuff to prepare a good environement
become_interactive
#wait for Ctrl-D
automatically clean up

python 有可能吗?如果没有,你有没有看到另一种做同样事情的方法?

【问题讨论】:

  • 谢谢大家!作为记录,使用代码模块实现此目的的最简单方法如下: import code code.interact(local=globals())
  • 要将局部变量也放入命名空间,您需要code.interact(local=dict(globals(), **locals())。注意添加**locals。我自己也想知道这个问题,您的评论是我找到的最佳答案:-)

标签: python scripting interactive


【解决方案1】:

你可以调用 python 本身:

import subprocess

print "Hola"

subprocess.call(["python"],shell=True)

print "Adios"

【讨论】:

    【解决方案2】:

    code 模块将允许您启动 Python REPL。

    【讨论】:

      【解决方案3】:

      不完全是你想要的,但是 python -i 将在执行脚本后启动交互式提示。

      -i :在运行脚本(也是 PYTHONINSPECT=x)并强制提示后进行交互检查,即使标准输入看起来不是终端

      $ python -i your-script.py
      Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03) 
      ...
      >>> 
      

      【讨论】:

        【解决方案4】:

        在启动 Python 时使用 -i 标志并设置在清理时运行的 atexit 处理程序。

        文件脚本.py:

        import atexit
        def cleanup():
            print "Goodbye"
        atexit.register(cleanup)
        print "Hello"
        

        然后您只需使用 -i 标志启动 Python:

        C:\temp>\python26\python -i script.py
        Hello
        >>> print "interactive"
        interactive
        >>> ^Z
        
        Goodbye
        

        【讨论】:

          【解决方案5】:

          详细说明 IVA 的答案:embedding-a-shell,包含 code 和 Ipython。

          def prompt(vars=None, message="welcome to the shell" ):
              #prompt_message = "Welcome!  Useful: G is the graph, DB, C"
              prompt_message = message
              try:
                  from IPython.Shell import IPShellEmbed
                  ipshell = IPShellEmbed(argv=[''],banner=prompt_message,exit_msg="Goodbye")
                  return  ipshell
              except ImportError:
                  if vars is None:  vars=globals()
                  import code
                  import rlcompleter
                  import readline
                  readline.parse_and_bind("tab: complete")
                  # calling this with globals ensures we can see the environment
                  print prompt_message
                  shell = code.InteractiveConsole(vars)
                  return shell.interact
          
          p = prompt()
          p()
          

          【讨论】:

            【解决方案6】:

            使用 IPython v1.0,您可以简单地使用

            from IPython import embed
            embed()
            

            docs 中显示了更多选项。

            【讨论】:

            • 你可以在任何地方使用它并且它保留了范围。
            • 我真希望我以前知道这一点!谢谢
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-19
            • 2013-03-26
            • 1970-01-01
            相关资源
            最近更新 更多