Python: ModuleNotFoundError: No module named '' - python

I am running python code in docker.
I have the following file structure:
-my_dir
-test.py
-bird.py
-string_int_label_map_pb2.py
-inference.py
inference.py:
import test
import bird
from string_int_label_map_pb2 import StringIntLabelMap
test.py and bird.py both contain this code:
print('hello world!')
def this_is_test():
return 'hi'
In inference.py 'import test' throws no error(but 'hello world!' is never printed).
'import bird' throws: ModuleNotFoundError: No module named 'bird'. Finally
'import string_int_label_map_pb2 ' throws: ModuleNotFoundError: No module named 'string_int_label_map_pb2 '
Note: bird.py and test.py are not simultaneously existing in the dir, they are depticted as such only to make my point. They exist only when I rename the same file to either name to test if the name itself was to blame.

If one or the other is not in the folder but you still have import test and import bird in the inference.py, that's your issue. Python is trying to import both files but can not find the file.

I added bird.py to /worker/ (the WORKDIR path configured in the dockerfile) and sure enough "Hello world!" printed.
So the issue was that inference.py was not searching its parent dir for imports as I thought, but rather the path configured in WORKDIR.
Still don't understand why import test gave no errors since there was never a test.py file in /worker/.

I also had this problem, how did I solve the problem?
For example.
My directory:
--Application
---hooks
----init.py
----helpers.py
---model
----init.py
----model_person.py
In script model_person.py
import sys
sys.path.append('../')
from hooks.helpers import *
Thats all

Related

Why do my imports work in pycharm, but not on the command line?

I have the following folder layout:
my_folder/
my_subfolder/
__init__.py
main.py
import_1.py
import_2.py
With files:
# main.py
from my_subfolder import import_1
import_1.call_import_2(3)
And
# import_1.py
from my_subfolder import import_2
def call_import_2(n):
import_2.print_hello_world_n_times(n)
And
# import_2.py
def print_hello_world_n_times(n):
for i in range(n):
print('hello world')
Now the thing is, if I run main.py in pycharm, it works fine. However, if I run it from the command line python my_subfolder/main.py or python main.py (depending which folder I am in), it doesn't work! The git bash also cannot get it to work. I get the error:
ModuleNotFoundError no module named 'my_subfolder'
Does anyone know what causes this discrepancy between pycharm and the command line?
# main.py
from . import import_1
import_1.call_import_2(3)
and
# import_1.py
from . import import_2
def call_import_2(n):
import_2.print_hello_world_n_times(n)
You're already in my_subfolder so it looks for another one inside of that.

No module found error when I have added the path

I have a project structure that looks like:
The file greet.py is given as:
def greet_morning(message):
print("Hello, {}", message)
def greet_evening(message):
print("Evening message: {}", message)
and the file msg.py is given as :
import sys
import os
sys.path.append(os.getcwd())
from greet.greet import greet_morning
greet_morning("heyy")
When I try to run msg.py as python message/msg.py, I get an error saying ImportError: No module named greet.greet. I am running this file from the root. Why do I get this error, when I have already added the cwd in the system path?
I think is
from untitled.greet.greet import greet_morning
if still doesnt work, add:
import sys
sys.path.append('../')
edit
I think you may find all the possible solutions here Importing files from different folder
add __init__.py inside greet and msg folder__init__.py
You have missed the file __init__.py in your module.
Just create an empty file __init__.py in greet folder.

ImportError on Python

I'm new to python and I'm having this problem that I can't figure it out.
My file structure is:
enter image description here
On Criador.py I have several functions, for example:
def doSomething():
pass
def doSomethingElse():
pass
and Im trying to use one of this functions on the Controller.py file:
The first thing I did was, on the Controller.py:
import Controller.Criador
and then tried to use that function as:
Controller.Criador.doSomething()
After running Controller.py, I got this error:
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
I tried several other things, like:
from . import Criador
or
from Controller.Criador import doSomething
or
from Controller import Criador
and nothing helped, just changed the errors to:
ImportError: cannot import name 'Criador'
and
ModuleNotFoundError: No module named 'Controller.Criador'; 'Controller' is not a package
and
ImportError: cannot import name 'Criador'
Can someone give me a light about this? I'm using PyCharm and it does not give me any error when I declare the imports, only when I run the file
If Controller.py and Criador.py are in the same folder, you can do this inside Controller.py:
import Criador
Criador.doSomething()

Attempted relative import beyond toplevel package

