【问题标题】:How to set a timeout period for downloading YouTube video audio using Python and Windows如何使用 Python 和 Windows 设置下载 YouTube 视频音频的超时时间
【发布时间】:2019-05-20 22:04:46
【问题描述】:

在某些 YouTube 链接上,youtube_dl 需要数小时才能尝试下载它们。所以我想为它尝试下载视频设置一个时间限制。在 MAC/Linux 上,您可以使用 Signal 或 Interrupting Cow,但我运行 Windows 并且无法弄清楚如何在一段时间后停止此过程。

我尝试使用其他堆栈溢出的超时信息,特别是

#I got the code immediately below from a different stack overflow post: 


from contextlib import contextmanager
import threading
import _thread

class TimeoutException(Exception):
    def __init__(self, msg=''):
        self.msg = msg

@contextmanager
def time_limit(seconds, msg=''):
    timer = threading.Timer(seconds, lambda: _thread.interrupt_main())
    timer.start()
    try:
        yield
    except KeyboardInterrupt:
        raise TimeoutException("Timed out for operation {}".format(msg))
    finally:
        # if the action ends in specified time, timer is canceled
        timer.cancel()

#This I'm trying to have a timeout for.

if __name__ == '__main__':

    for i in range(len(df)):
        url = df.loc[i, 'url']
        artist_name = df.loc[i, 'Artist']
        track_name = df.loc[i, 'Title']

        html = requests.get(url)

        index_begin = html.text.find('href=\"https://www.youtube.com')
        youtube_link = html.text[index_begin + 6: index_begin + 49]
        print(youtube_link)

        # Run youtube-dl to download the youtube song with the link:
        new_track = artist_name + "--" + track_name
        location = "SongMP3_files/" + new_track + ".%(ext)s"

        process_call = ["youtube-dl", "--audio-format", "mp3", "-x", "-R 2", "--no-playlist", "-o", location, youtube_link]

        try:
            with time_limit(10, 'aahhh'):
                subprocess.run(process_call)
        except TimeoutException:
            print('didn't work')

【问题讨论】:

    标签: python process download subprocess


    【解决方案1】:

    我认为您正在寻找类似于以下代码部分的内容。它也应该在 Windows 上工作。

    from subprocess import Popen, PIPE
    from threading import Timer
    
    def run(cmd, timeout_sec):
        proc = Popen(cmd.split(), stdout=PIPE, stderr=PIPE)
        timer = Timer(timeout_sec, proc.kill)
        try:
            timer.start()
            stdout, stderr = proc.communicate()
        finally:
            timer.cancel()
    
    run("sleep 1", 5)
    run("sleep 5", 1)
    

    【讨论】:

      猜你喜欢
      • 2012-09-02
      • 1970-01-01
      • 2015-02-12
      • 2021-03-28
      • 1970-01-01
      • 2017-02-14
      • 2021-10-06
      • 2020-08-03
      相关资源
      最近更新 更多