Python如何从txt文件执行代码 [英] Python how to execute code from a txt file

查看:120
本文介绍了Python如何从txt文件执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在txt文件中保留一段代码,然后从我的Python脚本中执行它.

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

例如txt文件中有

print("ok")

我希望我的程序打印ok而不打印print("ok ").我该怎么办?

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

推荐答案

通常,做您想做的事会带来安全风险,但不一定如此.

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

您肯定必须将潜在风险通知用户.

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

有多个程序使用execfile()或compile()和exec语句来提供插件系统.

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.

execfile(),eval()和exec语句均允许您指定将在其中执行/评估代码的范围.

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)

这将防止新代码与旧代码混合. 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有一个很好的模块,称为rexec,但是从Python 2.2开始,它不再起作用.

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

它在受限环境中实现execfile()exec语句和eval(). 尽管它不起作用,但是它仍然存在,您可以浏览代码以查看其完成方式.

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.

这篇关于Python如何从txt文件执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