Python 子进程运行/调用不工作

Python 子进程运行/调用不工作,python,python-3.x,terminal,subprocess,Python,Python 3.x,Terminal,Subprocess,我想在Python代码中使用该实用程序。当我在Linux终端中使用它时,它工作得很好。这是命令: $ raster2pgsql -a "/mnt/c/Users/Jan/path/to/raster/dem.tiff" test_schema.raster2 | psql -h localhost -d pisl -U pisl 然后我使用subprocess.run,我也尝试过subprocess.call在Python代码中使用相同的工具。这是我的代码: from subprocess i

我想在Python代码中使用该实用程序。当我在Linux终端中使用它时,它工作得很好。这是命令:

$ raster2pgsql -a "/mnt/c/Users/Jan/path/to/raster/dem.tiff" test_schema.raster2 | psql -h localhost -d pisl -U pisl
然后我使用subprocess.run,我也尝试过subprocess.call在Python代码中使用相同的工具。这是我的代码:

from subprocess import run
command = ["raster2pgsql", "-a", '"' + file_name + '"', self.schema_name +  "." + identifier, "|", "psql", "-h", "localhost", "-p", "5432", "-d", self.dbname]
run(command)
我得到这个错误:

ERROR: Unable to read raster file: "/mnt/c/Users/Jan/path/to/raster/dem.tiff"
打印命令给出了我认为与在终端中工作相同的正确结果:

['raster2pgsql', '-a', '"/mnt/c/Users/Jan/path/to/raster/dem.tiff"', 'test_schema.raster2', '|', 'psql', '-h', 'localhost', '-p', '5432', '-d', 'pisl']
我仔细检查了光栅文件的路径是否正确,尝试了单引号和双引号,但没有任何帮助。我看过一些类似的问题,但没有发现任何有用的东西

我在Windows10中使用Python3.5和LinuxBashshell

问题:我使用子流程的方式有什么问题?

这里有两个问题:

不需要额外引用文件名。它直接传递给系统,由于没有名为/tmp/something的文件,因此命令失败。 其次,为了能够通过管道,需要shell=True 所以快速修复:

command = ["raster2pgsql", "-a", file_name, self.schema_name +  "." + identifier, "|", "psql", "-h", "localhost", "-p", "5432", "-d", self.dbname]
run(command,shell=True)
或者使用命令字符串,因为shell=True对参数列表很挑剔:

command = "raster2pgsql -a "+ file_name + " " + self.schema_name +  "." + identifier + " | psql -h localhost -p 5432 -d" + self.dbname
run(command,shell=True)
难看,不是吗

最好在不使用shell=True的情况下运行2个进程,并使用python将它们连接在一起,更具可移植性和安全性不确定shell=True在Linux上如何与参数列表反应:

from subprocess import *
command1 = ["raster2pgsql", "-a", file_name, self.schema_name +  "." + identifier]
p = Popen(command1,stdout=PIPE)
command2 = ["psql", "-h", "localhost", "-p", "5432", "-d", self.dbname]
run(command2,stdin=p.stdout)

由于stdout=pipe参数,创建的第一个Popen对象将其输出写入管道。由于stdin=p.stout,run函数也可以将输入作为管道。它消耗第一个命令的输出,创建一个本地管道命令链,而不需要shell和引号、空格、特殊字符解释等警告…

为什么要引用文件名?因为它不识别文件名,而不识别文件名。当我删除引号时,它会将test_schema.raster2视为文件名。请测试一下。如有错误,请准确报告。我怀疑引号是否是问题所在,因为shell在您执行的工作命令中删除了引号。感谢您的解释。我试图让py 3脚本运行py 2脚本,我使用process=subprocess.run['py','-2',os.path.basenamelatest_file],但由于某种原因它没有运行。我无意中遇到了这个问题,通过在另一行中添加shell=True,它可以正常工作。你有没有可能知道它为什么起作用?非常感谢你!您的意思是subprocess.run['py','-2',os.path.basenamelatest_file],shell=True运行,而如果shell=True则不运行?这很可能是另一个问题。哦,恰恰相反。有一句话不管用。但是,在您建议的dirty:command=['py','-2',os.path.basenamelatest_file]subprocess.runcommand格式中,shell=Trueit可以工作。