From 9c4e4577dcfc1a41c65a0a5bcc2d9e90eff28abc 2008-02-14 15:38:37 From: vivainio Date: 2008-02-14 15:38:37 Subject: [PATCH] _ip.runlines() is now much more liberal about indentation - it cleans up the scripts it gets --- diff --git a/IPython/ipapi.py b/IPython/ipapi.py index c0cf5e4..57c8960 100644 --- a/IPython/ipapi.py +++ b/IPython/ipapi.py @@ -263,11 +263,36 @@ class IPApi: Takes either all lines in one string or list of lines. """ + + def cleanup_ipy_script(script): + """ Make a script safe for _ip.runlines() + + - Removes empty lines + - Suffixes all indented blocks that end with unindented lines with empty lines + + """ + res = [] + lines = script.splitlines() + level = 0 + for l in lines: + stripped = l.lstrip() + if not l.strip(): + continue + newlevel = len(l) - len(stripped) + if level > 0 and newlevel == 0: + # add empty line + res.append('') + res.append(l) + level = newlevel + return '\n'.join(res) + '\n' + if isinstance(lines,basestring): - self.IP.runlines(lines) + script = lines else: - self.IP.runlines('\n'.join(lines)) + script = '\n'.join(lines) + clean=cleanup_ipy_script(script) + self.IP.runlines(clean) def to_user_ns(self,vars, interactive = True): """Inject a group of variables into the IPython user namespace. @@ -568,3 +593,4 @@ def make_session(user_ns = None): import IPython.Shell return IPython.Shell.start(user_ns) + diff --git a/test/test_ipapi.py b/test/test_ipapi.py index 31fde66..8bd3561 100644 --- a/test/test_ipapi.py +++ b/test/test_ipapi.py @@ -2,14 +2,34 @@ import sys sys.path.append('..') import IPython.ipapi - IPython.ipapi.make_session() ip = IPython.ipapi.get() def test_runlines(): + import textwrap ip.runlines(['a = 10', 'a+=1']) - ip.runlines('assert a == 11') + ip.runlines('assert a == 11\nassert 1') + assert ip.user_ns['a'] == 11 + complex = textwrap.dedent("""\ + if 1: + print "hello" + if 1: + print "world" + + if 1: + print "foo" + if 1: + print "bar" + + if 1: + print "bar" + + """) + + + ip.runlines(complex) + def test_db(): ip.db['__unittest_'] = 12