2015-07-12 30 views
1

我有这个代码:Python的EXEC()的问题

def test(variable, customCode = ""): 

    if variable > 1: 
     print(">1") 

    if customCode != "": 
     exec(customCode) 

    if foo == 1: 
     print("Success") 

numb = 12 
code = "if variable > 1: foo = 1" 

test(numb, code) 

在执行时,给出了这样的错误:

Error 1

所以,后来,我在的开头加入foo = 0代码,并得到这个输出:

Issue 2

现在,显然,它也应该是输出Success,但它不是。

这是什么问题?

使用Python 3

+0

代码执行得很好,使用'> 1'然后换行符和'Success'。 –

+0

@ l'L'l,你使用python3吗? –

+0

@PadraicCunningham,我尝试了'2.7.6'和'3.4.3'(在Python3中它失败了),对不起,我没有提到。你的回答让我好奇 - 是否会被视为一种范围界定? –

回答

3

正确的方法是通过一个字典的关键在Python 3和查找给exec,在python2您的代码将作为工作是因为高管是不是在python3函数的声明:

def test(variable, customCode = ""): 
    d = {"variable":variable} 
    if customCode != "": 
     exec(customCode, d) 
    if d["foo"] == 1: 
     print("Success") 

numb = 12 
code = "if variable > 1: foo = 1" 

test(numb, code) 

输出:

In [13]: numb = 12 

In [14]: code = "if variable > 1: foo = 1" 

In [15]: test(numb, code) 
Success 

exec

Note The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

您还需要了解您的if variable > 1为False的情况,因为您永远不会执行代码,所以foo永远不会被添加。

+1

好的,你的回答让我想到我的解决方案,我即将发布。谢谢。 – Quelklef

0

阅读@Padraic坎宁安的岗位给了我一个想法,它曾作为一个解决方案:

很简单:不是只是在做: foo = 1,做到: global foo; foo = 1

更改代码:

def test(variable, customCode = ""): 

    if variable > 1: 
     print(">1") 

    if customCode != "": 
     exec(customCode) 

    if foo == 1: 
     print("Success") 

numb = 12 
code = "if variable > 1: global foo; foo = 1" 

test(numb, code) 

问题是exec()是一个函数,而不是在Python 3一份声明中,所以foo被用作局部变量。 (来源:@Padraic Cunningham)