简体   繁体   English

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

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

The following code does not work properly in Python.以下代码在 Python 中无法正常工作。 The problem is that the output does not get redirected to output by using > :问题是输出不会通过使用>重定向到output

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

The command is actually the following if you print it:如果您打印它,该命令实际上是以下内容:

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

So the perl script subsetA.pl takes two arguments and writes it to stdout which gets redirected to tmpQuery.fasta .所以perl 脚本subsetA.pl接受两个参数并将其写入stdoutstdout被重定向到tmpQuery.fasta But tmpQuery.fasta is empty after the command gets called.但是在调用命令后tmpQuery.fasta为空。

If I run it direct on CLI then it works perfectly.如果我直接在 CLI 上运行它,那么它可以完美运行。

You don't need the shell's output redirection operator with Popen ;你不需要 shell 的输出重定向操作符和Popen that's what the stdout argument is for.这就是stdout参数的用途。

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

Since you are calling communicate to get the standard output, though, you don't want to redirect the output at all:但是,由于您正在调用communicate来获取标准输出,因此您根本不想重定向输出:

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

You can try你可以试试

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

Both current answers don't work!当前的两个答案都不起作用!

This works (tested on Python 3.7):这有效(在 Python 3.7 上测试):

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

Note:笔记:

  1. You do not need split or array in Popen.在 Popen 中不需要 split 或 array。
  2. BOTH stdout and shell parameters are needed.需要stdoutshell参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM