问题描述
在某些YouTube链接上,youtube_dl需要花费数小时才能尝试下载它们.因此,我想对尝试下载视频的时间设置一个时间限制.在MAC/Linux上,您可以使用Signal或Interrupting Cow,但是我运行Windows,并且无法弄清楚如何在一段时间后停止该过程.
On some YouTube links youtube_dl takes hours to try to download them. So I want to set a time limit on how long it tries to download a video for. On MAC/Linux you can use Signal or Interrupting Cow, but I run Windows and can't figure out how to stop this process after some time.
我尝试使用其他堆栈溢出中有关超时的一些信息,尤其是
I've tried using some info on timeout from other stack overflow, in particular
#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')
推荐答案
我认为您正在寻找类似以下代码部分的内容.它也应该在Windows上运行.
I think you are looking for something similar like the following code part. It should work on Windows as well.
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)
这篇关于如何设置超时时间,以使用Python和Windows下载YouTube视频音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!