Как установить период ожидания для загрузки видео с аудио YouTube с помощью Python и Windows - PullRequest
0 голосов
/ 21 мая 2019

На некоторых ссылках 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')

1 Ответ

0 голосов
/ 21 мая 2019

Я думаю, что вы ищете что-то похожее на следующую часть кода.Это должно работать и на 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...