Error in python exec command

Asked

Viewed 83 times

0

I’m trying to accomplish an action through command exec():

import asyncio
from pyppeteer import launch

async def main(a): #função que executará o comando
    exec(a)

c="""browser = await launch() #inicializa navegador
    page = await browser.newPage()
    await page.goto('https://translate.google.com/?hl=pt-BR', timeout= 0) #timeout = 0 serve para impossibilitar erro por timeout
    dimensions = await page.evaluate('''() => {
        return {
            "width": document.documentElement.clientWidth,
            "height": document.documentElement.clientHeight
        }
    }''') #define as dimensões do navegador
    await page.setViewport(dimensions)
    await page.click('.tlid-open-source-language-list', button='left')
    await page.screenshot({'path': r'C:\Users\Windows 7\Desktop\yes.png'})
    await browser.close() #fecha navegador
"""
asyncio.get_event_loop().run_until_complete(main(c)) #executa a função main()
input('fim')

The interpreter indicates an error such as invalid syntax on the line browser = await launch(), and that code works perfectly when it runs directly, so there’s something wrong when it’s inserted into a string and then exec().

By the way, the following code works very well:

def x(y):
    exec(y)
x('''print("oi")
print('tchau')''')

So the problem is not that a multi-line string is exec(). As all the interpreter indicates is Syntax Error: invalid syntax, I don’t know how to make the code work.

1 answer

0


According to this overflow response, exec() of a multiline string causes complications in the formatting of the code, so it is necessary to enter the function in another function that will prevent the error.

The corrected code is:

import asyncio
from pyppeteer import launch

async def main(a):
    exec(f'async def __ex(): ' +
        ''.join(f'\n {l}' for l in a.split('\n'))
    )
    return await locals()['__ex']()

c=r"""browser = await launch()
page = await browser.newPage()
await page.goto('https://translate.google.com/?hl=pt-BR', timeout= 0)
dimensions = await page.evaluate('''() => {
    return {
        "width": document.documentElement.clientWidth,
        "height": document.documentElement.clientHeight
    }
}''')
await page.setViewport(dimensions)
await page.click('.tlid-open-source-language-list', button='left')
await page.screenshot({'path': r'C:\Users\Windows 7\Desktop\yes.png'})
await browser.close()
"""
asyncio.get_event_loop().run_until_complete(main(c))
input('fim')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.