问题描述:
有时在写python时,我们希望可以直接执行cmd命令,但是却不会提示报错,也没得到预期结果,如文件没有如期创建。这往往是权限不足的问题。举个例子:
执行如下操作时:
os.system(f'D:\ffmpeg\ffmpeg-n6.1.1-94-gf914c18de5-win64-lgpl-shared-6.1\bin\ffmpeg.exe -i "{new_video_file_path}" -ar 16000 -ac 1 -c:a pcm_s16le "{audio_file}"')
或是
command = f'D:\\ffmpeg\\ffmpeg-n6.1.1-94-gf914c18de5-win64-lgpl-shared-6.1\\bin\\ffmpeg.exe -i {new_video_file_path} -ar 16000 -ac 1 -c:a pcm_s16le {audio_file}'
subprocess.run(command, shell=True)
都不会报错和失败,但是最终却看不到文件的输出,根本原因是权限不够。
解决方案:
只能算是曲线救国,通过创建bat脚本写入命令在去执行bat脚本,可以绕过缺少系统权限的问题。
简单的参考代码:
import subprocess
import os
#写需要执行的命令
command = f'D:\\ffmpeg\\ffmpeg-n6.1.1-94-gf914c18de5-win64-lgpl-shared-6.1\\bin\\ffmpeg.exe -i {new_video_file_path} -ar 16000 -ac 1 -c:a pcm_s16le {audio_file}'
print('command', command)
def write_batch_file(batch_file_path, command):
with open(batch_file_path, "w") as batch_file:
batch_file.write(command)
# 获取当前目录
current_directory = os.getcwd()
# bat脚本路径
batch_file_path = os.path.join(current_directory, "run_ffmpeg.bat")
# 将命令写入批处理文件
write_batch_file(batch_file_path, command)
# 执行
result = subprocess.run(batch_file_path, shell=True)
if result2.returncode == 0:
print("命令执行成功!")
else:
print("命令执行失败!")