Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit e08519b

Browse files
authored
Merge pull request #12708 from adityausathe/12107_parse_opts
Issue #12107 fix: additional spaces while parsing timeit-magic options
2 parents 7e0c8b7 + e6fa312 commit e08519b

3 files changed

Lines changed: 39 additions & 7 deletions

File tree

IPython/core/magic.py

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,9 @@ def parse_options(self, arg_str, opt_str, *long_opts, **kw):
618618
posix = kw.get('posix', os.name == 'posix')
619619
strict = kw.get('strict', True)
620620

621+
preserve_non_opts = kw.get("preserve_non_opts", False)
622+
remainder_arg_str = arg_str
623+
621624
# Check if we have more than one argument to warrant extra processing:
622625
odict = {} # Dictionary with options
623626
args = arg_str.split()
@@ -629,10 +632,18 @@ def parse_options(self, arg_str, opt_str, *long_opts, **kw):
629632
try:
630633
opts,args = getopt(argv, opt_str, long_opts)
631634
except GetoptError as e:
632-
raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
633-
" ".join(long_opts))) from e
634-
for o,a in opts:
635-
if o.startswith('--'):
635+
raise UsageError(
636+
'%s ( allowed: "%s" %s)' % (e.msg, opt_str, " ".join(long_opts))
637+
) from e
638+
for o, a in opts:
639+
if mode is "string" and preserve_non_opts:
640+
# remove option-parts from the original args-string and preserve remaining-part.
641+
# This relies on the arg_split(...) and getopt(...)'s impl spec, that the parsed options are
642+
# returned in the original order.
643+
remainder_arg_str = remainder_arg_str.replace(o, "", 1).replace(
644+
a, "", 1
645+
)
646+
if o.startswith("--"):
636647
o = o[2:]
637648
else:
638649
o = o[1:]
@@ -649,7 +660,10 @@ def parse_options(self, arg_str, opt_str, *long_opts, **kw):
649660
# Prepare opts,args for return
650661
opts = Struct(odict)
651662
if mode == 'string':
652-
args = ' '.join(args)
663+
if preserve_non_opts:
664+
args = remainder_arg_str.lstrip()
665+
else:
666+
args = " ".join(args)
653667

654668
return opts,args
655669

IPython/core/magics/execution.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,8 +1073,9 @@ def timeit(self, line='', cell=None, local_ns=None):
10731073
does not matter as long as results from timeit.py are not mixed with
10741074
those from %timeit."""
10751075

1076-
opts, stmt = self.parse_options(line,'n:r:tcp:qo',
1077-
posix=False, strict=False)
1076+
opts, stmt = self.parse_options(
1077+
line, "n:r:tcp:qo", posix=False, strict=False, preserve_non_opts=True
1078+
)
10781079
if stmt == "" and cell is None:
10791080
return
10801081

IPython/core/tests/test_magic.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -472,6 +472,23 @@ def test_parse_options():
472472
nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
473473

474474

475+
def test_parse_options_preserve_non_option_string():
476+
"""Test to assert preservation of non-option part of magic-block, while parsing magic options."""
477+
m = DummyMagics(_ip)
478+
opts, stmt = m.parse_options(
479+
" -n1 -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True
480+
)
481+
nt.assert_equal(opts, {"n": "1", "r": "13"})
482+
nt.assert_equal(stmt, "_ = 314 + foo")
483+
484+
485+
def test_run_magic_preserve_code_block():
486+
"""Test to assert preservation of non-option part of magic-block, while running magic."""
487+
_ip.user_ns["spaces"] = []
488+
_ip.magic("timeit -n1 -r1 spaces.append([s.count(' ') for s in ['document']])")
489+
assert _ip.user_ns["spaces"] == [[0]]
490+
491+
475492
def test_dirops():
476493
"""Test various directory handling operations."""
477494
# curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')

0 commit comments

Comments
 (0)