【os.system subprocess】python程序执行cmd命令缺少权限问题的解决

问题描述:

         有时在写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("命令执行失败!")

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

J_Emiya_Kiritsugu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值