2011-05-26 120 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