使用案例:
我必须与python subprocess32
模块一起工作,用于超时,但代码也可以在windows上运行。模块文档建议
if os.name == 'posix' and sys.version_info[0] < 3:
import subprocess32 as subprocess
else:
import subprocess
The problem:
我认为上面的方法没有考虑到像communicate
,check_output
,wait
这样的方法只有timeout
参数和subprocess32
模块。使用此方法,对这些方法的所有调用都将失败
我不希望实现同一函数的两个不同变体,有条件地导入模块和所有东西。
寻找一种巨蟒式的方式来处理这件事。我的直觉告诉我,decorators
和partial
函数应该会有帮助,但似乎无法计算出精确和简洁的方法。
有什么建议吗?
发布于 2018-07-14 17:50:34
我设计了一种非常丑陋的方法,使用partial
函数来完成此任务
from functools import partial
from subprocess import check_output
import subprocess
if os.name == 'posix' and sys.version_info[0] < 3:
from subprocess32 import check_output
import subprocess32 as subprocess
check_output = partial(check_output,timeout=10)
def execute_cmd(cmd, args):
command = []
command.append(cmd)
command = command + args
try:
proc_out = check_output(command, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
print("Failed to execute local command \nError code:%s, Output:%s",
e.cmd, e.returncode, e.output)
# I wish to handle TimeoutExpired exception here, but then this won't be generic
except:
print("Command %s failed to execute on host", command)
raise
https://stackoverflow.com/questions/51326053
复制相似问题