gpt4 book ai didi

python - 如何读取和执行文件中的脚本

转载 作者:行者123 更新时间:2023-12-04 16:36:37 24 4
gpt4 key购买 nike

这是一个简化的示例,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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com