简体   繁体   English

(Python 3.X)Python exec()函数无缘无故地抛出TypeError

[英](Python 3.X) Python exec() function throws TypeError for no reason

I have ran into a problem with a project I'm working on. 我遇到了一个我正在研究的项目的问题。 I've found where in the code this problem is happening, and put it in an isolated, simple environment, and the error persists. 我已经在代码中找到了这个问题发生的位置,并将其置于一个孤立,简单的环境中,并且错误仍然存​​在。

Here's the code: 这是代码:

def parse(input_var):
    input_var = input_var.split("[METHOD]")
    if(len(input_var)>1):
        input_var[0] = input_var[0].replace("using ","exec(parse(")
        input_var[0] = input_var[0].replace(";","))")
        input_var = input_var[0]+input_var[1]
    else:
        input_var=input_var[0]
    exec(input_var)


foo="""
using bar;
[METHOD]
print('Passed foo!')
"""

bar = """
print('Passed bar!')
"""

parse(foo)

And here is the output from running the code: 以下是运行代码的输出:

Passed bar!
Traceback (most recent call last):
  File "python", line 22, in <module>
  File "python", line 9, in parse
  File "<string>", line 2, in <module>
TypeError: exec() arg 1 must be a string, bytes or code object

The "bar" piece of code is causing the problem, even though it obviously is a string. “bar”代码片段引起了问题,即使它显然是一个字符串。 The thing that's so rotten about this is that it never runs the second half of the "foo" code, which in my other program that uses this code, is kind of necessary. 关于这个问题如此糟糕的事情是,它永远不会运行“foo”代码的后半部分,这在我使用此代码的其他程序中是必要的。

you have to remove calling exec from "exec(parse(" it will work fine because exec function accept only a string, bytes or code object as arg no need to add it in this code statment 你必须从“exec”中删除调用exec (解析(“它将正常工作,因为exec函数只接受一个字符串,字节或代码对象作为arg,无需在此代码中添加它

def parse(input_var):
    input_var = input_var.split("[METHOD]")
    if(len(input_var)>1):
        input_var[0] = input_var[0].replace("using ","parse(")
        input_var[0] = input_var[0].replace(";",");")
        input_var = input_var[0]+input_var[1]
    else:
        input_var=input_var[0]
    exec(input_var)


foo="""
using bar;
[METHOD]
print('Passed foo!')
"""

bar = """
print('Passed bar!')
"""

parse(foo)

You have this error because input_var contains exec . 您有此错误,因为input_var包含exec So you try to execute the code which in turn tries to execute another code. 因此,您尝试执行代码,而代码又尝试执行另一个代码。 And the second time exec 's argument is not a string but function parse . 第二次exec的参数不是字符串而是函数parse So remove exec word from input_var . 所以从input_var删除exec word。 Then you get no errors and get output: 然后你得到没有错误并获得输出:

Passed bar!
Passed foo!

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

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