我正在编写一个脚本(脚本A),需要打开一个新的Python IDLE shell,自动运行另一个脚本(脚本B),然后关闭它。以下代码是我用于此目的的代码:
import sys
sys.argv=['','-n','-t','My New Shell','-c','execfile("VarLoader.py")']
import idlelib.PyShell
idlelib.PyShell.main()
但是我无法自动关闭新shell。我已经尝试将以下内容添加到脚本B中,但要么它不关闭新shell,要么弹出一个窗口询问我是否要杀死它。
exit()
import sys
sys.exit()
答案 0 :(得分:1)
而不是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
不会使用您的子类,您实际上可以创建函数的副本 - 而无需修改原始文件 - 使用{ {1}}将使用您修改过的类的构造函数:
FunctionType
然后你可以像这样运行额外的IDLE shell:
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,让你的程序按你想要的方式工作。 (它也与其他版本的python兼容!)