如何从txt文件导入行并使其成为变量值python?

How to import line from txt file and make it a variable value python?

我有一个 test.txt 文件,现在有 2 行

not False == True
not True == True

我正在尝试将其导入我的函数,以便它显示带有输入的文本,然后实际进行布尔计算 然后对每一行再做一次。它适用于第 6 行的输入,但第 7 行不起作用,我知道为什么,我只是不知道如何做我想做的...

def calc (read):
    line = read.readline()

    if line:
        lines = line.strip()
        input(f"Does {lines}?>")
        print(f"{lines}")
        return calc(boolfile)

boolfile = open("test.txt")
calc(boolfile)

您似乎在寻找 eval。 试试这个:

def calc (read):
    line = read.readline()

    if line:
        lines = line.strip()
        input(f"Does {lines}?>")
        print(eval(lines))
        return calc(boolfile)

boolfile = open("test.txt")

calc(boolfile)

输出:

Does not False == True?>
True
Does not True == True?>
False

f-strings 只能计算源代码中 f-string 内部的表达式。

如果你想评估一个包含表达式表示的字符串,就好像它是源代码一样,你需要使用 eval.

eval 几乎总是一个坏主意的原因有很多(tl;dr:任何可以更改您传递给 eval 的输入的人都可以让您达到 运行 他们想要的任何代码)。但如果那真的是你想要做的,那就是这样做的方式:

if line:
    lines = line.strip()
    input(f"Does {lines}?>")
    print(eval(lines))

如果你想做一些更安全的事情,你唯一能做的就是将代码解析和解释为比 "any Python expression" 更安全的东西。这并不像听起来那么难(特别是因为,如果你的语言是 Python 的精确子集,你可以只使用 ast 模块来进行解析,而你只需要编写解释器部分), 但它不完全是单行的。