Python: How to import a class from a parent directory - python

I am running a python-script that imports a class that I have created. This is the directory order:
Classes
- myClass.py
Scripts
- myScript.py
The first line of myScript.py reads:
from Classes.myClass import myClass
I have also tried:
import sys
sys.path.append('..')
from Classes.myClass import myClass
And I have tried to include an empty __init__.py file to the Classes folder.
With any of these ways, I end up with the error message:
" ModuleNotFoundError: No module named 'Classes' "
Can anyone help me?

From your top level directory
(I'm assuming it's the one containing Classes/ and Scripts/)
run: python3 -m Scripts.myScript
From man python3:
-m module-name
Searches sys.path for the named module and runs the
corresponding .py file as a script.

Related

Exception has occurred: ModuleNotFoundError No module named

I've added one folder into my project called folderb as follows:
mainproject
foldera
__init__.py (empty)
filea.py (module)
folderb
__init__.py (empty)
fileb.py (module)
My project is located under:
/root/Documents/Repositories/mainproject/
Inside filea.py module i want to use module's functions of fileb.py from folderb therefore i import as follows:
from folderb.fileb import myfunctionb
Nevertheless i am getting this:
Exception has occurred: ModuleNotFoundError
No module named 'folderb'
What am i doing wrong?
The issue is set up of sys.path with two different way of execution of the script. Go to mainproject folder. This would work:
python -m foldera.filea
and this would not
python foldera/filea.py
You can see why it is so by adding this to beginning of foldera/filea.py before any other import:
import sys
print(sys.path)
Invocation using the path will add /root/Documents/Repositories/mainproject/foldera to the path where Python interpreter looks for modules. Invocation using the package and module name (with -m option) would add /root/Documents/Repositories/mainproject/.
You can make the path variant working by augmenting the sys.path, either with
PYTHONPATH=. python foldera/filea.py
or by adding this ugly code to the beginning of filea.py:
current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
sys.path.insert(0, parent)
Don't do that, use the first option. More information:
PEP 338 – Executing modules as scripts
Python documentation - Command line and environment, option -m

ModuleNotFoundError: No module named after calling a script from another script

Assume I have the following file structure:
Package/
__init__.py
A.py
B.py
Inside __init__.py I have the following:
__init__.py/
import numpy as np
import pandas as pd
Then I issue the following in the A.py script:
A.py/
from Package import *
However, I receive an error message that no module name Package is defined.
ModuleNotFoundError: No module named Package
I thought from Package import * means running everything in the __init__.py.
I can run the A.py content and use the init import from B.py as I expected.(using from Package import *)
I am using VSCode and Anaconda and my OS is Windows 10.
I can append the project folder every time to my PythonPath using the following commands:
sys.path.append("Path to the Package")
But I do not want to run this piece of code every time.
Can anyone explain what is the problem?
Is this a new problem in Python since I do not recall having such issues in the past?
Because if you run the B.py, the Parent folder of Package folder will be added into the sys.path, be equal to you add sys.path.append("Path to the Package") in the A.py file.
But when you run the A.py, it will add the Package folder instead of the Parent folder of Package folder to the sys.path.
sys.path:
A list of strings that specifies the search path for modules.
Initialized from the environment variable PYTHONPATH, plus an
installation-dependent default.
As initialized upon program startup, the first item of this list,
path[0], is the directory containing the script that was used to
invoke the Python interpreter.
If you are running the python file in debug mode(F5), and the Package folder was the subfolder of your workspace, you can configure the PYTHONPATH in the launch.json file:
"env": {
"PYTHONPATH": "${workspaceFolder}"
},
In your A.py script use just use import file.py and do not use the star. Or, put all your files in a second Package2 directory and use from Package2 import * from your current A.py file.

Python: import from other directory - name is not defined

I looked to several related questions:
Importing python file from other directory
and
how to import module from other directory in python?
but they do not really solve my problems.
So I have
|-1.py
|-my_app
|-a.py
|-b.py
From 1.py I did:
import sys
sys.path.insert (0, './my_app/')
from a import *
and I have the error: name a is not defined.
How could I call the class and functions I defined in a.py and b.py from 1.py?
Many thanks
You need to have an __init__.py file (it can be empty) under the my_app directory for it to be an importable package.

How do I use absolute and relative imports in python 3.6?

I have a python project/library called "slingshot" with the following directory structure:
slingshot/
__init__.py
__main__.py
build.py
deploy.py
util/
__init__.py
prepare_env.py
cdn_api.py
From __main__.py I would like to import functions from util/prepare_env.py.
I would like to ensure that util refers to the util I have in my project, and not some other util library that may be installed somewhere.
I tried from .util import prepare_env but I get an error.
from util import prepare_env seems to work, but doesn't address the ambiguity of "util".
What am I doing wrong?
__main__.py is as follows:
import os
from .util import prepare_env
if __name__ == '__main__':
if 'SLINGSHOT_INITIALIZED' not in os.environ:
prepare_env.pip_install_requirements()
prepare_env.stub_travis()
prepare_env.align_branches()
os.environ['SLINGSHOT_INITIALIZED'] = 'true'
When I type python3 ./slingshot I get the following error:
File "./slingshot/__main__.py", line 2, in <module>
from .util import prepare_env
ImportError: attempted relative import with no known parent package
When I type python3 -m ./slingshot I get the following error:
/usr/local/opt/python3/bin/python3.6: Relative module names not supported
__main__.py modules in a package make the module run as a script when you use the -m command line switch. That switch takes a module name, not a path, so drop the ./ prefix:
python3 -m slingshot
The current working directory is added to the start of the module search path so slingshot is found first, no need to give a relative path specification here.
From the -m switch documentation:
Search sys.path for the named module and execute its contents as the __main__ module.
Since the argument is a module name, you must not give a file extension (.py). The module name should be a valid absolute Python module name[.]
[...]
As with the -c option, the current directory will be added to the start of sys.path.

Executing python script from command line: error with imports

I have written a small script in Python with Eclipse, and it works when executed from Eclipse. But it doesn't work from command line:
>python test.py argument1 argument2
from src import Tests, ImportError: No module named src
The script is stored with the following folders:
ScriptFolder
.input
.report
.src
..test.py
..Tests
...Test1.py
...Test2.py
..TestUtils
...FileUtils.py
And this is the way I'm doing the imports at test.py:
from src import Tests
from TestUtils import FileUtils
About the init.py files, the one which shares folder with test.py is empty, and the one into Tests folder has this content:
import Test1
import Test2
And the init.py file into TestUtils has this content:
import FileUtils
The problem is that, if I change the line from src import Tests to just import Tests I'm getting error in Eclipse: Unresolved imports: Tests. found at src.Tests
How can I make it work for both Eclipse and command line?
sys.path.append(path_to_src_directory)
This will add a path to default paths where python looks for modules.
Since, currently the path to your src directory is not known to python, it gives No module named src error.
Also, your src directory does not seem to have an __init__.py file.

Categories