Importing error in python using eclipse - python

I have two files one is:
file1.py that is located at myapp/file1.py
file2.py at test/file2.py
I want to use the function of file2.py in file1.py
How can i import file2.py to file1.py?
I tried to: from test.file2 import file2 it compiles but when i run it i got an error from the debug: Import Error no module named file2
What is the right way to do this?

By Default, Python searches in the project directory and hence the files from other directories cannot be imported as we do for the files available locally in the project folder.
But to accomplish that we might want to amend the system path which can be done in the following way.
import sys
sys.path.insert(1, '/path/to/your/filefolder/')
#also sys.path.append(0,/'path/to/your/filefolder/[file])
import [your file]
Hope this can help :)

Related

Getting a ModuleNotFoundError when trying to import from a particular module

The directory I have looks like this:
repository
/src
/main.py
/a.py
/b.py
/c.py
I run my program via python ./main.py and within main.py there's an important statement from a import some_func. I'm getting a ModuleNotFoundError: No module named 'a' every time I run the program.
I've tried running the Python shell and running the commands import b or import c and those work without any errors. There's nothing particularly special about a either, it just contains a few functions.
What's the problem and how can I fix this issue?
repository/
__init__.py
/src
__init__.py
main.py
a.py
b.py
c.py
In the __init__.py in repository, add the following line:
from . import repository
In the __init__.py in src, add the following line:
from . import main
from . import a
from . import b
from . import c
Now from src.a import your_func is going to work on main.py
Maybe you could try using a relative import, which allows you to import modules from other directories relative to the location of the current file.
Note that you will need to add a dot (.) before the module name when using a relative import, this indicates that the module is in the same directory as the current file:
from . import a
Or try running it from a different directory and appending the /src path like this:
import sys
sys.path.append('/src')
You could also try using the PYTHONPATH (environment variable) to add a directory to the search path:
Open your terminal and navigate to the directory containing the main.py file (/src).
Set the PYTHONPATH environment variable to include the current directory, by running the following command
export PYTHONPATH=$PYTHONPATH:$(pwd)
At last you could try to use the -m flag inside your command, so that Python knows to look for the a module inside the /src directory:
python -m src.main
I've had similar problems in the past. Imports in Python depend on a lot of things like how you run your program, as a script or as a module and what is your current working directory.
Thus I've created a new import library: ultraimport It gives the programmer more control over imports and lets you do file system based, relative imports.
Your main.py could look like this:
import ultraimport
a = ultraimport('__dir__/a.py')
This will always work, no matter how you run your code, no matter what is your sys.path and also no init files are necessary.

How to import Python Class or Function from parent directory?

I have this project structure,
.\src
.\api
test.py
.\config
config.py
app.py
when i'm trying to import a function or class from test.py inside config.py, using this statement
from src.api.test import tes_func
I get this error
ModuleNotFoundError: No module named 'src.api'
if i use these 2 lines i can import using
from api.test import tes_func.
import sys
sys.path.append("../")
why it's not working when use from src.api.test import test_func
Is there a way to import python files without sys.path.append("../").
Thanks in advance.
You need to change the working directory.
Before python was only able to see other files inside the config folder.
If you run your program from a common parent directory python is able to see both folders and there files.
..\PycharmProjects\pythonProject> python -m src.config.config
My folder structure:
With this command src is now your root directory meaning in config.py you will need to import the function like this:
from src.api.test import tes_func

Visual Studio Code Project Importing from Wrong Directory

I have the below directory structure. In my test2.py file, I am importing resource.py. It is however referencing resource.py from Folder1 instead of Folder2. Can someone explain to me what is happening, and/or how I can import from the correct directory?
-Folder1 (Original folder)
--resource.py
--Folder
---test1.py
-Folder2 (Copied from folder 1)
--resource.py (modified global variable values)
--Folder
---test2.py
Update: I was able to workaround my problem by adding the below snippet of code. Any additional suggestions are welcome, so I don't need to apply this code to each .py file in Folder2 that needs resource.py
import sys
sys.path.remove('path\\to\\not\\wanted\\directory')
sys.path.add('path\\to\\wanted\\import\\source')
After Python: Clear Internal Extension Cache from Command Palette, specify the clear path about importing the module with the following code:
import sys
sys.path.append("./")
import folder2.resource as f2r
See result:

