在运行时修改循环函数的内部

Sch*_*ote 5 python python-3.x

这个是一个很糟糕的,但请耐心等待.

我正在调用一个具有无限期等待某种输入的函数的库.不幸的是,这个函数以这样的方式被窃听:它允许它从中读取的管道填充不相关的输入,导致程序在等待它自己失明的输入时锁定.该库完全是关键的,非常难以复制,维护者不接受拉取请求或错误报告.

我需要在这个函数的主体中注入一个"flush the pipe"函数调用.以前我通过利用具有回调参数的类似函数来解决这个问题,但是这个特定的函数没有这样的参数.

我能做什么?

Ran*_*niz 3

似乎您可以查看源代码,因此您可以做的就是浏览源代码并找到在有缺陷的方法中调用的方法并对其进行猴子修补

class OtherGuysClass:

    def buggedMethod(self, items):
        for item in items:
            a = self.convert(item)
            print(a * 5)

    def convert(self, str):
        return int(str)

if __name__ == "__main__":
    try:
        OtherGuysClass().buggedMethod([1, 2, None, 5])
    except Exception as e:
        print("Bugged method crashed: " + str(e))

    # Replace convert with our own method that returns 0 for None and ""
    o = OtherGuysClass()
    original_convert = o.convert
    def float_convert(str):
        if str:
            return original_convert(str)
        return 0
    o.convert = float_convert
    o.buggedMethod(["1", "2", None, "5"])
Run Code Online (Sandbox Code Playgroud)

5
10
错误方法崩溃:int() 参数必须是字符串、类似字节的对象或数字,而不是“NoneType”
5
10
0
25