2011-05-26 78 views
0

我对python很陌生。目标是使用子进程解析&从shell中检索打印输出来执行shell命令。执行错误如下面的示例输出msg中所示。还示出了下面是示例代码段在Python中转义转义序列

代码段:

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: `/' 

有一种解决方法,或者可以使用的功能?

感谢您的帮助 感谢

+1

给予子过程文件“tst.txt”的完整路径。 – MBarsi 2011-05-26 09:45:28

回答

1

我想你的主要错误是不是蟒蛇有关。更确切地说,有3个:

  1. 你忘了import subprocess
  2. 它应该是sed -e 's/.*Location: //g'。你写了///g而不是s///g
  3. tst.txt不存在。
+0

谢谢 - 这是一个错误。同时找到它。此外,下面的链接回答了关于转义'\ r'的问题http://stackoverflow.com/questions/4392176/escape-for-str-in-python。 – Joe 2011-05-26 10:19:19

1

您应该直接将testStr作为第一个参数传递,而不是将其包含在列表中。请参阅subprocess.Popen,这是启动“在Unix上,使用shell = True:...”的段落。

+0

感谢您的信息 – Joe 2011-05-26 10:22:06