Store output of subprocess.Popen call in a string

前端 未结 15 2213
一个人的身影
一个人的身影 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: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'))
    

提交回复
热议问题