简体   繁体   中英

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)

Use PYTHONPATH . For example

PYTHONPATH=. python tests/unitTests/test_stringUtils.py

or

PYTHONPATH=.. python unitTests/test_stringUtils.py

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