Store output of subprocess.Popen call in a string

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

提交回复
热议问题