Merge pull request #266 from rth/dedent-by-default

Handle multi-line Python strings input in JS
This commit is contained in:
Michael Droettboom 2018-12-10 17:25:37 -05:00 committed by GitHub
commit 81cd031360
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 6 deletions

View File

@ -4,6 +4,7 @@ A library of helper utilities for connecting Python to the browser environment.
import ast import ast
import io import io
from textwrap import dedent
__version__ = '0.3.0' __version__ = '0.3.0'
@ -24,6 +25,9 @@ def eval_code(code, ns):
""" """
Runs a string of code, the last part of which may be an expression. Runs a string of code, the last part of which may be an expression.
""" """
# handle mis-indented input from multi-line strings
code = dedent(code)
mod = ast.parse(code) mod = ast.parse(code)
if isinstance(mod.body[-1], ast.Expr): if isinstance(mod.body[-1], ast.Expr):
expr = ast.Expression(mod.body[-1].value) expr = ast.Expression(mod.body[-1].value)
@ -44,6 +48,9 @@ def find_imports(code):
Finds the imports in a string of code and returns a list of their package Finds the imports in a string of code and returns a list of their package
names. names.
""" """
# handle mis-indented input from multi-line strings
code = dedent(code)
mod = ast.parse(code) mod = ast.parse(code)
imports = set() imports = set()
for node in ast.walk(mod): for node in ast.walk(mod):

View File

@ -102,17 +102,11 @@ class SeleniumWrapper:
self.driver.execute_script("window.logs = []") self.driver.execute_script("window.logs = []")
def run(self, code): def run(self, code):
if isinstance(code, str) and code.startswith('\n'):
# we have a multiline string, fix indentation
code = textwrap.dedent(code)
return self.run_js( return self.run_js(
'return pyodide.runPython({!r})'.format(code)) 'return pyodide.runPython({!r})'.format(code))
def run_async(self, code): def run_async(self, code):
from selenium.common.exceptions import TimeoutException from selenium.common.exceptions import TimeoutException
if isinstance(code, str) and code.startswith('\n'):
# we have a multiline string, fix indentation
code = textwrap.dedent(code)
self.run_js( self.run_js(
""" """
window.done = false; window.done = false;