[英]Executing a text file as Python source code
如何使用 Python 運行文本文件?
例如; 如果文本文件名為textfile.txt
,並且它包含以下行:
print("Hello")
如何使用 Python 將其作為代碼行運行?
只需調用 python 解釋器並將文件傳遞給它:
python yourfile.txt
您可以使用 exec: https : //docs.python.org/3/library/functions.html#exec這樣您的代碼看起來就像這樣:
filehandle = open("filename.txt","r")
code_to_execute = filehandle.read()
exec(code_to_execute)
請記住,您的文件必須具有正確的語法,因此不會出現語法錯誤(主要是關於縮進)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.