Itération 122442
Itération 122442

Reputation: 2962

How to import a python class from a file in a different folder?

I have the following file structure:

├───common
│       hdfs.py
│       impala.py
│       pandasUtils.py
│       proxy.py
│       stringUtils.py
│       __init__.py
│
├───tests
│   └───unitTests
│           test_stringUtils.py
│           __init__.py

From tests/unitTests/test_stringUtils.py, I want to import the file common/stringUtils.py

I tried the following:

import unittest
from common.stringUtils import StringUtils

But I have the following error: Unable to import 'common.stringUtils'.

Is there a way to import a file without dealing with sys path or doing anything different from "import from" ?(30 years and still looks like an early access game)

Upvotes: 2

Views: 77

Answers (1)

ghchoi
ghchoi

Reputation: 5156

Use PYTHONPATH. For example

PYTHONPATH=. python tests/unitTests/test_stringUtils.py

or

PYTHONPATH=.. python unitTests/test_stringUtils.py

Upvotes: 2

Related Questions