如何使用Python和Windows设置下载YouTube视频音频的超时时间

2024-04-24 23:54:02 发布

您现在位置:Python中文网/ 问答频道 /正文

在一些YouTube链接上,YouTube下载需要几个小时。所以我想设置一个时间限制,限制它下载视频的时间。在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')

Tags: thenameimporturldffortimeyoutube
1条回答
网友
1楼 · 发布于 2024-04-24 23:54:02

我认为您正在寻找类似以下代码部分的内容。它应该也适用于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)

相关问题 更多 >