简体   繁体   中英

exec python2 vs python3

I'm transferring a testframework from python2 to python3. I have troubles with the exec statement to exec function change. At run-time I decide depending on a xls file which function is called. 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?

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

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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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