将参数传递到Python subprocess.Popen [英] Passing parameters to Python subprocess.Popen

查看:1326
本文介绍了将参数传递到Python subprocess.Popen的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我转换这个bash脚本到Python。我现在有一个工作的Python版本。然而,为了得到它的工作,我不得不砍我通过它变成一个长字符串传递到subprocess.Popen()命令。 我不希望使用一个长的命令字符串。我想打入正确的个别参数这一点。我怎样才能做到,在这种的具体的例子吗?

我的具体问题是我要如何改变这一行:

  =过程subprocess.Popen(CMD,壳= TRUE,...

成这样的形式:

  =过程subprocess.Popen([PROG,INF,独的,OUTF],壳=假,...

下面是我的完整code,使上述片段才​​有意义:

 #!的/ usr /斌/包膜蟒蛇进口SYS
进口子
进口os.path中
进口argparse #requires Python 2.7版或以上解析器= argparse.ArgumentParser(说明='转换(的.m4v)视频到使用的ffmpeg(.MP3)的音频文件。')
parser.add_argument(' - D',' - 目录,有利于='源目录名',需要= TRUE)
parser.add_argument(' - O',' - 产出,帮助=输出目录名',需要= FALSE)
parser.add_argument(' - 一',' - 独的',帮助='ffmpeg的\\的独的选项,默认为64K,要求= FALSE)
parser.add_argument(;M4V' - - S','源',帮助=输入型例如,文件EXT(默认的.m4v),默认值=所需= FALSE)
parser.add_argument(' - E',' - 分机',帮助='输出类型,例如,文件EXT(默认.MP3),默认为MP3,要求= FALSE)
parser.add_argument(' - P, - 项目,帮助='应用程序例如,在/ usr /斌/的ffmpeg,默认为在/ usr /斌/的ffmpeg,要求= FALSE)
ARGS = parser.parse_args()独的= args.arate
来源= args.source
new_ext = args.ext
PROG = args.program
in_path = args.directory如果(不args.output):
    out_path = in_path
其他:
    out_path = args.output如果(未os.path.isfile(PROG)):
    打印(命令{}不存在.format(PROG))其他:
    尝试:
        文件名= os.listdir(in_path)
        在文件名的文件:
            打印(NAME = {} \\ nextension = {}格式(名称,扩展))
            如果(扩展==源):
                INF = os.path.join(in_path,文件)
                OUTF = os.path.join(out_path,名称+ new_ext)
                CMD ={} XPROG -i{} XPath的-b:{一}艺术-vn{} XOUT'。格式(XPROG = PROG,XPath的= INF,艺术=独的,XOUT = OUTF)
                流程= subprocess.Popen(CMD,壳= TRUE,标准输出= subprocess.PIPE,标​​准错误= subprocess.PIPE,标​​准输入= subprocess.PIPE)
                标准输出,标准错误= process.communicate()
                return_ code = process.poll()
                打印(标准输出='{}'\\ nstderr ='{}'\\ nreturn_ code ='{}'。格式(标准输出,标准错误,return_ code)条)
    除了IO错误为e:
        打印(错误:未找到文件。)


解决方案

下面是正确的参数一个完整的工作解决方案POPEN()。

 导入子
进口os.path中
进口argparse #requires Python 2.7版或以上解析器= argparse.ArgumentParser(说明='转换(的.m4v)视频到使用的ffmpeg(.MP3)的音频文件。')
parser.add_argument(' - D',' - 目录,有利于='源目录名',需要= TRUE)
parser.add_argument(' - O',' - 产出,帮助=输出目录名',需要= FALSE)
parser.add_argument(' - 一',' - 独的',帮助='ffmpeg的\\的独的选项,默认为64K,要求= FALSE)
parser.add_argument(;M4V' - - S','源',帮助=输入型例如,文件EXT(默认的.m4v),默认值=所需= FALSE)
parser.add_argument(' - E',' - 分机',帮助='输出类型,例如,文件EXT(默认.MP3),默认为MP3,要求= FALSE)
parser.add_argument(' - P, - 项目,帮助='应用程序例如,在/ usr /斌/的ffmpeg,默认为在/ usr /斌/的ffmpeg,要求= FALSE)
ARGS = parser.parse_args()独的= args.arate
来源= args.source
new_ext = args.ext
PROG = args.program
in_path = args.directory如果(不args.output):
    out_path = in_path
其他:
    out_path = args.output如果(未os.path.isfile(PROG)):
    打印(命令{}不存在.format(PROG))其他:
    尝试:
        文件名= os.listdir(in_path)
        在文件名的文件:
            名,扩展名= os.path.splitext(文件)
            如果(扩展==源):
                打印(处理:{}格式(文件)。)
                INF = os.path.join(in_path,文件)
                OUTF = os.path.join(out_path,名称+ new_ext)
                流程= subprocess.Popen([PROG-i,天道酬勤,-b:一个,独的,-vn,OUTF],壳=假,标准输出= subprocess.PIPE,标​​准错误= subprocess.PIPE,标​​准输入= subprocess.PIPE)
                标准输出,标准错误= process.communicate()
                return_ code = process.poll()
                打印(标准输出='{}'\\ nstderr ='{}'\\ nreturn_ code ='{}'。格式(标准输出,标准错误,return_ code)条)
            其他:
                打印(跳过:{}。格式(文件))    除了IO错误为e:
        打印(错误:未找到文件。)

如果任何人有这样的改进,请让我知道!

I'm converting this bash script to Python. I have a working Python version now. However, in order to get it to work, I had to hack the command I passed to subprocess.Popen() by making it into one long string. I do not wish to use one long command string. I wish to break this into the proper individual parameters. How can I do that in this specific example?

My specific question is how do I change this line:

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

into a form like this:

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

Here's my complete code so that the above fragments will make sense:

#!/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.")

解决方案

Here is a complete working solution with proper arguments for Popen().

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:
            name, extension = os.path.splitext(file)
            if(extension == source):
                print("Processing: {}".format(file))
                inf = os.path.join(in_path, file)
                outf = os.path.join(out_path, name + new_ext)
                process = subprocess.Popen([prog, "-i", inf, "-b:a", arate, "-vn", outf], shell=False, 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))
            else:
                print("Skipping: {}".format(file))

    except IOError as e:
        print("Error: file not found.")

If anyone has improvements on this, please let me know!

这篇关于将参数传递到Python subprocess.Popen的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