gpt4 book ai didi

python - 如何执行存储在列表中的Python代码?

转载 作者:行者123 更新时间:2023-12-01 02:25:48 25 4
gpt4 key购买 nike

我有一个文件“file.txt”:

some text
some more text
*
a = 10
if a == 10:
print (a)
else:
print ("hello world")
/*
some text
some more text

我从文件中提取 */* 之间的文本,并将其逐行存储到列表中:

['a = 10', 'if a == 10:', '    print (a)', 'else:', '    print ("hello world")']

与:

list = []
for line in open("file.txt", 'r'):
if line.startswith("*"):
store = True
if line.startswith("/*"):
store = False
if store == True:
if line.startswith("*"): pass
else: list.append(line)

之后我想执行列表中的代码。我使用 execcompile 编写了以下代码:

code_to_execute = compile("""
a = 10
if a == 10:
print (a)
else:
print ("hello world")
""", '<string>', 'exec')

和:

exec code_to_execute

但我想通过使用 list 来做到这一点:在以下意义上:

code_to_execute = compile(list)
exec code_to_execute

如何使用 python 来做到这一点? (最好是python2.7)

问题不在于如何将列表的成员连接到字符串中。问题是如何执行多行变量。因为如果我从列表中创建一个字符串,我将丢失换行符和缩进,此外我认为不可能执行以下操作:

string = "print \"hello world\""
code_to_execute = compile(""" """ + string + """ """, '<string>', 'exec')

或者是吗?

最佳答案

有点不清楚你要什么,但我将从这个声明开始

But I would like to do that with the use of the list: in the sense of:

code_to_execute = compile(list)
exec code_to_execute

并敦促您遵循@dseuss 的评论,只需这样做

code_to_execute = compile("\n".join(list), "<string>", "exec")
exec code_to_execute

不,您不会丢失换行符。你试过这个吗?

示例:

>>> l = ['a = 10', 'if a == 10:', '    print (a)', 'else:', '    print ("hello world")']
>>> code_to_execute = compile("\n".join(l), "<string>", "exec")
>>> exec code_to_execute
10

关于python - 如何执行存储在列表中的Python代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47413958/

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