【问题标题】:how to read and execute the scripts in file如何读取和执行文件中的脚本
【发布时间】:2021-09-12 01:38:23
【问题描述】:

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

【问题讨论】:

    标签: python


    【解决方案1】:

    正如您在帖子中包含的那样,命令提示符返回了此错误

    '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 语句。

    【讨论】:

      【解决方案2】:

      您可以使用exec,而不是os.system(s)

      exec(s)
      

      但请注意,这确实不安全,更多细节here

      【讨论】:

      • 谢谢,如果我在steps.txt中有多行,我应该如何使用这个?
      • 我注意到我必须使用readlines(), 和exec(s[0]), exec(s[1]).....,这和你的意思一样吗?跨度>
      • @adameye2020 是的!
      • 想知道是否有更好的方法来逐行执行,我记得在 Matlab 中我可以在一行中执行完整的脚本
      • @adameye2020 您可以使用read 而不是readlines,而不是1 个字符串,或者使用for 循环,例如for line is s: exec(line)
      猜你喜欢
      • 2016-12-08
      • 1970-01-01
      • 2014-02-24
      • 2011-12-18
      • 2017-12-20
      • 1970-01-01
      • 2011-05-26
      • 2013-06-14
      • 1970-01-01
      相关资源
      最近更新 更多