Python how to execute code from a txt file

♀尐吖头ヾ 提交于 2020-01-11 07:36:11

问题


I want to keep a piece of code in a txt file and execute it from my Python script.

For example in the txt file there is

print("ok")

I want my programme to print ok and not print print("ok "). How can I do this?


回答1:


Doing what you want usually is a security risk, but not necessarily so.

You'll definitely have to notify the user about potential risk.

There is more than one program using execfile() or compile() and exec statement to provide plug-ins system.

There is nothing so ugly about it, you just have to know what are you doing, when and where.

Both execfile(), eval() and exec statement allow you to specify a scope in which will your code be executed/evaluated.

myscope = {}
execfile("myfile.txt", myscope)

This will prevent the new code being mixed with the old one. All variables classes, functions and modules from myfile.txt will be contained in myscope dictionary.

This, however, does not prevent malicious code to delete all files it can from your disk or something similar.

Python 2 has a nice module called rexec, but from Python 2.2 it doesn't work any more.

It implements execfile() exec statement and eval() in restricted environment. Though it doesn't work it is there, and you can dig through the code to see how it is done.

So, you see, it is possible to allow only secure code to execute (well, as secure as it can be) from external source.

There is another way too. You can load the file, compile the code from it and then inspect it to see what it does. Then say, yes I'll execute it or no, I won't. This is, however, a little bit more work and a lot of complications.

But, I don't think that it'll be necessary to go through all that stuff. Please elaborate some more on your problem. What exactly do you mean by level editor? I don't think external code is a solution for that.




回答2:


You are looking for eval function

eval is a function that takes arbitrary python code represented as a string and execute it at run time.

Example

>>> x = 1
>>> y = eval('x+1')
>>> print(y)
2

It works in both Python 2.x and 3.x

Check the documentation : https://docs.python.org/2.7/library/functions.html#eval



来源:https://stackoverflow.com/questions/31704916/python-how-to-execute-code-from-a-txt-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!