I'm trying to make a customization feature, so that users can run their own Python code. I know I could've just used another python code and call it as a module, but this is different. I'm turning it into an EXE file, and the module is already provided in the exe (so users can't make changes on the module). That is why I need to run it from a txt file. My plan is to read the contents of the txt file first (which contains the custom Python code), and run it with eval
. A single-lined code would work, but it wouldn't just run on 2-line (or more) codes. Is there any way we can do to read 2 or more lines of the txt file (that contains a whitespace/comment)? Thanks.
[EDIT: I'm sorry, I mean the code would go error if the user puts a whitespace or a comment (#), any way to allow them putting a whitespace or a comment? Thanks.]
My code is provided here:
import traceback
import os
from pathlib import Path
customscript = 'customscript.txt'#P.S: the name of the txt file is this
scriptpath = Path(customscript)
def scriptreset():
print("Couldn't find custom script, rewriting!")
with open(customscript, 'w+') as f:
f.write("#Write down your Python code here =]")
print("Done! Re-use this command")
try:
if scriptpath.is_file():
scriptfile = open(customscript)
lines = scriptfile.readlines()
for line in lines:
eval(line)
else:
scriptreset()
except Exception:
print(traceback.format_exc())
Inside the txt file:
print("HELLO WORLD")
Inside the alternate version of the txt file that will cause an error:
def pack():
print("Hi world!")#I love this world
input("Do you like earth?")
pack()