Calling functions from packages

I’m trying to access functions from run_perf.py in addMetrics.py by including this import statement

from analysis import run_perf
...
runtime = run_perf.calcMs()

I keep getting ModuleNotFoundError: No module named ‘analysis’ but don’t know what about my import is wrong.

File Structure:

appName/
│
├── bin/
│
├── appName/
│   ├── __init__.py
│   ├── runner.py
│   ├── analysis/
│   │   ├── __init__.py
│   │   ├── run_perf.py
│   │   └── mem_perf.py
│   │
│   └── conversion/
│       ├── __init__.py
│       ├── convert.py
│       └── addMetrics.py
│
├── .gitignore
├── LICENSE
└── README.md

Note

  • My __init__.py files are empty at the moment

  • import analysis.run_perf results in same error

  • from appName.analysis import run_perf results in same error

I’m trying to access functions from run_perf.py in addMetrics.py by
including this import statement

from analysis import run_perf
...
runtime = run_perf.calcMs()

I keep getting ModuleNotFoundError: No module named ‘analysis’ but don’t know what about my import is wrong.

That means that Python can’t fine the “analysis” package. Python looks
in sys.path:

from sys import path
print(repr(path))


/Users/cameron/lib/python:/Users/cameron/rc/python

which contains my personal code and tabhistory for interactive python
use.

based on your file tree:

File Structure:

appName/
├── bin/
├── appName/
│   ├── __init__.py
│   ├── runner.py
│   ├── analysis/
│   │   ├── __init__.py
│   │   ├── run_perf.py
│   │   └── mem_perf.py
│   └── conversion/

[…]

You need to include /path/to/appName/appName in your $PYTHONPATH.

For testing purposes, do that by hand< example:

export PYTHONPATH=/path/to/appName/appName

For an appplication tree like the above, as installed, one typical
approach would be to have the executable in appName/bin be a small
wrapper script which figured that out from its own path, set
$PYTHONPATH, then executed Python on your real Python main programme. Or
alternatively to have the installation process wire the required path
into the wrapper script to avoid having it guess.

Cheers,
Cameron Simpson cs@cskk.id.au

1 Like

Worked like a charm!

Thank you for such a thoughtful response Cameron.

Best,
Cole

That is a very verbose response above (sorry), but it is likely you do not have any Python package named ‘analysis’ in your Python installation. Use pip to install it, or maybe download from PyPi, and install it.