Create a PyCharm configuration that runs a module a la "python -m foo"

PythonPycharm

Python Problem Overview


My python entrypoint needs to be run as a module (not a script), as in:

python -m foo.bar

The following does not work (and is not supposed to):

python foo/bar.py

How can I create a run confirguration in pycharm that runs my code using the first invokation above?

Python Solutions


Solution 1 - Python

In 2018.1 it is finally possible to specify the module name instead of the script path in the UI. There is a dropdown for changing it, to the left of the input field.

PyCharm Run Configuration

Solution 2 - Python

There is a workaround I use for my scripts, which do use relative imports.

python -m actually invokes a script called runpy.py which is part of a standard Python installation. These two invocations are equivalent:

python -m my_module.a.b module_arguments
python python_lib_directory/runpy.py my_module.a.b module_arguments

Use the latter method to setup your Run/Debug Configuration:

Script: python_lib_directory/runpy.py

Script parameters: my_module.a.b module_arguments

Interpreter options: (leave blank, no -m required)

Solution 3 - Python

According to man python, the -m option

> -m module-name
> Searches sys.path for the named module and runs the corresponding .py file as a script.

So most of the time you can just right-click on bar.py in the Project tool window and select Run bar.

If you really need to use the -m option, then specify it as an Interpreter option, with the module name as the Script in the Edit Configurations dialog:

enter image description here

Solution 4 - Python

IntelliJ IDEA / PyCharm 2017

Field "Script" is optional in the recent versions of JetBrains IDEs. Specifying -m foo.bar in "Script parameters" is enough:

enter image description here

Solution 5 - Python

In PyCharm 2016 specifying -m without a script path doesn't work, as they use a wrapper script that doesn't accept the -m argument.

Here's my solution, which works for run & debug configurations: https://github.com/amnong/misc/tree/master/pycharm_runner

Edit: I just read J. R. Petrus's comment, and my solution is very similar. BTW I also tried to support proper entry points using pkg_resources, but for some reason pkg_resources.load_entry_point() could not find my project's distribution...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex FlintView Question on Stackoverflow
Solution 1 - PythonchugreevdView Answer on Stackoverflow
Solution 2 - PythonJ. R. PetrusView Answer on Stackoverflow
Solution 3 - PythonandrewdotnView Answer on Stackoverflow
Solution 4 - PythonAnton TarasenkoView Answer on Stackoverflow
Solution 5 - PythonAmnon GrossmanView Answer on Stackoverflow