作为 Python 代码运行并评估导入的文本文件

问题描述 投票:0回答:2

我有一些动态生成并存储在文本文件中的 Python 代码。它基本上由各种变量组成,例如存储数据的列表和字符串。该信息被提供给一个类来实例化不同的对象。如何将文本文件中的数据输入到课堂中?

这是我的课:

class SomethingA(Else):
    def construct(self):
        // feed_data_a_here
        self.call_method()

class SomethingB(Else):
    def construct(self):
        // feed_data_b_here
        self.call_method()

以下是

text_a
文件中的一些示例内容。正如您所看到的,这是一些有效的 Python 代码,我需要将其直接输入到对象中。调用
call_method()
取决于此输出数据。

self.height = 12
self.id = 463934
self.name = 'object_a'

有没有办法将这些数据加载到类中,而无需从文本文件中手动复制和粘贴所有数据?

谢谢。

python python-3.x file oop inheritance
2个回答
2
投票

我可能会为你的文件编写一个解析器来删除“self”。在开头并将变量添加到字典中:

import re

# You could use more apprpriate regex depending on expected var names
regex = 'self\.(?P<var_name>\D+\d*) = (?P<var_value>.*)'
attributes= dict()
with open(path) as file:
    for line in file:
        search = re.search(regex, line)
        var_name = search.group(var_name)
        var_value = search.group(var_value).strip() # remove accidentalwhite spaces
        attributes[var_name] = var_value

foo = classA(**attributes)

工作中的正则表达式示例

编辑

如果您使用我建议的代码,字典中的所有项目都将是字符串类型。也许你可以尝试:

  • eval()
    ,由@Welgriv 提议,但稍作修改:
eval(f'attributes[{var_name}] = {var_value}')
  • 如果您的数据由标准 python 数据组成并且格式正确,您可以尝试使用
    json
    :
import json

x = '12'
y = '[1, 2, 3]'
z = '{"A": 50.0, "B": 60.0}'

attributes = {}
for i, v in enumerate([x, y, z]):
    attributes[f'var{i+1}'] = json.loads(v)

print(attributes)

# Prints
# {'var1': 12, 'var2': [1, 2, 3], 'var3': {'A': 50.0, 'B': 60.0}}

2
投票

您可能会寻找 eval() 函数。它评估并尝试将 python 表达式作为文本执行。例如:

eval('print("All your base are belong to us")')

将打印该句子。在您的情况下,您应该打开文本文件,然后对其进行评估。

备注

  • eval()
    函数存在一些安全问题,因为用户可能会执行任何代码。
  • 我不确定您尝试实现的总体上下文是什么,但您可能更喜欢以不同于 python 代码的方式存储数据(名称、id、高度...),例如键值或其他方式,因为它将使您的应用程序极度依赖于环境。举个例子,如果有 python 更新并且某些代码被弃用,您的应用程序将不再工作。
© www.soinside.com 2019 - 2024. All rights reserved.