Python subprocess.Popen: 使用“>”重定向不起作用

Python subprocess.Popen: redirection with ">" does not work

以下代码在 Python 中无法正常运行。问题是输出没有通过使用 >:

重定向到 output
command = toolpath + " " + query + " " + number + " > " + output;
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE);
output = process.communicate()[0];

打印出来其实命令如下:

./subsetA.pl ./remainingqueries.fasta 100 > ./tmpQuery.fasta

所以 perl 脚本 subsetA.pl 接受两个参数并将其写入 stdout,后者被重定向到 tmpQuery.fasta。但是调用命令后 tmpQuery.fasta 为空。

如果我 运行 它直接在 CLI 上运行,那么它可以完美运行。

你可以试试

command = toolpath + " " + query + " " + number + " > " + output;
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE,Shell=True);
output = process.communicate()[0];

您不需要 shell 的输出重定向运算符和 Popen;这就是 stdout 参数的目的。

command = [toolpath, query, number]
with open(output) as output_fh:
    process = subprocess.Popen(command, stdout=output_fh)

由于您调用 communicate 来获取标准输出,因此您根本不想重定向输出:

command = [toolpath, query, number]
process = subprocess.Popen(command, stdout=subprocess.PIPE)
output = process.communicate()[0]

目前的两个答案都不行!

这有效(在 Python 3.7 上测试):

subprocess.Popen(['./my_script.sh arg1 arg2 > "output.txt"'],
                 stdout=subprocess.PIPE, shell=True)

注:

  1. 在 Popen 中不需要拆分或数组。
  2. 同时需要 stdoutshell 个参数。