From ade8ee2775c4910b1d40d030a8a607d4e9642167 2012-02-18 23:10:34 From: MinRK Date: 2012-02-18 23:10:34 Subject: [PATCH] ignore errors in shell.var_expand If an error is raised in the formatter, leave it untransformed. This means that var_expand("$foo") will return "$foo" if `foo` is undefined, but more importantly it will *not* raise when var_expand is used on literal code that doesn't expect to be expanded (e.g. %prun arguments). Tests included. --- diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py index 8ea90d7..7775b63 100644 --- a/IPython/core/interactiveshell.py +++ b/IPython/core/interactiveshell.py @@ -2675,7 +2675,12 @@ class InteractiveShell(SingletonConfigurable, Magic): ns = self.user_ns.copy() ns.update(sys._getframe(depth+1).f_locals) ns.pop('self', None) - return formatter.format(cmd, **ns) + try: + cmd = formatter.format(cmd, **ns) + except Exception: + # if formatter couldn't format, just let it go untransformed + pass + return cmd def mktempfile(self, data=None, prefix='ipython_edit_'): """Make a new tempfile and return its filename. diff --git a/IPython/core/tests/test_interactiveshell.py b/IPython/core/tests/test_interactiveshell.py index 581d5c5..5b65e9f 100644 --- a/IPython/core/tests/test_interactiveshell.py +++ b/IPython/core/tests/test_interactiveshell.py @@ -235,10 +235,24 @@ class InteractiveShellTestCase(unittest.TestCase): ip = get_ipython() ip.user_ns['f'] = u'Ca\xf1o' self.assertEqual(ip.var_expand(u'echo $f'), u'echo Ca\xf1o') + self.assertEqual(ip.var_expand(u'echo {f}'), u'echo Ca\xf1o') + self.assertEqual(ip.var_expand(u'echo {f[:-1]}'), u'echo Ca\xf1') + self.assertEqual(ip.var_expand(u'echo {1*2}'), u'echo 2') ip.user_ns['f'] = b'Ca\xc3\xb1o' # This should not raise any exception: ip.var_expand(u'echo $f') + + def test_bad_var_expand(self): + """var_expand on invalid formats shouldn't raise""" + ip = get_ipython() + + # SyntaxError + self.assertEqual(ip.var_expand(u"{'a':5}"), u"{'a':5}") + # NameError + self.assertEqual(ip.var_expand(u"{asdf}"), u"{asdf}") + # ZeroDivisionError + self.assertEqual(ip.var_expand(u"{1/0}"), u"{1/0}") class TestSafeExecfileNonAsciiPath(unittest.TestCase):