Import .py file from parent directory - python

I wanted to import a file from another folder into another file in the same root folder.
Directory list:
ROOT/
resource/
console_log/
__init__.py (empty)
file1.py
libs/
__init.py__ (empty)
function.py
__init__.py (empty)
I tried using this code in resource/console_log/file1.py:
from resource.libs.function import function_name
It just doesn't work. Returns this error:
No module named 'resource'
If I use this code instead
from ..libs.function import function_name
It gives me this:
attempted relative import with no known parent package
How can I solve?
Is there any way to fix it without using the sys?
EDIT:
I "fixed" the problem by moving all the files directly to the libs folder thus removing the resource folder. Except that if from libs/file1.py I want to import a function present in the main.py file I get the same error
New folder structure:
ROOT/
libs/
__init__.py
file1.py
file2.py
function.py
logs/
debug.log
__init__.py
main.py
If I use this code in the libs/file1.py file, it works correctly (only if I start it from the main.py file)
# file1.py
from libs.function import function_name
But if in libs/file2.py I want to recall a variable present in the main.py file, it returns me an error
# file2.py
from main import data
# ERROR
No module named 'main'
If he doesn't give me this error he gives me another one
attempted relative import with no known parent package

I think your PYTHONPATH isn't set correctly. You can either export it or run your program with it set as expected for the single command. The following will set the PYTHONPATH for the single command execution:
PYTHONPATH=./:$PYTHONPATH python resource/console_log/file1.py

Related

Importing module from different folder using relative path and __init__.py files

I'm on Windows 10, using Python 3.8.3. Here is my simple folder structure:
root_project_folder\
__init__.py # Empty file
project_1_folder\
__init__.py # Empty file
foo.py
project_2_folder\
__init__.py # Empty file
bar.py
Within foo.py I have the following code:
from ..project_2_folder.bar import Test
Test.test_method()
Within bar.py I have the following code:
class Test:
#staticmethod
def test_method():
print("Test successful")
When I run foo.py, I receive the following error:
ImportError: attempted relative import with no known parent package
I've read a few threads about importing using relative paths. Here are the threads for reference:
Python3 relative imports failing in package
Importing files from different folder
What is init.py for?
I did not append any directories to sys.path. I also did not modify PYTHONPATH either, such as adding directories as an environment variable. From what I have read, I don't need to do any of that. Would I have to add something to one of the __init__.py files?
Any help would be appreciated.

Transform a python folder into a package: `ModuleNotFoundError`

Suppose that in a folder my_package, i have three files :
__init__.py, blanck
file1.py, containing a functon function1
file2.py, containing the import statement : from file1 import function1
Then, from another directory, when I use import my_package.file2 as file2, I have a ModuleNotFoundError coming from the line of the statement from file1 import function1.
Obviously, i did something wrong somewhere. But where ? The MWE i gave is small, but i append to have a lot of python files in my_package folder, some of them importing each other. I'm trying to change this directory into a package that i can import from elsewhere, that's why i added the __init__.py blanck file, but it does not seem to work that way.
Check this tree structure.
my_package
|
'----- __init__.py
'----- file1.py
'----- file2.py
Script (somewhere in your system)
|
'--- test.py
when you import my_package (import my_package.file2 as file2) in the another directory say in test.py, it looks for the directory named my_package in its current path.. (i.e. inside Script folder )
as my_package is not present inside the Script folder you will get the error ModuleNotFoundError.
so in test.py write the code as shown below
import sys
sys.path.append("/home/MyFiles/my_package") # absolute path of the my_package folder
import file2
# Now use file2 and work on it
# all other modules/files in my_package folder can also be imported.
I suppose i found the solution myself : I added a setup.py file with propper content to the folder and then i ran pip -m my_package, allowing me to import it from everywhere..

Absolute imports - module not found

I'm trying to organize my scripts in a way I can use absolute imports, without appending to sys.path, making it as easy to use in different computers as possible without problems. I have read and I understand absolute paths are the most appropriate way to do this.
My folder structure looks something like:
main/
__init__.py
tools/
__init__.py
script1.py
base/
__init__.py
script2.py
I have been trying to do from main.tools.script1 import Foo in file main/base/script2.py and I still get the error ImportError: No module named main.tools.script1.
If is print sys.path, the first item is main/base/.
If I run python on a terminal from main, I can import tools.script1, but cannot write main.tools.script1.
I have read other posts, but this is still really not clear for me.
MyNiceProgram-1.0/
setup.py
README
LICENSE
bin/
myniceprogram.py # main entry point
myniceprogram/
__init__.py
tools/
__init__.py
script1.py
base
__init__.py
script2.py
Then you use:
from myniceprogram.tools import script1
from myniceprogram.base import script2
Don't
Name your main package main - it should be treated as a global package so the name should be descriptive. If you want to have a package named main put it inside myniceprogram.main
Execute scripts inside your package. Your main script should be outside the package for absolute import to work. Otherwise you can end up having two copies of the same script, imported absolutely and relatively.

import python file in another directory failed

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.

Import Script from a Parent Directory

How do I import a module(python file) that resides in the parent directory?
Both directories have a __init__.py file in them but I still cannot import a file from the parent directory?
In this folder layout, Script B is attempting to import Script A:
Folder A:
__init__.py
Script A:
Folder B:
__init__.py
Script B(attempting to import Script A)
The following code in Script B doesn't work:
import ../scriptA.py # I get a compile error saying the "." is invalid
You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).
In general it is preferable to use absolute imports rather than relative imports.
toplevel_package/
├── __init__.py
├── moduleA.py
└── subpackage
├── __init__.py
└── moduleB.py
In moduleB:
from toplevel_package import moduleA
If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.
From the docs:
from .. import scriptA
You can do this in packages, but not in scripts you run directly. From the link above:
Note that both explicit and implicit relative imports are based on the
name of the current module. Since the name of the main module is
always "__main__", modules intended for use as the main module of a
Python application should always use absolute imports.
If you create a script that imports A.B.B, you won't receive the ValueError.
If you want to run the script directly, you can:
Add the FolderA's path to the environment variable (PYTHONPATH).
Add the path to sys.path in the your script.
Then:
import module_you_wanted

Categories