【发布时间】: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