I have a main.py file in the folder project and read.py in the folder ./project/utils. In the main.py, I called
import sys, os
sys.path.append('./utils/')
from utils.read import function1
However, when I use the python main.py command, I got the error
ImportError: No module named utils.read. What should I change? Thanks all
i think you need to add __init__.py
in your directory..
make sure you have __init__.py in utils folder.. then only python will understand it is package folder contains py
__init__.py specifies that the folder is actually a package. a package in python is a directory containing .py files (modules). In every folder which is a package (that is, a folder containing multiple .py files) you should define __init__.py.
It can be empty, or you can put some statements to execute when the package is imported (or modules from the package).
For exmaple, let's take this directory tree:
/dev/package/greeter.py
and current working directory is /dev.
>>> from package import greeter
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
from package import greeter
ImportError: No module named package
import pakcage results in the same error. When adding __init__.py into the package folder, it works. My init is simple as
print 'init executed'
>>> from package import greeter
init executed
>>>
One common functionality to put in __init__.py is the __all__ variable. You can read more about it here Can someone explain __all__ in Python?
Related
I have the following file/folder structure:
testpackage (folder)
src (folder)
__init__.py
module1.py
tests
__init__.py
test_module1.py
just for clearance: the "module1.py" is under the "src" folder which is under the "testpakcage" folder.
"tests" is also under the "testpakcage" folder - same level as the "src" one.
module1.py has a class named "class1" as so:
class class1:
def method1 (self):
print('i am method1')
in test_module1.py I want to run tests on the above module. this is it's contents:
import unittest
from testpackage.src import module1
t = module1.class1()
t.method1()
this package is not installed, and I don't instead to install or submit it anywereh, I'm just trying to find the best structuring practice for me, for future packaging creation.
problem is: when I run the following either from the "tests" or "testpackage" folder:
/usr/bin/python3.6 -m unittest discover
I get the following error:
E
======================================================================
ERROR: test_module1 (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_module1
Traceback (most recent call last):
File "/usr/lib64/python3.6/unittest/loader.py", line 428, in _find_test_path
module = self._get_module_from_name(name)
File "/usr/lib64/python3.6/unittest/loader.py", line 369, in _get_module_from_name
__import__(name)
something similar also happens when I just try to run "test_module1.py" from the "tests" folder:
Traceback (most recent call last):
File "test_module1.py", line 5, in <module>
from testpackage.src import *
ModuleNotFoundError: No module named 'testpackage'
so I tried changing the "import" line with a few alternatives but none of them work. each one of those was a different attempt (not all of them at once):
from testpackage.src import *
import testpackage.src.module1 as module1
import ..src.module1
from ..src.module1 import class1
searching stackoverflow I found solutions that worked for some but not for those using python 3 and above - which is my case.
any suggestions? I think what I'm trying to do is rather simple and I'm missing something really basic here.
I'm using python3.6 by way
I'm wondering if you saw different errors for some of those different import attempts you made. Not sure if this will solve your problem, but this is one way it would generally be accomplished.
First, I am not sure what the top level of your package is supposed to be. Do you reference testpackage in any of the code in the src folder? If so, that top folder should also contain an __init__.py file.
Now, at the very top of your test_module1.py file, add:
import sys
pkg_dir = ".." # if "src" if the top level folder else "..." if testpackage is the top level folder
sys.path.append(pkg_dir)
Note you must change pkg_dir depending on your module's structure.(which I cannot tell from your question).
What this code does is add the folder containing the top level folder of your package to the python import search tree. This can solve problems that the relative import in your example file will not: if the files in your module use module-level imports (e.g. import testpackage.src.module2 in module1.py). This is common in packages with multiple submodules that cross-import.
I am playing around with the AIMA python project, but I'm having trouble with importing the logic.py file into main.py. The following is folder structure:
project/
aima/
__init__.py
utils.py
logic.py
main.py
I added the folder to my python path variable. Every time I do
# main.py
import aima.logic as logic
I get this error:
File "main.py", line 2, in
import aima.logic as logic
File "/project/aima/logic.py", line 34, in
from utils import (
ImportError: No module named 'utils'
I thought this was strange since logic.py imports the utils file it should be fine since they are under the same directory.
I tried searching for answers, but most of them mention adding to python module search path and adding __init__.py and do not work for me.
Trying this may be good
from project.aima import logic
I met a very strange problem:
My file structure is like: (core and test are directories)
core
----file1.py
----__init__.py
test
----file2.py
in file2, i wrote:
from core import file1
result is:
ImportError: cannot import name file1
Have to create __init__.py file inside the test dir:
Because The __init__.py files are required to make Python treat the directories as containing packages.
parent/
child1/
__init__.py
file1.py
child2/
__init__.py
file2.py
From the error:
If run the child2/file2.py file directly. You are not able to access child1/file1.py from the child2/file2.py
Because only from the parent directory can access the child.
If have a folder structure like:
parent/
child1/
__init__.py
file1.py
child2/
__init__.py
file2.py
file3.py
If we run the file3.py file. Can able to access both child1/file1.py, child2/file2.py in file3.py
Because It is running from the parent directory.
If we need to access child1/file1 from child2/file2.py, We need to set the parent directory:
By running this below command we can achieve it...
PYTHONPATH=. python child2/file2.py
PYTHONPATH=. It refers the parent path. Then runs child2/file2.py file from the shell
It's not a strange problem, imports simply don't work like that.
From the official documentation: https://docs.python.org/3/tutorial/modules.html
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
The directory containing the input script (or the current directory when
no file is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell
variable PATH).
The installation-dependent default.
You could look into relative imports, here's a good source: https://stackoverflow.com/a/16985066/4886716
The relevant info from that post is that there's no good way to do it unless you add core to PYTHONPATH like Shawn. L says.
When I tried your case, I got
Traceback (most recent call last):
File "file2.py", line 3, in <module>
from core import file1
ImportError: No module named core
The reason is that Python does not find core. In this case, you need to add core to the system path, as shown below (add them at the very beginning of file2.py):
import sys,os
sys.path.append(path_to_core.py)
Or, if you would run it using command line, you could simply put the following at the beginning of file2.py
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__),'../'))
Here, os.path.join(os.path.dirname(__file__),'../') is to state the path to file2.py.
I get the following error while running some python code
Traceback (most recent call last):
File "./dspl.py", line 4, in
import base
ImportError: No module named base
The disp.py is in directory PERSISTENCE_LENGTH, as listed below. The disp.py imports few python scripts that are inside the directory UTILS (shown below). I added the path of imported directory (/home/vinay/oxDNA) to PYTHONPATH i.e.,export PYTHONPATH=${PYTHONPATH}:/home/vinay/oxDNA/). There is a proper__init__.py file inside the UTILS directory.
disp.py is in the directory: /home/vinay/oxDNA/EXAMPLES/PERSISTENCE_LENGTH
disp.py is importing other modules that are in the directory: /home/vinay/oxDNA/UTILS
When I print sys.path, I can see that PYTHONPATH is okay. as shown below
['', '/home/vinay', '/home/vinay/oxDNA/UTILS', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-linux2', )
If your module is in a directory, rather than being a singled named file, then the directory is required to have a __init__.py file. The existence of this file makes the directory a module and then you can load from that module, the __init__.py can be empty but you can also have an entry in it of:
__all__ = ['component_name1', 'etc', 'etc']
If you do then the names listed in __all__ are those that will be available after a from mondule_name import *
The normal practice is to have a meaningful name for the directory, e.g.: `my_utils' and for the components within the directory, e.g.: 'file_io.py' and you can then access the items within file_io as:
import my_utils
my_utils.file_io.functionA()
or
from my_utils import file_io
file_io.functionA()
or
from my_utils.file_io import functionA()
functionA()
Note that in the all above examples functionA has access to other functions within file_io.py and, if file_io.py has the appropriate imports, to other functions in other files in my_utils.
It is also important to remember that python is case dependent even on windows.
I created a package, for the ease of use I call it packageA.
In this package I have 4 submodules in (separate files) and an init file, so the package contains the following files:
__init__.py
moduleA.py
moduleB.py
moduleC.py
moduleD.py
Module B-D stand alone, they don't import any other local module. Module A imports module B-D.
Now I have a script that wants to import packageA, the init.py is empty so far.
import packageA
works without problems. But moduleA is not available from this import. If I want to use it via packageA.moduleA it raises this error:
AttributeError: 'module' object has no attribute
The following also works without problems:
from packageA import moduleB
from packageA import moduleC
from packageA import moduleD
And the next import causes the ImportError:
from packageA import moduleA
raises this Error:
Traceback (most recent call last):
File "run.py", line 19, in <module>
from packageA import moduleA
ImportError: cannot import name moduleA
I thought that maybe I'm doing sth wrong in moduleA, but even if moduleA is empty the import raises the same error. It seems like that this module can't be imported somehow. How is this possible?
I have separete unit test files for all python modules, and yes, moduleA is working correctly without any errors.
Perhaps you are importing a different version of the package from a different location. Try this in your script to make sure it is the right one -- it should print the full path of the __init__.py file.
import packageA
print packageA.__file__
Also, check if the package's module search path has been altered. Normally this is a list that contains one element, the directory path of the package:
print packageA.__path__