【问题标题】:Using grep in log file在日志文件中使用 grep
【发布时间】:2016-02-29 08:44:26
【问题描述】:

如何在下面的字符串中放置 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

【问题讨论】:

    标签: python subprocess


    【解决方案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)
    

    【讨论】:

    • 我怀疑它是否可以在 linux shell 上运行,这个 GET 究竟是做什么的?,从未见过这样的 shell 命令
    • 嗨,Alok,它对我有用,它不能在 linux shell 中工作,但是当我让它在那里工作时,它会在我的 python 脚本中执行。谢谢。
    【解决方案2】:

    你使用了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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-13
      • 2011-12-31
      • 2017-11-10
      • 2021-05-01
      • 2023-01-23
      • 2014-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多