【问题标题】:Python subprocess.Popen: redirection with ">" does not workPython subprocess.Popen:使用“>”进行重定向不起作用
【发布时间】:2015-10-30 09:56:52
【问题描述】:

以下代码在 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 上运行它,那么它可以完美运行。

【问题讨论】:

  • 你在 Popen 中用shell=True 试过了吗?
  • 现在 perl 脚本没有得到参数 :-(
  • 啊,是的,你不需要拆分了
  • 等瞧...谢谢!就是这样

标签: python bash process


【解决方案1】:

您不需要带有Popen 的shell 的输出重定向运算符;这就是 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 中打开文件,并将 file 对象传递给 Popen 以让它为子进程设置标准输出。
【解决方案2】:

你可以试试

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

【讨论】:

  • 现在 perl 脚本没有得到参数 :-(
【解决方案3】:

当前的两个答案都不起作用!

这可行(在 Python 3.7 上测试):

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

注意:

  1. Popen 中不需要拆分或数组。
  2. stdoutshell 参数都是必需的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    相关资源
    最近更新 更多