简体   繁体   中英

Python: how to import custom module

I'm just starting with Python and do have more experience with C#\\Java. So what makes my head hurt is how do I import my Python modules to another custom module? I've already tried couple of things:

SO: Python can't find my module

SO: Cant import my own modules

SO: Import Error: no module named when importing my own module

and several more, but those generally sugget me to use relative imports (using appropriate number of . before import statement). It seems fragile to me because as far as I know imports are relative and resolved depending on where file.py was executed.

So here is my project structure in PyCharm:

Project
├───lib
│    ├───__init__.py
│    ├───pages
│    │   ├───__init__.py
│    │   ├───pageA.py
│    │   └───pageB.py
│    └───actions
│        ├───__init__.py
│        ├───actionA.py
│        └───actionB.py
├───tests
│    ├───__init__.py
│    ├───base_test.py
│    └───search_test.py
└───main.py

In my search_test.py I do import module from lib.actions.actionA import ActionA , in actionA.py I'm importing module like from lib.pages.pageA import PageA . And here is my main.py :

import unittest
from tests.search_test import SearchTest

def create_test_suite():
    test_suite = unittest.TestSuite()
    test_suite.addTest(SearchTest())
    return test_suite


if __name__ == 'main':
    suite = create_test_suite()
    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)

When I run this within PyCharm it works perfectly. But now I need to run it from console:

D:\Projects\Python Projects> python -m unittest project_name.main

and I'm facing ImportError: no module named 'lib' . With this:

D:\Projects\Python Projects\project_name> python main.py

nothing happens.

What can I do? Should I stick to relative pattern or there is some kind of Java-like packages importing?

When you face ImportError this means Python doesn't find your module. So, where does it look for modules?

Probably your PyCharm working directory fits your project. But when you execute it from command line, Python looks for modules in the current directory and in PYTHONPATH env variable. This env variable is translated into a list, which you can check with

import os
print os.sys.path

Make sure your project is in that path, and if not add it's directory to PYTHONPATH env variable. You can check this answer on instruction how to.

Also, you can update the env variable through command line, as explaiend here

我认为应该改为project_name文件夹并在其中运行python -m unittest main ,而不是python -m unittest project_name.main

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