生成用于执行的python代码(自动更正“”)

2024-04-24 11:41:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一个python代码生成器 作为输入,它有一个源代码:source 我需要生成的部分输出是execute(source_code)source_code是表示source的字符串时。 如果我为input source=“import sys”写入"execute({0})".format(source) 我去拿execute(import sys)。 所以我试着:execute(\"\"\"{0}\"\"\")format(source)。可以吗?我试着测试它…有时它是好的…问题发生在源代码中有""" 例如:

from IPython.display import HTML

HTML("""
<script>
console.log("hello");
</script>
<b>HTML</b>
""")

我的密码是

execute("""from IPython.display import HTML
HTML("""
<script>
console.log("hello");
</script>
<b>HTML</b>
""")""")

升级版: 将代码更改为

execute('''{0}''').format(source)

如果无法解决问题,则会遇到以下问题:

def tojson(data):
    '''Shorten the code to respond a little bit.'''
    print(json.dumps(data))

Tags: fromimportlogformatsourcehelloexecute源代码
1条回答
网友
1楼 · 发布于 2024-04-24 11:41:24

使用单引号和三引号应有助于:

execute('''from IPython.display import HTML
HTML("""
<script>
console.log("hello");
</script>
<b>HTML</b>
""")''')

在笔记本中运行时,需要使用eval()来实际显示HTML

exec('''from IPython.display import HTML''')
eval('''HTML("""
<script>
console.log("hello");
</script>
<b>HTML</b>
""")''')

在您的情况下,可能:

execute('''{0}''').format(source)

如果字符串中有''',也可以使用:

source = """
def add(a, b):
    '''Add'''
    return a + b

print(add(1, 2))
"""

exec('''{0}'''.format(source))

输出:

3

相关问题 更多 >