+ 3
Python: execute a program inside another program
Let’s say file.txt is a text file, and it’s content is: x=5 print(x) So, if I make this code in python: file=open(“file.txt”, “r”) cont= file.read() cont Will the output be 5 or a string “x=5 print(x)”? If it returns the string, how can i execute a program inside another one, or something like that?
6 Respuestas
+ 9
Check it out - codes created by codes created and run by codes... 😉
https://code.sololearn.com/c5f76DBYhYSO/?ref=app
+ 5
Use compile() to create a Code obj and then execute it.
Here I use a string literal representation of cont which would essentially be the equivalent of what you'd receive after using file.read() they way you have it above. This way you can see the code work in the playground.
cont = '''x=5
print(x)'''
obj = compile(cont, '', 'exec')
exec(obj)
https://docs.python.org/3/library/functions.html#compile
+ 5
The use of eval won't work here, because eval is used for expressions. x=5 is an assignment statement and will result in an error when used within eval. You can however also just use exec() like:
with open("file.txt", 'r') as file:
for line in file:
exec(line)
+ 1
cont is simple a variable that contain a string object (file content)... For evalutate code, use global eval function
+ 1
after you read your file, you could use eval, or complie and then exec it like @ChaoticDawg said, but beware of the security hole it is
0
oh, right, didn't think about this