0

I write a python code generator as an input it has a source code: source Part of the output I need to generate is execute(source_code) When source_code is a string representing source . If I write "execute({0})".format(source) for input source = "import sys" i'll get execute(import sys). So I tried : execute(\"\"\"{0}\"\"\")format(source). Is it ok? I tried to test it...Sometimes it is ok....The problem occurs when inside the source there are""" For example:

from IPython.display import HTML

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

my code turns to be

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

UPD: Changing the code to

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

doesn`t solve the problem, the issue will be encountered with :

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

1 Answer 1

1

Using single triple quotes should help:

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

Running in a Notebook, you need to use eval() to actually display the HTML:

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

In your case probably:

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

Works also if there are ''' inside the string:

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

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

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

Output:

3
Sign up to request clarification or add additional context in comments.

1 Comment

changing to execute('''{0}''')format(source) indeed works! thanks! but what happens if inside source there is '''? I will encounter the same issue?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.