这是一个简化的示例,python程序在设备上运行并等待文本文件了解下一步如何执行,文本文件将频繁上传到设备。
如何让python程序将文本文件(在本例中,steps.txt
只有一行"z = x + y"
)“翻译”成可执行脚本?
import os
import time
x = 3
y = 9
s = None
while 1:
time.sleep(1)
try:
with open("steps.txt", 'r') as f:
s = f.readline()#s = "z = x + y"
f.close()
break
except:
pass
os.system(s)#'z' is not recognized as an internal or external command,operable program or batch file.
最佳答案
正如您在帖子中所包含的那样,命令提示符返回了此错误
'z' is not recognized as an internal or external command,operable program or batch file.
当您将字符串 "z = x + y"
传递给 os.system()
时。那是因为该命令未在 python 中运行。我相信你想做的是
# s = "z = x + y"
os.system(f'python -c "{s}"')
这当然会返回一个 NameError
。
相反,要执行 python 程序中的代码行,请使用 exec()
方法,如下所示:
# s = "z = x + y"
exec(s)
但请注意!两者 exec() and eval() should really be avoided ,因为它们会带来严重的安全问题。
注意:f.close()
不是必需的,因为您使用了 with
语句。
关于python - 如何读取和执行文件中的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69147840/