Store output of subprocess.Popen call in a string

前端 未结 15 2225
一个人的身影
一个人的身影 2020-11-22 03:23

I\'m trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.

#!/usr/bin/python
import subprocess         


        
相关标签:
15条回答
  • 2020-11-22 03:37

    I wrote a little function based on the other answers here:

    def pexec(*args):
        return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].rstrip()
    

    Usage:

    changeset = pexec('hg','id','--id')
    branch = pexec('hg','id','--branch')
    revnum = pexec('hg','id','--num')
    print('%s : %s (%s)' % (revnum, changeset, branch))
    
    0 讨论(0)
  • 2020-11-22 03:37

    Use ckeck_output method of subprocess

    import subprocess
    address = 192.168.x.x
    res = subprocess.check_output(['ping', address, '-c', '3'])
    

    Finally parse the string

    for line in res.splitlines():
    

    Hope it helps, happy coding

    0 讨论(0)
  • 2020-11-22 03:48

    for Python 2.7+ the idiomatic answer is to use subprocess.check_output()

    You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....

    If args is just single command with no args of its own (or you have shell=True set), it can be a string. Otherwise it must be a list.

    for example... to invoke the ls command, this is fine:

    from subprocess import check_call
    check_call('ls')
    

    so is this:

    from subprocess import check_call
    check_call(['ls',])
    

    however, if you want to pass some args to the shell command, you can't do this:

    from subprocess import check_call
    check_call('ls -al')
    

    instead, you must pass it as a list:

    from subprocess import check_call
    check_call(['ls', '-al'])
    

    the shlex.split() function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses... like this:

    from subprocess import check_call
    import shlex
    check_call(shlex.split('ls -al'))
    
    0 讨论(0)
  • 2020-11-22 03:49

    The following captures stdout and stderr of the process in a single variable. It is Python 2 and 3 compatible:

    from subprocess import check_output, CalledProcessError, STDOUT
    
    command = ["ls", "-l"]
    try:
        output = check_output(command, stderr=STDOUT).decode()
        success = True 
    except CalledProcessError as e:
        output = e.output.decode()
        success = False
    

    If your command is a string rather than an array, prefix this with:

    import shlex
    command = shlex.split(command)
    
    0 讨论(0)
  • 2020-11-22 03:51

    This worked for me for redirecting stdout (stderr can be handled similarly):

    from subprocess import Popen, PIPE
    pipe = Popen(path, stdout=PIPE)
    text = pipe.communicate()[0]
    

    If it doesn't work for you, please specify exactly the problem you're having.

    0 讨论(0)
  • 2020-11-22 03:51

    This works perfectly for me:

    import subprocess
    try:
        #prints results and merges stdout and std
        result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
        print result
        #causes error and merges stdout and stderr
        result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
    except subprocess.CalledProcessError, ex: # error code <> 0 
        print "--------error------"
        print ex.cmd
        print ex.message
        print ex.returncode
        print ex.output # contains stdout and stderr together 
    
    0 讨论(0)
提交回复
热议问题