subprocess.check_output return code

前端 未结 5 1845
刺人心
刺人心 2020-12-02 22:03

I am using:

grepOut = subprocess.check_output(\"grep \" + search + \" tmp\", shell=True)

To run a terminal command, I know that I can use a

5条回答
  •  长情又很酷
    2020-12-02 22:43

    is there a way to get a return code without a try/except?

    check_output raises an exception if it receives non-zero exit status because it frequently means that a command failed. grep may return non-zero exit status even if there is no error -- you could use .communicate() in this case:

    from subprocess import Popen, PIPE
    
    pattern, filename = 'test', 'tmp'
    p = Popen(['grep', pattern, filename], stdin=PIPE, stdout=PIPE, stderr=PIPE,
              bufsize=-1)
    output, error = p.communicate()
    if p.returncode == 0:
       print('%r is found in %s: %r' % (pattern, filename, output))
    elif p.returncode == 1:
       print('%r is NOT found in %s: %r' % (pattern, filename, output))
    else:
       assert p.returncode > 1
       print('error occurred: %r' % (error,))
    

    You don't need to call an external command to filter lines, you could do it in pure Python:

    with open('tmp') as file:
        for line in file:
            if 'test' in line:
                print line,
    

    If you don't need the output; you could use subprocess.call():

    import os
    from subprocess import call
    try:
        from subprocess import DEVNULL # Python 3
    except ImportError: # Python 2
        DEVNULL = open(os.devnull, 'r+b', 0)
    
    returncode = call(['grep', 'test', 'tmp'], 
                      stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL)
    

提交回复
热议问题