在python中将文件名传递给shell命令
下面是一个场景。我想在python脚本中运行一个命令行程序。 该命令将在执行后生成一个文件,我将该文件读入 操作。 我想将文件名作为函数参数传递在python中将文件名传递给shell命令,python,shell,Python,Shell,下面是一个场景。我想在python脚本中运行一个命令行程序。 该命令将在执行后生成一个文件,我将该文件读入 操作。 我想将文件名作为函数参数传递 def myfunc(myinputfile,myoutputfile): cmd = "mycommand -i %s -o %s" %(myinputfile,myoutputfile) 我尝试使用subprocess.call,但显然它要求我将commandname和参数作为列表的单独条目来编写。我还有别的办法吗。另外,在继续之前执
def myfunc(myinputfile,myoutputfile):
cmd = "mycommand -i %s -o %s" %(myinputfile,myoutputfile)
我尝试使用subprocess.call,但显然它要求我将commandname和参数作为列表的单独条目来编写。我还有别的办法吗。另外,在继续之前执行该命令也很重要,因为我希望稍后将文件的输出读入脚本中的变量 除非使用的是
shell=True
,否则需要将参数列表传递给子流程
:
def myfunc(myinputfile,myoutputfile):
cmd = ['mycommand', '-i', myinputfile, '-o', myoutputfile]
顺便说一句,这使得使用变量值作为参数变得更加容易。如果您想调用shell命令,我建议:
d = dict(os.environ.copy()) #copy enviroment
cmd = "mycommand -i %s -o %s" %(myinputfile,myoutputfile)
p = subprocess.Popen(cmd, shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,env=os.environ,cwd=PATHWHEREYOUHAVEACOMMAND,close_fds=True)
如果要打开终端并运行命令:
d = dict(os.environ.copy())
cmd4="mycommand -i %s -o %s" %(myinputfile,myoutputfile)
cmd="gnome-terminal --working-directory=%s --title='your title' --command='%s' " % (yourpath,cmd4)
p = subprocess.Popen(cmd, shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.STDOUT,env=os.environ,cwd=PATHWHEREYOUHAVEACOMMAND,close_fds=True)
为什么将命令行参数指定为列表是一个问题
subprocess.call(['mycommand','-i',myinputfile,'-o',myoutputfile])
命令行引用规则让人头疼。您应该使用传递列表的接口(如subprocess.call
)。否则,当路径包含有趣的角色时,它将全部崩溃。请记住,在Linux中,它可能包含除nul字节以外的任何内容,而Windows排除了一些字符,但它们仍然不排除重要的空格大小写,而且它们也不一致地排除它们。@JanHudec可以给我举个例子吗?什么例子?已链接的答案中有使用subprocess.call
的示例。奇怪文件名的例子?通常路径上有足够的空间。你也可以在那里引用,所以简单地引用论点是不行的。