subprocess.check_output() doesn't seem to exist (Python 2.6.5)

前端 未结 3 888
逝去的感伤
逝去的感伤 2020-11-28 22:25

I\'ve been reading the Python documentation about the subprocess module (see here) and it talks about a subprocess.check_output() command which seems to be exac

3条回答
  •  旧巷少年郎
    2020-11-28 23:04

    IF it's used heavily in the code you want to run but that code doesn't have to be maintained long-term (or you need a quick fix irrespective of potential maintenance headaches in the future) then you could duck punch (aka monkey patch) it in wherever subprocess is imported...

    Just lift the code from 2.7 and insert it thusly...

    import subprocess
    
    if "check_output" not in dir( subprocess ): # duck punch it in!
        def f(*popenargs, **kwargs):
            if 'stdout' in kwargs:
                raise ValueError('stdout argument not allowed, it will be overridden.')
            process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
            output, unused_err = process.communicate()
            retcode = process.poll()
            if retcode:
                cmd = kwargs.get("args")
                if cmd is None:
                    cmd = popenargs[0]
                raise subprocess.CalledProcessError(retcode, cmd)
            return output
        subprocess.check_output = f
    

    Minor fidgeting may be required.

    Do bear in mind though the onus is on you to maintain dirty little backports like this. If bugs are discovered and corrected in the latest python then you a) have to notice that and b) update your version if you want to stay secure. Also, overriding & defining internal functions yourself is the next guy's worst nightmare, especially when the next guy is YOU several years down the line and you've forgot all about the grody hacks you did last time! In summary: it's very rarely a good idea.

提交回复
热议问题