Python子进程.Popen : redirection with ">" does not work

标签 python bash process

以下代码在 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 的输出重定向运算符;这就是 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子进程.Popen : redirection with ">" does not work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33433167/

相关文章:

bash - IF 语句与逻辑运算符未按预期工作

mysql - 在 LAMP 上运行重复的维护过程

python - 如何在Python中执行这个unix进程?连接参数时出现问题

java - 如何将数据作为参数从java传递到python脚本

bash - grep 区分大小写 [A-Z]?

bash - 在 Bash 中,如何查看字符串是否不在数组中?

android - 一个 intentService 不会被系统杀死?

python - 如何使用 PyGame 计时器事件?如何使用计时器将时钟添加到 pygame 屏幕?

python: 无法打开文件 'python DACscrap.py &' : [Errno 2] 没有这样的文件或目录...但是它有吗?

python - 在 Webtest 测试失败中找到真正的错误