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

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

Comments

Projects
None yet
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

This comment has been minimized.

Show comment
Hide comment
@bfroehle

bfroehle Jan 10, 2013

Contributor

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
Contributor

bfroehle commented Jan 10, 2013

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 added a commit to tkf/ipython that referenced this issue Mar 23, 2013

Test for #2727 (%run -m doesn't support relative imports)
test_run_submodule_with_relative_import fails.
@tkf

This comment has been minimized.

Show comment
Hide comment
@tkf

tkf Mar 23, 2013

Contributor

I fixed this in #3066

Contributor

tkf commented Mar 23, 2013

I fixed this in #3066

@bfroehle bfroehle closed this in 9087bb9 May 3, 2013

mattvonrocketstein pushed a commit to mattvonrocketstein/ipython that referenced this issue Nov 3, 2014

Test for #2727 (%run -m doesn't support relative imports)
test_run_submodule_with_relative_import fails.

mattvonrocketstein pushed a commit to mattvonrocketstein/ipython that referenced this issue Nov 3, 2014

Merge pull request #3066 from tkf/run-module
Add support for relative import to %run -m (fixes #2727)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment