首页 > 解决方案 > 超出子进程最大递归深度

问题描述

我正在尝试使用子进程从 Spotify 桌面应用程序窗口标题当前播放曲目名称。一般来说,我的代码是有效的。但是当尝试每五秒检索一次歌曲名称时,我得到 RecursionError。问题出在哪里?

代码1

def title_of_window(self,window_class):
    """
        Retrieves the title of application by through 'subprocess'.

        Params:
            window_class (string) -- name of the application to be taken the title
                ex. --> spotify
                    --> filezilla
                    --> putty
                    --> atom

        For this app:
            - window_class parameter must be equal to "spotify"
            - Retrieves the current playing song name from Spotify.

    """
    # Finds id of all GUI apps who running.
    # Ex. -> ['0x200000a', '0x3800007', '0x4800001', '0x2e00010', '0x3600001\n']
    active_windows = subprocess.Popen(["xprop",
                                       "-root",
                                       "_NET_CLIENT_LIST_STACKING"],
                                       stdout=subprocess.PIPE).communicate()
    active_windows_ids = active_windows[0].decode("utf-8").split("# ")[1].split(", ")
    #
    # Sends all ids to 'xprop -id' and checks. If app name equal to window_class parameter, return title of this app.
    # Ex. -> get_window.py — ~/Desktop/projects — Atom
    for active_id in active_windows_ids:
        window = subprocess.Popen(["xprop",
                                    "-id",
                                    active_id.strip(),
                                    "WM_CLASS",
                                    "_NET_WM_NAME"],
                                    stdout=subprocess.PIPE).communicate()
        window = window[0].decode("utf-8").split('"')
        if window_class == window[3].lower():
            return window[5]

主循环

def run(self):
    song = self.title_of_window(self.SPOTIFY)
    if self.temp_song_name != song:
        lyric = self.get_lyric(song)
        self.add_lyric_to_tk(song,lyric)
    else:
        self.add_lyric_to_tk(song, "Not Found")
    self.top.after(5000,self.run)
    self.top.mainloop()

错误:

File "spotifyLyric.py", line 137, in run
    song = self.title_of_window(self.SPOTIFY)
File "spotifyLyric.py", line 51, in title_of_window
    stdout=subprocess.PIPE).communicate()
RecursionError: maximum recursion depth exceeded while calling a Python object

标签: pythonrecursionsubprocess

解决方案


问题是您要self.top.mainloop()多次调用。您应该能够通过将调用移动self.top.mainloop()到您的__init__()方法来修复错误。

def __init__(self):
    ...
    self.run()
    self.top.mainloop()

def run(self):
    song = self.title_of_window(self.SPOTIFY)
    if self.temp_song_name != song:
        lyric = self.get_lyric(song)
        self.add_lyric_to_tk(song,lyric)
    else:
        self.add_lyric_to_tk(song, "Not Found")
    self.top.after(5000,self.run)

这能解决你的问题吗?

编辑:有关问题的详细描述,请参见此处


推荐阅读