Reputation: 11
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. 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.
Upvotes: 1
Views: 949
Reputation: 2348
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
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)
Upvotes: 2
Reputation:
You have this error because input_var
contains 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
. So remove exec
word from input_var
. Then you get no errors and get output:
Passed bar!
Passed foo!
Upvotes: 2