为何定义runFFmpeg(commandlist)并执行runFFmpeg(buildFFmpeg())能让代码正常运行?
问题解析:修改函数定义与调用让FFmpeg代码生效的原理
问题背景
我创建了commandlist但运行代码时提示ffmpeg未定义,将runFFmpeg()的定义改为def runFFmpeg(commandlist):,并把调用语句改成runFFmpeg(buildFFmpeg())后,代码成功运行,下面解释这两处修改的生效原理。
1. 修改runFFmpeg函数定义:添加参数commandlist
原来的runFFmpeg函数没有定义参数,函数内部执行subprocess.run(commandlist)时,找不到名为commandlist的变量——因为commandlist是在buildFFmpeg函数内部定义的局部变量,作用域仅限于buildFFmpeg函数,无法被其他函数直接访问。
改成def runFFmpeg(commandlist):后,函数声明了一个参数,允许外部向它传入一个变量,这样函数内部的commandlist就有了合法的来源,后续调用subprocess.run时就能正确获取FFmpeg的命令列表,不会再触发变量未定义的错误。
2. 修改调用语句:传入buildFFmpeg()的返回值
buildFFmpeg函数的核心作用是生成FFmpeg的命令列表并返回它。调用runFFmpeg(buildFFmpeg())时,会先执行buildFFmpeg(),得到它返回的命令列表,再把这个列表作为参数传递给runFFmpeg函数。
这一步完成了命令列表的传递:让runFFmpeg函数拿到了具体的FFmpeg命令参数,subprocess.run(commandlist)就能正确调用系统中的FFmpeg程序,执行编码任务。
完整代码示例
def buildFFmpeg(): commandlist = [ "ffmpeg", "-i", inputdic[1], "-c:v", inputdic[4], "-preset", inputdic[3], "-crf", inputdic[2], "-q:v", inputdic[6], "-c:a", inputdic[5], "-b:a", inputdic[7], "output.mkv" ] return commandlist def runFFmpeg(commandlist): print(commandlist) if subprocess.run(commandlist).returncode == 0: print ("FFmpeg Script Ran Successfully") else: print ("There was an error running your FFmpeg script") print('Press 1 to start to encoding or 2 to stop this process') start = input('Press to start: ') x = int(start) if x == 1: runFFmpeg(buildFFmpeg()) else: exit()
内容的提问来源于stack exchange,提问作者jiraiya_sensei
相关产品推荐
相关产品推荐

