0
我遇到了子进程模块的问题。我缺少check_output函数,我想知道是否有一种方法来更新/替换这个没有做一个完整的python重新安装。如何更新python附带的模块?
我遇到了子进程模块的问题。我缺少check_output函数,我想知道是否有一种方法来更新/替换这个没有做一个完整的python重新安装。如何更新python附带的模块?
是的,可能的话,如果需要,您可以在自己的功能中添加该功能(只有在您需要它时才提供反向功能)。
if 'check_output' not in dir(subprocess):
def check_output(cmd_args, *args, **kwargs):
proc = subprocess.Popen(
cmd_args, *args,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
out, err = proc.communicate()
if proc.returncode != 0:
raise subprocess.CalledProcessError(args)
return out
subprocess.check_output = check_output
但是,正如该代码所示,您也可以将其写得更详细一点,它的操作也不会有所不同。
编辑:直接从子模块的Python版本2.7
def check_output(*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, output=output)
return output
副本,以便将做同样的事情,原来的功能? –
实际上是的,如果你想使用它,我还包含了来自最新版本的子过程模块的直接副本。再次,我只会将它用作现有代码的向后兼容性。如果你正在编写新的代码,我会自己使用Popen和.communicate()。 – CasualDemon
我为这个项目使用了Python 2.6,这个代码还能工作吗? @CasualDemon –