在日志文件中使用grep

时间:2016-02-29 08:44:26

标签: python subprocess

如何将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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:1)

您使用了shell关键字管道(|),因此您需要设置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)