+ 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?

21st Apr 2018, 7:38 PM
David Shlomo
6 Respostas
+ 9
Check it out - codes created by codes created and run by codes... 😉 https://code.sololearn.com/c5f76DBYhYSO/?ref=app
22nd Apr 2018, 5:21 AM
Kuba SiekierzyƄski
Kuba SiekierzyƄski - avatar
+ 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
21st Apr 2018, 8:09 PM
ChaoticDawg
ChaoticDawg - avatar
+ 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)
21st Apr 2018, 9:32 PM
ChaoticDawg
ChaoticDawg - avatar
+ 1
cont is simple a variable that contain a string object (file content)... For evalutate code, use global eval function
21st Apr 2018, 7:42 PM
KrOW
KrOW - avatar
+ 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
21st Apr 2018, 9:06 PM
Amaras A
Amaras A - avatar
0
oh, right, didn't think about this
21st Apr 2018, 10:33 PM
Amaras A
Amaras A - avatar