简体   繁体   English

exec python2 vs python3

[英]exec python2 vs python3

I'm transferring a testframework from python2 to python3. 我正在将一个testframework从python2转移到python3。 I have troubles with the exec statement to exec function change. 我在执行函数更改时遇到了exec语句的麻烦。 At run-time I decide depending on a xls file which function is called. 在运行时,我决​​定根据xls文件调用哪个函数。 I tried to give local() and global() and also tried the execHelper instead of exec (see example below) I also tried the namespace technique of the exechelper function direct in the testfunction but always some names are not found in the namespace.... any suggestions? 我试图给local()和global()并尝试execHelper而不是exec(参见下面的例子)我也尝试了exechelper函数的命名空间技术直接在testfunction中,但总是在命名空间中找不到某些名称。 .. 有什么建议么?

def execHelper(command,callerobject):
    ns = {}
    exec(command,ns)
    for name, value in ns.items():
        setattr(callerobject, name, value)

def myfunction2(val1,val2):
    return val1 * val2

class myclass():
    def myfunction1(self,val1,val2):
        return val1 + val2

    def test(self):
        a = 5
        self.b = 10
        exec("result = self.myfunction1(a,self.b)+myfunction2(a,self.b)")
        print(result)


test = myclass()
test.test()
def myfunction2(val1,val2):
    return val1 * val2

class myclass():
    def myfunction1(self,val1,val2):
        return val1 + val2


    def test(self):
        a = 5
        self.b = 10
        exec("global result;result = self.myfunction1(a,self.b)+myfunction2(a,self.b)")
        print(result)


test = myclass()
test.test()

Use global in exec function 在exec函数中使用global

There is a big difference between exec in Python 2 and exec() in Python 3. So in python 3 , we have to bring the result varialbe into the scope of exec(). Python 2中的exec和Python 3中的exec()之间存在很大差异。因此在python 3中,我们必须将结果varialbe带入exec()的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM