代码如下:
import asyncio import os async def split_video(video_path): print("开始执行{}目录下的操作:".format(video_path)) split_file = os.path.split(video_path) # 分割文件名与目录 split_filename = os.path.splitext(split_file[1]) # 分离文件名和扩展名 os.chdir(split_file[0]) # 切换目录 try: touch_dir = os.mkdir(split_filename[0]) # 创建文件夹, except Exception as e: print("文件已存在,请检查文件目录") os.system("pause") raise e os.chdir(split_filename[0]) # 切换目录至新建文件夹里面 print("切割后的图片保存到:{}".format(os.getcwd())) await asyncio.sleep(1) # 此处阻塞,会不等待,直接执行后面的操作 os.popen("ffmpeg -i {} -r 60 %d.jpg".format(video_path)).read() async def main(): task_list = [asyncio.create_task(split_video(r"D:Video1.mp4")), asyncio.create_task(split_video(r"D:Video2.mp4"))] done = await asyncio.wait(task_list) print(done) asyncio.run(main())
查看运行结果:
如图:第一个任务sleep后并没有等待,直接执行第2个任务,这就是异步操作。