Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

relative paths for modules in python

I've attempted a few different techniques trying to do something that to me seems doable but I guess I am missing some gotchas about python (using 2.7 but would like this to work also for 3.* if possible).

I am not sure about terminology like package or module, but to me the following seems quite a "simple" doable scenario.

This is the directory structure:

.
├── job
│  └── the_script.py
└── modules
  ├── __init__.py
  └── print_module.py

The content of the_script.py:

# this does not work
import importlib
print_module = importlib.import_module('.print_module', '..modules')
# this also does not work
from ..modules import print_module
print_module.do_stuff()

The content of print_module:

def do_stuff():
 print("This should be in stdout")

I would like to run all this "relative paths" stuff as:

/job$ python2 the_script.py

But the importlib.import_module gives various errors:

  • if I just use 1 input parameter ..modules.print_module, then I get: TypeError("relative imports require the 'package' argument")
  • if I use 2 input parameters (as in the example above), then I get: ValueError: Empty module name

On the other hand using the from ..modules syntax I get: ValueError: Attempted relative import in non-package.

I think the __init__.py empty file should be enough to qualify that code as "packages" (or modules? not sure about the terminology), but it seems there's something I am missing about how to manage relative paths.

I read that in the past people was hacking this using the path and other functions from import os and import sys, but according to the official docs (python 2.7 and 3.*) this should not be needed anymore.

What am I doing wrong and how could I achieve the result of printing the content modules/print_module.do_stuff calling it from a script in the "relative directory" job/?

Answer*

Draft saved
Draft discarded
Cancel
2
  • Thanks for pointing out the docs :) but this gives: ImportError: No module named modules.print_module Commented Mar 19, 2017 at 22:16
  • 1
    In python 2 this gives AttributeError: 'module' object has no attribute 'append', however if I put instead sys.path.append('..'), then this gives ImportError: No module named modules.print_module. In python 3 it gives similar error messages. Commented Mar 20, 2017 at 19:54

lang-py

AltStyle によって変換されたページ (->オリジナル) /