How to use python to execute the code in txt file
This article mainly shows you "how to use python to execute the code in txt files", the content is easy to understand, clear, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "how to use python to execute the code in txt files" this article.
Foreword:
We know that most of the python code files are of type py.
So, can we use txt files to store our code?
Of course, a language as powerful as python can be made bigger by using the built-in exex () function.
1. What is the exec () function?
According to the official documentation, the definition of the exec function is as follows:
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 ().
In a nutshell, exec () can accept a string that represents python code and execute the string as code (the concepts of globals and locals are not covered here, which will be supplemented in a later article).
two。 How do I read the code in txt as a string?
You can do this simply by using python's built-in file stream operation, such as using the read () function of the File object to read the code at once:
With open ("code.txt", "r") as f: code = f.read ()
Where "code.txt" is the code you want to execute, which should not contain syntax errors, otherwise it is not easy to debug (it is best to put the debugged code into txt).
3. A complete example of executing a txt file using exec ()
(1) write code in the txt file, such as:
Def mul (x, y): print ("x y = {}" .format (x y)) return x*ymul (2, 3)
(2) read the contents of the "code.txt" file as a string:
With open ("code.txt", "r") as f: code = f.read ()
(3) execute the string using exec ():
Exec (code) above is all the contents of the article "how to use python to execute the code in the txt file". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!