2017-08-29 29 views
1

您好我想從shell腳本移動到Python無法使用子

awk -F' ' '{print FILENAME " "$2 " " $3 " " $5}' $text| tail -n+4|head -n -2

同時使用Python創建子在python腳本來執行awk命令,我得到一個錯誤。你能否請我哪裏錯了。我嘗試使用轉義字符後F.

c1 = subprocess.Popen(["awk -F' ' '{print FILENAME " "$2 " " $3 " " $5}' {0} | tail -n+4|head -n -2".format(text)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
output = c1.communicate() 
print output 
+0

對於'c1',它看起來像你想傳遞一個字符串而不是一個列表並且使用'shell = True'參數 - 另外,如果你這樣做確保你相信'場所'的供應商_完全_因爲你很容易受到注射。否則,你需要在python中構建shell管道(雖然稍微笨拙一些,但仍然有可能) – mgilson

+0

我也試過這個c1 = subprocess.Popen(['awk','-F''「,'' {print FILENAME「」$ 2「」$ 3「」$ 5}'「,{0}] .format(text)],stdin = subprocess.PIPE,stdout = subprocess.PIPE,stderr = subprocess.PIPE) c2 = subprocess。 Popen(['tail','-n + 4'],stdin = c1.stdout,stdout = subprocess.PIPE) c3 = subprocess.Popen(['head','-n','-2'], stdin = c2.stdout,stdout = subprocess.PIPE) 輸出,err = c3.communicate() – Amitabh

+0

我試過shell = True,我得到一個錯誤KeyError:'print FILENAME $ 2 $ 3 $ 5' – Amitabh

回答

0

我能夠通過

第一=「AWK -F」'「{打印 「+場地+」 $ 2 「+」 $ 3 「+」 來解決這個$ 5}'「+ venue1 +」| tail -n + 4 | head -n -2「

c1 = subprocess.Popen([first],shell = True,stdout = subprocess.PIPE,stderr = subprocess.PIPE)

X = c1.communicate()[0]

輸出爲 xyz 我需要x,y和z之間的空間