这是运行任意命令返回其stdout数据的Python代码,或者在非零退出代码上引发异常:
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
Run Code Online (Sandbox Code Playgroud)
communicate 用于等待进程退出:
stdoutdata, stderrdata = proc.communicate()
Run Code Online (Sandbox Code Playgroud)
该subprocess模块不支持超时 - 能够终止运行超过X秒的进程 - 因此,communicate可能需要永久运行.
在旨在在Windows和Linux上运行的Python程序中实现超时的最简单方法是什么?