Basic Python import mechanics

I have the following directory tree:
project/
A/
__init__.py
foo.py
TestA/
__init__.py
testFoo.py
the content of testFoo is:
import unittest
from A import foo
from the project directory I run python testA/testFoo.py
I get a ModuleNotFoundError No module named A
I have two question: how to improt and run A.foo from TestA.testFoo and why is it so difficult to grasp the import logic in Python? Isn't there any debug trick to solve this kind of issues rapidly, I'm sorry I have to bother you with such basics questions?
When your are executing a file an environment variable called python path is generated, python import work with this variable to find your file to import, this path is generated with the path of the file you are executing and it will search in the current directory and sub directories containing an __init__.py file, if you want to import from a directory on the same level you need to modify your python path or change the architecture of your project so the file executed is always on top level.
you can include path to your python path like this :
import sys
sys.path.insert(0, "/path/to/file.py")
You can read more on import system : https://docs.python.org/3/reference/import.html
The best way in my opinion is to not touch the python path and include your test directoy into the directory where tested files are:
project/
A/
__init__.py
foo.py
TestA/
__init__.py
testFoo.py
Then run the python -m unittest command into your A or project directory, it will search into your current and sub directories for test and execute it.
More on unittest here : https://docs.python.org/3/library/unittest.html
Add the folder project/testA to the system pythonpath first:
import sys
sys.path.insert(0, "/path/to/pythonfile")
and try the import again.
Can you try this ?
Create an empty file __init__.py in subdirectory TestA. And add at the begin of main code
from __future__ import absolute_import
Then import as below :
import A.foo as testfoo
The recommended way in py3 may be like below
echo $pwd
$ /home/user/project
python -m testA.testFoo
The way of execute module python -m in python is a good way to replace relative references。
You definitely cannot find A because python need look from sys.path, PYTHONPATH to find the module.
And python will automatically add current top level script to sys.path not currently directory to sys.path. So if you add print(sys.path) in testFoo.py, you will see it only add project/TestA to the sys.path.
Another word, the project did not be included in sys.path, then how python can find the module A?
So you had to add the project folder to sys.path by yourself, and, this just needed in top script, something like follows:
import unittest
import sys
import os
file_path = os.path.abspath(os.path.dirname(__file__)).replace('\\', '/')
lib_path = os.path.abspath(os.path.join(file_path, '..')).replace('\\', '/')
sys.path.append(lib_path)

Path appended but python does not find module

I have the following structure:
~/git/
~/git/folder1
~/git/folder2
in ~/git/folder1 I have main.py, which imports doing the following:
import folder2.future_data as future_data
which throws the following error:
import folder2.future_data as f_d
ImportError: No module named folder2.future_data
Despite my $PATH containing
user#mac-upload:~$ echo $PATH
/home/user/anaconda2/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/home/user/git/folder2
Why am I unable to import from folder2 despite it being in my path?
Am I missing something?
Try putting an empty __init__.py file in each directory (~/git, ~/git/folder1, and ~/git/folder2). Then do export PYTHONPATH=${HOME}/git:$PYTHONPATH (assuming bash shell).
This will also allow you to just set your PYTHONPATH once at the top level and be done with it. If you add more directories (modules) that you need to import, you can just keep adding __init__.py files to your structure (instead of having to constantly modify your PYTHONPATH every time your file/directory structure changes).
You can explicitly added the path inside the main.py script before you doing import
import sys
sys.path.append(r'~/git/folder2')
import future_data

Categories

Resources