gpt4 book ai didi

python - 将参数传递给 Python subprocess.Popen

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:41 36 4
gpt4 key购买 nike

我正在转换 this bash script到 Python。我现在有一个可用的 Python 版本。然而,为了让它工作,我不得不将传递给 subprocess.Popen() 的命令变成一个长字符串。 我不想使用一个长命令字符串。我希望将其分解为适当的单独参数。在这个特定的示例中,我如何做到这一点?

我的具体问题是如何更改此行:

process = subprocess.Popen(cmd, shell=True, ...

变成这样的形式:

process = subprocess.Popen([prog, inf, arate, outf], shell=False, ...

这是我的完整代码,以便上面的片段有意义:

#!/usr/bin/env python

import sys
import subprocess
import os.path
import argparse #requires Python 2.7 or above

parser = argparse.ArgumentParser(description='Converts (.M4V) videos into (.MP3) audio files using ffmpeg.')
parser.add_argument('-d','--directory', help='Source directory name',required=True)
parser.add_argument('-o','--output',help='Output directory name', required=False)
parser.add_argument('-a','--arate',help='ffmpeg\'s arate option', default="64K", required=False)
parser.add_argument('-s','--source',help='Input type; e.g., file ext (default .m4v)', default=".m4v", required=False)
parser.add_argument('-e','--ext',help='Output type; e.g., file ext (default .mp3)', default=".mp3", required=False)
parser.add_argument('-p','--program',help='application program e.g., /usr/bin/ffmpeg', default="/usr/bin/ffmpeg", required=False)
args = parser.parse_args()

arate = args.arate
source = args.source
new_ext = args.ext
prog = args.program
in_path = args.directory

if(not args.output):
out_path = in_path
else:
out_path = args.output

if(not os.path.isfile(prog)):
print("Command {} does not exist".format(prog))

else:
try:
filenames = os.listdir(in_path)
for file in filenames:
print("name={}\nextension={}".format(name, extension))
if(extension == source):
inf = os.path.join(in_path, file)
outf = os.path.join(out_path, name + new_ext)
cmd = "{xprog} -i '{xpath}' -b:a {art} -vn '{xout}'".format(xprog=prog, xpath=inf, art=arate, xout=outf)
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
stdout,stderr = process.communicate()
return_code = process.poll()
print("stdout='{}'\nstderr='{}'\nreturn_code='{}'".format(stdout, stderr, return_code))
except IOError as e:
print("Error: file not found.")

最佳答案

如果在您的初始示例中传递“shell=True”,那么 the docs 中的注释是相关的:

The shell argument (which defaults to False) specifies whether to use the shell as the program to execute. If shell is True, it is recommended to pass args as a string rather than as a sequence

在这种情况下:

subprocess.Popen(['ls -l'], shell=True)

结果:

total 1416
-rw-r--r-- 1 me AD\Domain Users 17 Nov 3 01:17 file1
drwxr-xr-x 7 me AD\Domain Users 238 Jan 22 15:34 dir
-rw-r--r-- 1 me AD\Domain Users 368 Nov 14 22:39 file2.xml

关于python - 将参数传递给 Python subprocess.Popen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21299155/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com