前言:
我们知道,python代码文件大多数都是py类型。
那么,能不能使用txt文件存储我们的代码呢?
python这么强大的语言当然可以做大,只需使用内置的exex()函数。
1.什么是exec()函数?
根据官方文档的介绍,exec函数的定义如下:
1
2
3
4
5
|
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()函数将代码一次性读取:
1
2
|
with open ( "code.txt" , "r" ) as f: code = f.read() |
其中“code.txt”就是想要执行的代码,其中不应该包含语法错误,否则不便于调试(最好是将已经调试完成的代码放入txt中)。
3.使用exec()执行txt文件的完整例子
(1)在txt文件中写代码,比如:
1
2
3
4
5
|
def mul(x, y): print ( "x*y = {}" . format (x * y)) return x * y mul( 2 , 3 ) |
(2)以字符串形式读取“code.txt”文件内容:
1
2
|
with open ( "code.txt" , "r" ) as f: code = f.read() |
(3)使用exec()执行字符串:
1
|
exec (code) |
到此这篇关于如何利用python执行txt文件中的代码的文章就介绍到这了,更多相关python执行txt文件代码内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://zhuanlan.zhihu.com/p/112213767