Skip to content

%run -m doesn't support relative imports #2727

Closed
pag opened this Issue Dec 29, 2012 · 2 comments

3 participants

@pag
pag commented Dec 29, 2012

I'm trying to use %run -m to run modules within some packages, but it doesn't work quite like python -m: it doesn't support relative imports.

For example, I have the following two files:

  • ./foo/init.py

    x = 1
    
  • ./foo/bar.py

    from . import x
    print x
    

With python -m foo.bar or ipython -m foo.bar the output is x. With %run, however:

>>> run -m test.bar
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/IPython/utils/py3compat.py", line 179, in execfile
    __builtin__.execfile(filename, *where)
  File "/private/tmp/test/bar.py", line 1, in <module>
    from . import x
ValueError: Attempted relative import in non-package
@bfroehle

Yes, confirmed bug. The %run code is pretty involved, so it might be a bit of a project to fix this.

As a temporary solution (and inspiration for an eventual patch) look at runpy.run_module which you could use as:

In [6]: import runpy

In [7]: runpy.run_module('foo.bar');
1
@tkf tkf added a commit to tkf/ipython that referenced this issue Mar 23, 2013
@tkf tkf Test for #2727 (%run -m doesn't support relative imports)
test_run_submodule_with_relative_import fails.
ced51b9
@tkf
tkf commented Mar 23, 2013

I fixed this in #3066

@bfroehle bfroehle closed this in 9087bb9 May 3, 2013
@mattvonrocketstein mattvonrocketstein pushed a commit to mattvonrocketstein/ipython that referenced this issue Nov 3, 2014
@tkf tkf Test for #2727 (%run -m doesn't support relative imports)
test_run_submodule_with_relative_import fails.
8e595f2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.