Search code examples
pythonmodulenotfounderror

Wrapper for 'python -m' command


I have a package with following structure:

my_package
 |-- src
 |    |-- __init.py__
 |    |-- __main.py__
 |    |-- foo.py
 |    |-- bar.py
 |-- setup.py

I'm trying to import foo and bar in main.py but it gives ModuleNotFoundError while executing with command python my_package from terminal but runs perfectly fine with the command python -m src from my_package directory. I want to exclude -m flag. All the material I found over the internet points to two things

  • Set package location to sys.path.
  • Set package location to PYTHONPATH variable.

I did these two things but none worked for me so far.

Edit: As suggested in the comments, wrapper is suitable solution for this. But I am unable to figure what logic goes there. Any help would be helpful.


Solution

  • The standard library has a module runpy for this purpose: make a script containing just

    import runpy
    runpy.run_module("my_package",alter_sys=True)
    

    and then running bare python on that file will be equivalent to python -m my_package—including the requirement to set sys.path appropriately, either via PYTHONPATH or by placing the script in the directory containing my_package.