简体   繁体   中英

Relative path ImportError when trying to import a shared module from a subdirectory in a script

I am trying to import a util package one directory up from where my code is, but I get an ImportError which I don't understand.

I have a number of different variations on the import syntax in Python, none of which are working.

There are a number of similar questions on Stack Overflow, but none have helped me understand or fix this issue.

Of the top of my head, I have tried the following variations:

import util
import ..util
from .. import util
from ..util import parser
from AdventOfCode2022 import util
from ..AdventOfCode2022 import util
from ...AdventOfCode2022 import util

Most of these I guessed wouldn't work, but I tried them anyway to be sure.

Error message:

ImportError: attempted relative import with no known parent package

Directory structure:

.
├── day03
│   ├── input.txt
│   ├── part1.py
│   ├── part2.py
│   └── test_input.txt
└── util
    ├── __init__.py
    └── parser.py

I just want to import my util package from any "day0*/" directory - not sure why Python makes it so hard!

Two options:

  1. Add the full path to ./util/ to your PYTHONPATH environment variable.

For example on Bash, your ~/.bashrc might have export PYTHONPATH="${PYTHONPATH}:/Users/foobar/projects/advent-of-code/util/" .

  1. Add sys.path.append('/path/to/application/app/folder') before the import.

The other solutions don't work because:

  1. day03 and the parent directory are not modules with their own __init__.py . Lines like from..util import parser only work if everything involved is a module.
  2. You are presumably running the code from within ./day03/ .

View this as 'I have a bunch of independent Python projects ( day01 , day02 etc) that all want to share a common piece of code I have living in a different project ( util ) that lives somewhere else on my computer.'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM