python subprocess.Popen使用管道并将stdout重定向到命令中的文件不起作用

0 投票
1 回答
26 浏览
提问于 2025-04-14 16:20

这里是问题

我们来看一个文件:

printf 'this is \\n difficult' \>test

现在我想用Python来执行以下的bash命令:

grep 'diff' test |gzip \>test2.gz

我尝试了以下代码,但没有成功:

import subprocess

command = \['grep', 'diff', 'test', '|', 'gzip', '\>' 'test2.gz'\]

proc = subprocess.Popen(
  command,
  stdin=subprocess.PIPE,
  stdout=subprocess.PIPE,
  stderr=subprocess.STDOUT,
  encoding='utf8', shell=True)

然后我尝试使用以下方法将输出重定向到一个文件:

 import subprocess

 command = \['grep', 'diff', 'test', '|', 'gzip'\]

 test2 = open('test2.gz', 'w')

 proc = subprocess.Popen(
    command,
    stdin=subprocess.PIPE,
    stdout=test2,
    stderr=subprocess.STDOUT,
    encoding='utf8', shell=True)

但这也没有成功,所以我有点不知道该怎么做才能实现管道和重定向到文件。

1 个回答

0

这段话说的有点让人困惑:

command = ['grep', 'diff', 'test', '|', 'gzip']

这里试图用参数 ["diff", "test", "|", "gzip"] 来运行 grep 命令——这其实不是你想要的——而且当你使用 shell=True 时,你需要传入一个字符串,而不是一个列表。

如果你想使用像输入输出重定向这样的 shell 脚本功能,你需要运行一个 shell 脚本。

import subprocess

command = "grep 'diff' test | gzip"

with open('test2.gz', 'w') as test2:
  proc = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=test2, stderr=subprocess.STDOUT, encoding='utf8', shell=True)

撰写回答