Python IDLE源码分析-pyshell.py(四)

本文探讨了Python IDLE中 ModifiedInterpreter 的角色,它作为每个shell窗口的内置解释器,而非直接使用Python根目录的exe。通过分析源码,揭示其独立的输入/输出/错误流和解释执行机制,解释了IDLE如何实现交互功能。未来作者将不再为源码添加详细注释,可能考虑在GitHub上分享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件作用

    ModifiedInterpreter对应的实例是每一个shell窗口中嵌入的解释器。很多时候,我们以为在IDLE中运行代码是直接调用的Python根目录里的exe,其实并非如此——code模块允许开发者向它们的Python源码中再次嵌入解释器。但这个比较冷门,很少见,网上也难以查到。不过,要证明IDLE嵌入的是模块中的类很简单——重新编译Python源代码,改写其中的输出流,再替换,运行IDLE,然而IDLE中的输出流并未改变。


文件源码

class ModifiedInterpreter(InteractiveInterpreter):

    def __init__(self, tkconsole):
    	# 一些流信息。
        self.tkconsole = tkconsole
        locals = sys.modules['__main__'].__dict__
        # locals通过__dict__属性访问sys.modules['__main__']所有属性。
        # 一些解释器信息。
        InteractiveInterpreter.__init__(self, locals=locals)
        self.restarting = False
        self.subprocess_arglist = None
        self.port = PORT
        self.original_compiler_flags = self.compile.compiler.flags

    _afterid = None
    rpcclt = None
    rpcsubproc = None

    def spawn_subprocess(self):
        if self.subprocess_arglist is None:
            self.subprocess_arglist = self.build_subprocess_arglist()
        self.rpcsubproc = subprocess.Popen(self.subprocess_arglist)

    def build_subprocess_arglist(self):
        assert (self.port != 0), (
            "Socket should have been assigned a port number.")
        w = ['-W' + s for s in sys.warnoptions]
        # Maybe IDLE is installed and is being accessed via sys.path,
        # or maybe it's not installed and the idle.py script is being
        # run from the IDLE source directory.
        del_exitf = idleConf.GetOption('main', 'General', 'delete-exitfunc',
                                       default=False, type='bool')
        command = "__import__('idlelib.run').run.main(%r)" % (del_exitf,)
        return [sys.executable] + w + ["-c", command, str(self.port)]

    def start_subprocess(self):
        addr = (HOST, self.port)
        # GUI makes several attempts to acquire socket, listens for connection
        for i in range(3):
            time.sleep(i)
            try:
                self.rpcclt = MyRPCClient(addr)
                break
            except OSError:
                pass
        else:
            self.display_port_binding_error()
            return None
        # if PORT was 0, system will assign an 'ephemeral' port. Find it out:
        self.port = self.rpcclt.listening_sock.getsockname()[1]
        # if PORT was not 0, probably working with a remote execution server
        if PORT != 0:
            # To allow reconnection within the 2MSL wait (cf. Stevens TCP
            # V1, 18.6),  set SO_REUSEADDR.  Note that this can be problematic
            # on Windows since the implementation allows two active sockets on
            # the same address!
            self.rpcclt.listening_sock.setsockopt(socket.SOL_SOCKET,
                                                  socket.SO_REUSEADDR, 1)
        self.spawn_subprocess()
        # time.sleep(20) # test to simulate GUI not accepting connection
        # Accept the connection from the Python execution server
        self.rpcclt.listening_sock.settimeout(10)
        try:
            self.rpcclt.accept()
        except socket.timeout:
            self.display_no_subprocess_error()
            return None
        self.rpcclt.register("console", self.tkconsole)
        self.rpcclt.register("stdin", self.tkconsole.stdin)
        self.rpcclt.register("stdout", self.tkconsole.stdout)
        self.rpcclt.register("stderr", self.tkconsole.stderr)
        self.rpcclt.register("flist", self.tkconsole.flist)
        self.rpcclt.register("linecache", linecache)
        self.rpcclt.register("interp", self)
        self.transfer_path(with_cwd=
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值