首页 > 解决方案 > 如何通过python运行一行文件并获取输出

问题描述

我想读取文件的一行并将其提供给 python 并获取输出。例如

我写:

a = 0
b = 10
c = 100
a == b-10 and b== c-100

在蟒蛇中:

file = open("new.txt")
run(file[0])
run(file[1])
run(file[2])
print(out(file[3]))

我想要最后一行的 True 。任何想法?

标签: pythonpython-3.x

解决方案


最后一行,a == b - 10 和 b == c-100 由于 b != c-100 不评估为 True,但我认为您正在寻找的是:

with open("input.txt") as f:

    lines = [line for line in f.readlines()]
    exec(lines[0])
    exec(lines[1])
    exec(lines[2])
    print(eval(lines[3]))

推荐阅读