在python中运行管道命令 - 结果不同

时间:2012-01-31 16:50:52

标签: python command call subprocess pipe

我正在尝试在python中调用管道命令(echo -e“HEAD / HTTP / 1.0 \ n”| ncat -C localhost 80)。

from subprocess import call
cmd = 'echo -e "HEAD / HTTP/1.0\n" |  ncat -C localhost 80'
output=call(cmd, shell=True)
print output

然而,结果与预期不同:

HTTP/1.1 400 Bad Request
...

预期结果(从shell运行cmd时)是:

HTTP/1.1 302 Redirect
...

更新: 我刚试验过,这似乎完美无缺。

from subprocess import Popen, PIPE
p1 = Popen(['echo', 'HEAD / HTTP/1.0\n'], stdout=PIPE)
p2 = Popen(["ncat", "-C", "localhost", "80"], stdin=p1.stdout)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

1 个答案:

答案 0 :(得分:0)

您的\n正在 python 字符串中生成换行符。我假设你想要echo来解释它。尝试将其作为原始字符串:

cmd = r'echo -e "HEAD / HTTP/1.0\n" |  ncat -C localhost 80'

这样,python不会解释'\ n'并且它将被传递。