Here is my folder structure:
Mopy/ # no init.py !
bash/
__init__.py
bash.py # <--- Edit: yep there is such a module too
bass.py
bosh/
__init__.py # contains from .. import bass
bsa_files.py
...
test_bash\
__init__.py # code below
test_bosh\
__init__.py
test_bsa_files.py
In test_bash\__init__.py I have:
import sys
from os.path import dirname, abspath, join, sep
mopy = dirname(dirname(abspath(__file__)))
assert mopy.split(sep)[-1].lower() == 'mopy'
sys.path.append(mopy)
print 'Mopy folder appended to path: ', mopy
while in test_bsa_files.py:
import unittest
from unittest import TestCase
import bosh
class TestBSAHeader(TestCase):
def test_read_header(self):
bosh.bsa_files.Header.read_header()
if __name__ == '__main__':
unittest.main()
Now when I issue:
python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\path\to\Mopy\test_bash\test_bosh\test_bsa_files.py true
I get:
Traceback (most recent call last):
File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 124, in <module>
modules = [loadSource(a[0])]
File "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py", line 43, in loadSource
module = imp.load_source(moduleName, fileName)
File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py", line 4, in <module>
import bosh
File "C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\bash\bosh\__init__.py", line 50, in <module>
from .. import bass
ValueError: Attempted relative import beyond toplevel package
Since 'Mopy" is in the sys.path and bosh\__init__.py is correctly resolved why it complains about relative import above the top level package ? Which is the top level package ?
Incidentally this is my attempt to add tests to a legacy project - had asked in Python test package layout but was closed as a duplicate of Where do the Python unit tests go?. Comments on my current test package layout are much appreciated !
Well the answer below does not work in my case:
The module bash.py is the entry point to the application containing:
if __name__ == '__main__':
main()
When I use import bash.bosh or from bash import bosh I get:
C:\_\Python27\python.exe "C:\_\JetBrains\PyCharm 2016.2.2\helpers\pycharm\utrunner.py" C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true
Testing started at 3:45 PM ...
usage: utrunner.py [-h] [-o OBLIVIONPATH] [-p PERSONALPATH] [-u USERPATH]
[-l LOCALAPPDATAPATH] [-b] [-r] [-f FILENAME] [-q] [-i]
[-I] [-g GAMENAME] [-d] [-C] [-P] [--no-uac] [--uac]
[--bashmon] [-L LANGUAGE]
utrunner.py: error: unrecognized arguments: C:\Dropbox\eclipse_workspaces\python\wrye-bash\Mopy\test_bash\test_bosh\test_bsa_files.py true
Process finished with exit code 2
This usage message is from the main() in bash.
TLDR: Do
import bash.bosh
or
from bash import bosh
Avoid modifying sys.path, as this duplicates modules.
When you do
import bosh
it will import the module bosh. This means Mopy/bash is in your sys.path, python finds the file bosh there, and imports it. The module is now globally known by the name bosh. Whether bosh is itself a module or package doesn't matter for this, it only changes whether bosh.py or bosh/__init__.py is used.
Now, when bosh tries to do
from .. import bass
this is not a file system operation ("one directory up, file bass") but a module name operation. It means "one package level up, module bass". bosh wasn't imported from its package, but on its own, though. So going up one package is not possible - you end up at the package '', which is not valid.
Let's look at what happens when you do
import bash.bosh
instead. First, the package bash is imported. Then, bosh is imported as a module of that package - it is globally know as bash.bosh, even if you used from bash import bosh.
When bosh does
from .. import bass
that one works now: going one level up from bash.bosh gets you to bash. From there, bass is imported as bash.bass.
No need to hack or research the importing of the sibling module.
Simply go to your project directory and import the module. If project directory is not a package, add init.py to make it a project directory.
# File name ProjectDir/sibling1/main.py
import ProjectDir.sibling2
if __name__=='__main__':
md = sibling2.module()

Python ImportLib 'No Module Named'

I'm trying to use a variable as a module to import from in Python.
Using ImportLib I have been successfully able to find the test...
sys.path.insert(0, sys.path[0] + '\\tests')
tool_name = selected_tool.split(".")[0]
selected_module = importlib.import_module("script1")
print(selected_module)
... and by printing the select_module I can see that it succesfully finds the script:
<module 'script1' from 'C:\\Users\\.....">
However, when I try to use this variable in the code to import a module from it:
from selected_module import run
run(1337)
The program quits with the following error:
ImportError: No module named 'selected_module'
I have tried to add a init.py file to the main directory and the /test directory where the scripts are, but to no avail. I'm sure it's just something stupidly small I'm missing - does anyone know?
Import statements are not sensitive to variables! Their content are treated as literals
An example:
urllib = "foo"
from urllib import parse # loads "urllib.parse", not "foo.parse"
print(parse)
Note that from my_module import my_func will simply bind my_module.my_func to the local name my_func. If you have already imported the module via importlib.import_module, you can just do this yourself:
# ... your code here
run = selected_module.run # bind module function to local name

Categories