代码之家  ›  专栏  ›  技术社区  ›  Kevin Bell

无提示关闭Python IDLE shell

  •  1
  • Kevin Bell  · 技术社区  · 10 年前

    我正在编写一个脚本(脚本a),需要打开一个新的Python IDLE shell,在其中自动运行另一个脚本,然后关闭它。以下代码是我用于此目的的代码:

    import sys
    sys.argv=['','-n','-t','My New Shell','-c','execfile("VarLoader.py")']
    import idlelib.PyShell
    idlelib.PyShell.main()
    

    然而,我无法自动关闭新外壳。我尝试将以下内容添加到脚本B中,但要么它没有关闭新的shell,要么弹出一个窗口询问我是否要杀死它。

    exit()
    

    .

    import sys
    sys.exit()
    
    1 回复  |  直到 10 年前
        1
  •  1
  •   Tadhg McDonald-Jensen    10 年前

    我建议您创建一个子类来代替monkeypatching或修改IDLE源代码以使您的程序跳过退出提示 PyShell 覆盖 close 方法:

    import idlelib.PyShell
    class PyShell_NoExitPrompt(idlelib.PyShell.PyShell):
        def close(self):
            "Extend EditorWindow.close(), does not prompt to exit"
    ##        if self.executing:
    ##            response = tkMessageBox.askokcancel(
    ##                "Kill?",
    ##                "Your program is still running!\n Do you want to kill it?",
    ##                default="ok",
    ##                parent=self.text)
    ##            if response is False:
    ##                return "cancel"
            self.stop_readline()
            self.canceled = True
            self.closing = True
            return idlelib.PyShell.EditorWindow.close(self)
    

    最初的问题是,使用 idlelib.PyShell.main 不会使用您的子类,您实际上可以创建一个 复制 使用 FunctionType 将使用修改后的类的构造函数:

    import functools
    from types import FunctionType
    
    def copy_function(f, namespace_override):
        """creates a copy of a function (code, signature, defaults) with a modified global scope"""
        namespace = dict(f.__globals__)
        namespace.update(namespace_override)
        new_f = FunctionType(f.__code__, namespace, f.__name__, f.__defaults__, f.__closure__)
        return functools.update_wrapper(f, new_f)
    

    然后您可以像这样运行额外的IDLE shell:

    import sys
    #there is also a way to prevent the need to override sys.argv but that isn't as concerning to me.
    sys.argv = ['','-n','-t','My New Shell','-c','execfile("VarLoader.py")']
    hacked_main = copy_function(idlelib.PyShell.main,
                                {"PyShell":PyShell_NoExitPrompt})
    
    hacked_main()
    

    现在,您可以让IDLE保持原样,让您的程序也按您希望的方式运行。(它还与其他版本的python兼容!)