如何利用python执行txt文件中的代码
作者:机器学习入坑者 时间:2021-03-01 04:47:46
前言:
我们知道,python代码文件大多数都是py类型。
那么,能不能使用txt文件存储我们的代码呢?
python这么强大的语言当然可以做大,只需使用内置的exex()函数。
1.什么是exec()函数?
根据官方文档的介绍,exec函数的定义如下:
exec(source, globals=None, locals=None, /)
? ? Execute the given source in the context of globals and locals.
? ??
? ? The source may be a string representing one or more Python statements
? ? or a code object as returned by compile().
简单的说,exec()可以接受代表python代码的字符串,并将字符串作为代码执行(关于globals和locals的概念这里暂时先不做介绍,后续文章会进行补充)。
2.如何将txt中的代码作为字符串读取?
这一步骤只需使用python内置的文件流操作即可,比如使用File对象的read()函数将代码一次性读取:
with open("code.txt", "r") as f:
? ? code = f.read()
其中“code.txt”就是想要执行的代码,其中不应该包含语法错误,否则不便于调试(最好是将已经调试完成的代码放入txt中)。
3.使用exec()执行txt文件的完整例子
(1)在txt文件中写代码,比如:
def mul(x, y):
? ? print("x*y = {}".format(x*y))
? ? return x*y
mul(2, 3)
(2)以字符串形式读取“code.txt”文件内容:
with open("code.txt", "r") as f: ? ?
? ? code = f.read()?
(3)使用exec()执行字符串:
exec(code)?
来源:https://zhuanlan.zhihu.com/p/112213767
标签:python,执行,txt,文件,代码
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
NumPy索引与切片的用法示例总结
2022-05-13 19:33:38
![](https://img.aspxhome.com/file/2023/4/80544_0s.png)
ASP实现GB2312字符与区位码的相互转换
2009-12-28 10:27:00
DreamWeaver制作会移动的广告条
2008-02-03 11:34:00
Python可变和不可变、类的私有属性实例分析
2023-05-27 14:34:08
Python实现大乐透号码随机生成
2022-09-04 18:46:01
python utc datetime转换为时间戳的方法
2021-11-18 07:11:44
django中模板继承与ModelForm实例详解
2021-09-05 18:52:10
![](https://img.aspxhome.com/file/2023/2/68922_0s.png)
如何使用python读取Excel指定范围并转为数组
2023-06-13 15:21:10
![](https://img.aspxhome.com/file/2023/0/105360_0s.jpg)
XSL学习教程:运算符和函数
2008-01-22 18:24:00
![](https://img.aspxhome.com/file/UploadPic/20081/22/200812219755424s.gif)
python 模拟登陆163邮箱
2021-08-03 09:30:11
php 查找数组元素提高效率的方法详解
2023-11-15 02:51:08
实例讲解Oracle到SQL Server主键迁移
2009-03-25 13:30:00
python爬虫利用selenium实现自动翻页爬取某鱼数据的思路详解
2021-05-20 08:43:26
![](https://img.aspxhome.com/file/2023/2/105192_0s.jpg)
PHP正则表达式替换<pre>标签外的内容
2023-05-22 10:47:12
Python深度学习pytorch神经网络多输入多输出通道
2022-05-10 11:10:06
![](https://img.aspxhome.com/file/2023/3/72973_0s.png)
Django中Aggregation聚合的基本使用方法
2023-09-15 02:38:29
pytz格式化北京时间多出6分钟问题的解决方法
2021-07-31 14:10:21
Mootools 1.2教程(7)——设置和获取样式表属性
2008-11-25 13:48:00
使用 Python 清理收藏夹里已失效的网站
2023-01-11 01:26:00
![](https://img.aspxhome.com/file/2023/8/87998_0s.jpg)
python面向对象版学生信息管理系统
2022-07-23 02:16:57
![](https://img.aspxhome.com/file/2023/8/87638_0s.jpg)