【发布时间】:2017-07-19 15:59:39
【问题描述】:
我写了一个python代码生成器
作为输入,它有一个源代码:source
我需要生成的部分输出是execute(source_code)
当 source_code 是代表 source 的字符串时。
如果我为输入源写"execute({0})".format(source) = "import sys"
我会得到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))
【问题讨论】:
标签: python string exec code-generation