在一些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')
我认为您正在寻找类似以下代码部分的内容。它应该也适用于Windows。你知道吗
相关问题 更多 >
编程相关推荐