I have a file, "file.txt
":
some text
some more text
*
a = 10
if a == 10:
print (a)
else:
print ("hello world")
/*
some text
some more text
I extract the text between *
and /*
from the file and store is line by line into a list:
['a = 10', 'if a == 10:', ' print (a)', 'else:', ' print ("hello world")']
with:
list = []
for line in open("file.txt", 'r'):
if line.startswith("*"):
store = True
if line.startswith("/*"):
store = False
if store == True:
if line.startswith("*"): pass
else: list.append(line)
After that I want to execute the code inside the list.
I came halfway with the following code with exec
and compile
:
code_to_execute = compile("""
a = 10
if a == 10:
print (a)
else:
print ("hello world")
""", '<string>', 'exec')
and:
exec code_to_execute
But I would like to do that with the use of the list
: in the sense of:
code_to_execute = compile(list)
exec code_to_execute
How can I do this with python ? (preferably python2.7)
The problem is not how to join the members of a list into a string. The problem is how to execute a multiline variable. Since if I would make a string out of a list I'll lose the newlines and indentation, besides I thought it is not possible to do something like:
string = "print \"hello world\""
code_to_execute = compile(""" """ + string + """ """, '<string>', 'exec')
or is it ?