2016-02-29 47 views
-2

如何將grep放在下面的字符串中。我似乎沒有把握好。在日誌文件中使用grep

p = subprocess.Popen(["tail", "-10", "/datax/qantas/run/tomcat/logs/localhost_access_log.2016-02-29.txt" "|" "grep /checkout-qantas/int/price?"], stdout=subprocess.PIPE) 

給我

tail: cannot open /datax/qantas/run/tomcat/logs/localhost_access_log.2016-02-29.txt|grep /checkout-qantas/int/price?' for reading: No such file or directory 

回答

1

shell = True,並把在報價的完整的命令應該幫助你 -

p = subprocess.Popen('tail -10 /datax/qantas/run/tomcat/logs/localhost_access_log.2016-02-29.txt | grep /checkout-qantas/int/price?', stdout=subprocess.PIPE, shell = True) 
+0

是否在Linux的shell命令的工作? – AlokThakur

+0

我懷疑它會在linux shell上工作,究竟是什麼這個GET做的,從來沒有見過這樣的shell命令 – AlokThakur

+1

嗨Alok,它爲我工作,它不是在linux shell中工作,但是當我使它在那裏工作時,它的執行我的Python腳本。謝謝。 –

1

您已經使用殼管關鍵字(|),所以你需要設置shell=True

subprocess.Popen("tail -10 ... | grep ....", shell=True) 

如果你想保存輸出:

out = subprocess.check_output("tail -10 ... | grep ....", shell=True) 

最好不要使用shell=True,使用subprocess.PIPE代替例如爲:

>>> out = subprocess.Popen(['tail', '-10', '/var/log/syslog'], stdout=subprocess.PIPE) 
>>> subprocess.check_call(['grep', 'UDP'], stdin=out.stdout)