Search code examples
pythoneclipsepython-3.xpydevpython-import

Python3 -m run configuration in Eclipse


Update 2021: Solution is built into PyDev/Eclipse

See accepted answer for details

Original Question (and old answers) for below

As many comments/questions/rants on SO and other places will tell you, Python3 packages using relative imports want to be run from a central __main__.py file. In the case where a module, say "modA" within a package, say "packA", that uses relative imports needs to be run (for instance because a test package is run if __name__ == '__main__'), we are told to run instead run python3 -m modA.packA from the directory above modA if sys.path() does not contain the directory above modA. I may dislike this paradigm, but I can work around it.

When trying to run modA from Eclipse/PyDev, however, I can't figure out how to specify a run configuration that will execute the module properly with the -m flag. Has anyone figured out how to set up a run configuration that will do this properly?

References: Relative imports for the billionth time ; Relative import in Python 3 is not working ; Multilevel relative import


Solution

  • Nowadays (since PyDev 5.4.0 (2016-11-28)) you can go to the Settings > PyDev > Run and select Launch modules with python -m mod.name instead of python filename.py ;)

    See: https://www.pydev.org/history_pydev.html


    For older versions of PyDev (old answer)

    Unfortunately, right now, it's not automatic running with -m in PyDev, so, I'll present 3 choices to work in PyDev with relative imports which are preceded by a dot (in PyDev version 4.3.0):

    1. Don't use relative imports, only absolute imports in your __main__ modules.

    2. Create a separate module for the __main__ which will do an absolute import for the module you want to run and run that module instead (if you're distributing your application, this is probably needed anyways as the usual way for people to launch your code in Python is by passing the script as an argument to Python and not using the -m switch).

    3. Add the -m module to the vm arguments in your run configuration by doing:

    • Make the run (which will fail because of the relative import)
    • Right-click the editor > Copy Context Qualified Name
    • Open the run configuration: Alt, R, N (i.e.: Toolbar > Run > Run Configuration)
    • Open arguments tab and add the '-m Ctrl+V' (to add the -m and the module name you copied previously).

    Although this is definitely not ideal: you'll now receive an argument with the filename (as PyDev will always pass that to run the file) and the whole process is a nuisance.

    As a note, I do hope to provide a way to make runs within PyDev using the -m soon (hopefully for PyDev 4.4.0)... although this may not be possible if the file being run is not under the PYTHONPATH (i.e.: to run an external file it still has to support the option without the -m).