10

I'm working on a package, and I have a structure like:

 mypackage/
    __init__.py
    __main__.py
    someotherstuff.py
    test/
        __init__.py
        testsomeotherstuff.py

I've set it up so that the main.py function runs some unit tests, and executing python mypackage from the command-line works fine. However often I want to debut using ipython, but from the interpreter, run mypackage gives the error ERROR: File 'mypackage.py' not found. I can run it manually by doing run mypackage/__main__.py but somehow this seems wrong. Is there something else I should have done to set this up correctly?

1
  • 5
    The ability to do %run -m mypackage was added in a recent version - I don't know if that works for your case. Commented Mar 9, 2012 at 17:26

1 Answer 1

8

Running a package as a program was introduced in Python 2.5. I don't think IPython has a native feature for this, but starting with version 2.7, the Python standard library has, namely the runpy.run_module() function. Note that this behaves slightly different than IPython's %run, since it will return the global dictionary of the module instead of directly importing it into the interpreter scope.

Sign up to request clarification or add additional context in comments.

5 Comments

That gives me an error: ImportError: mypackage is a package and cannot be directly executed
@tdc: What Python version are you using?
Python 2.6.5 - which makes it odd that it runs from the command line then?
In Python 3.11 I do runpy.run_module("mypkg.my_module", run_name=__name__) to run the code inside the __main__ section of a submodule. I cannot manage to pass arguments (in sys.argv), though
@JuanPi Modules look at sys.argv themselves for their command line options. Since this is where they look, you need to modify sys.argv before calling run_module() to pass in arguments. This isn't the prettiest thing to do, since you pass parameters via global state, but in general the only alternative is forking a new interpreter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.