子流程最大递归深度超过

时间:2018-11-17 10:30:04

标签: python recursion subprocess

我正在尝试通过使用子进程从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]

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)
    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

1 个答案:

答案 0 :(得分:0)

问题是您多次拨打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)

这可以解决您的问题吗?

编辑:有关该问题的详细说明,请参见here