Environment:
Python 3.7.2
macOS
- Import sub1 normally from main.py
Currently, I am writing a python3 program with the following directory structure and source code.
├── main.py
└── modules
├── sub1.py
└── sub2.py
# main.py
from modules import sub1
if __name__ == '__main__':
sub1.sub1_func ()
# modules/sub1.py
import sub2
def sub1_func ():
sub2.sub2_func ()
if __name__ == '__main__':
sub1_func ()
# modules/sub2.py
def sub2_func ():
print ('sub2')
is
main.py imports sub1.py and uses sub1_func () in sub1,
sub1_func () refers to sub2.py sub2_func () in the same directory as sub1.py.
If i run main.py at this time,ModuleNotFoundError: No module named 'sub2'
will appear.
Therefore, considering the thing seen from main.py, the sub1.py import statement was changed fromimport sub2
tofrom modules import sub2
The correct operation as expected was confirmed. ("Sub2" is output)
However, when sub1.py is executed in this state,ModuleNotFoundError: No module named 'modules'
will appear.
sub1 is going to be referenced from other modules, so is there any way to import sub1 normally from main.py with import of sub1 asimport sub2
? .
In the first place, isn't it very good to have such a file structure?
If i am familiar with python, would you please teach me?
-
Answer # 1
-
Answer # 2
The python import is referenced relative to the path when it is executed.
To reference relative to the location of the file instead of the runtime pathimport .foo
Like, you need to write explicitly.
Related articles
- i don't know how to import multiple csv files into mongodb with python
- (python) i want to convert multiple json files with different columns into one csv format
- python - i want to put multiple jsonl files in a dataframe at once
- python - read multiple audio files (wav files)
- python - read only the maximum value from multiple csv files and combine them into one file
- python - i can't send multiple images with the line api
- python - cannot inherit a class with multiple arguments
- python multiple regression analysis statsmodelsformula
- bash - output cron results to multiple files (one is standard error only)
- python - i want to handle files with the path obtained by ospathjoin
- python - how to load multiple time formats with pandas
- python 3x - multiple outputs from a list of tuples
- emacs - (python) i want to automate the work of reading files in order
- python google drive api 100mb or more files cannot be uploaded
- i want to perform multiple processes with else in python list comprehension notation
- python - about multiple processing and loop processing in discordpy
- processing python dat files
- eliminating pandas install and import in python pyenv export ldflags
- python - import the original csv dataset
- python - randomly extract data from multiple data frames (no between data frames is the same)
Rewrite import of
sub1.py
.Relative import