【问题标题】:Run a complex grep command with Python使用 Python 运行复杂的 grep 命令
【发布时间】:2013-11-29 00:52:54
【问题描述】:

我正在尝试运行这个在 cmd 上运行良好的 grep 复合命令

grep Rec sy.log | grep e612r2246s768 | grep 2013-07 | grep -oh "'.*'" | wc -c

但是这里出了点问题,我还看不到:

import commands
commands.getstatus("""/bin/grep Rec /var/log/sy.log | /bin/grep e612r2246s768 | /bin/grep 2013-07 | /bin/grep -oh "'.*'" | /usr/bin/wc -c""")
Out[2]: 'ls: cannot access /bin/grep Rec /var/log/sy.log | /bin/grep e612r2246s768 | /bin/grep 2013-07 | /bin/grep -oh "\'.*\'" | /usr/bin/wc -c: No such file or directory'

使用子进程:

import subprocess
cmd = ["""/bin/grep Rec /var/log/sy.log | /bin/grep e612r2246s768 | /bin/grep 2013-07 | /bin/grep -oh "'.*'" | /usr/bin/wc -c"""]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
/home/www-data/gpslistener/scripts/<ipython-input-24-0881e54c5eab> in <module>()
----> 1 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)

/usr/lib/python2.7/subprocess.pyc in __init__(self, args, bufsize, executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, env, universal_newlines, startupinfo, creationflags)
    677                             p2cread, p2cwrite,
    678                             c2pread, c2pwrite,
--> 679                             errread, errwrite)
    680 
    681         if mswindows:

/usr/lib/python2.7/subprocess.pyc in _execute_child(self, args, executable, preexec_fn, close_fds, cwd, env, universal_newlines, startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite)
   1247                     if fd is not None:
   1248                         os.close(fd)
-> 1249                 raise child_exception
   1250 
   1251 

OSError: [Errno 2] No such file or directory

PD:路径没问题,谢谢

【问题讨论】:

  • "自 2.6 版起已弃用:命令模块已在 Python 3 中删除。改用子进程模块。"

标签: python python-2.7 command-line grep


【解决方案1】:

使用与 shell 注入相关的 usual caveat,执行 shell 管道的最简单方法是传入 shell=True

cmd = r'''/bin/grep Rec /var/log/syslog | \
    /bin/grep e612r2246s768 |\
    /bin/grep 2013-07 |\
/bin/grep -oh "'.*'" |\
/usr/bin/wc -c'''
subprocess.check_output(cmd, shell=True)

【讨论】:

    【解决方案2】:

    好的,这种方法对我有用:

    >>>import subprocess
    >>>cmd = ["""/bin/grep 'Rec' /var/log/sy.log | /bin/grep e612r2246s768 | /bin/grep 2013-07 | /bin/grep -oh "'.*'" | /usr/bin/wc -c"""]
    >>>print subprocess.check_output(cmd,shell=True)
    >>>365829
    

    【讨论】:

    • 你能解释一下为什么在 cmd 中出现 3 次 """ 吗??
    • @AshishKarpe 这有点晚了,但对于任何想知道的人来说,它使您可以在字符串中包含任何类型的引号。例如"""hello"'"world""" 将输出 hello"'"world。
    猜你喜欢
    • 2018-10-02
    • 2020-01-10
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-18
    相关资源
    最近更新 更多