使用Python运行复杂的grep命令

Gok*_*oku 3 python command-line grep python-2.7

我试图运行这个grep复合命令,在cmd上工作正常

grep Rec sy.log | grep e612r2246s768 | grep 2013-07 | grep -oh "'.*'" | wc -c
Run Code Online (Sandbox Code Playgroud)

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

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'
Run Code Online (Sandbox Code Playgroud)

使用子进程:

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
Run Code Online (Sandbox Code Playgroud)

PD:路径还可以,谢谢

Gok*_*oku 7

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

>>>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
Run Code Online (Sandbox Code Playgroud)


iru*_*var 6

通过与shell注入相关的常见警告,执行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)
Run Code Online (Sandbox Code Playgroud)