0

我对python有点陌生。目标是使用子进程解析执行 shell 命令并从 shell 中检索打印输出。执行错误如下面的示例输出消息所示。下面还显示了示例代码片段

代码片段:

testStr = "cat tst.txt | grep Location | sed -e '/.*Location: //g' "
print "testStr = "+testStr
testStrOut = subprocess.Popen([testStr],shell=True,stdout=subprocess.PIPE).communicate()[0]

输出:

testStr = cat tst.txt | grep Location | sed -e '/.*Location: //g' 
cat: tst.txt: No such file or directory
sed: -e expression #1, char 15: unknown command: `/'

是否有可以使用的解决方法或功能?

感谢您的帮助 谢谢

4

2 回答 2

1

我想你的主要错误与 python 无关。更准确地说,有3个:

  1. 你忘了import subprocess
  2. 应该是sed -e 's/.*Location: //g'。你写///g而不是s///g.
  3. tst.txt不存在。
于 2011-05-26T09:46:25.270 回答
1

You should be passing testStr directly as the first argument, rather than enclosing it in a list. See subprocess.Popen, the paragraph that starts "On Unix, with shell=True: ...".

于 2011-05-26T10:15:20.327 回答