I have a problem. I created a script that uses a few functions, but now I have moved those functions in a folder named: include. The file is called: mylib.py, but when I use the following code:
import sys
sys.path.insert(0, 'include/')
import mylib
It gives an error: No module named 'mylib'. The main code is in the windows directory: Desktop/Python/ and the include file in: Desktop/Python/include/.
What am I doing wrong?
add an empty file __init__.py to the include folder to make it a package.
then import from it with:
from include import mylib
Replace the second line with this one:
sys.path.insert(0, '/Desktop/Python/include')
Related
I have a python project a folder structure like this:
main_directory
main.py
drivers
__init__.py
xyz.py
utils
__init__.py
connect.py
I want to import connect.py into xyz.py and here's my code:
from utils import connect as dc
But I keep getting this error no matter what I do, please help:
ModuleNotFoundError: No module named 'utils'
Update: People are telling me to set the path or directory, I don't understand why I need to do this only for importing file. This is something that should work automatically.
In your utils folder __init__.py should be blank. If this doesn't work, try adding from __future__ import absolute_import in your xyz.py file.
Check your current directory. It must be main_directory.
import os
print("Current working directory is: ", os.getcwd()
if not, you can change using
os.chdir("path/to/main_directory")
also works with relative path
os.chdir('..')
I was also facing same problem when you use row python script so i use the following code at the beginning of the file
import os
import sys
current_dir = os.path.dirname(os.path.realpath(__file__))
parent_dir = os.path.dirname(current_dir)
sys.path.append(parent_dir)
This way it will search the require file at parent directory.
Hope this will work for you also..
You could move your utils folder into drivers, making the path to the to-be imported file a subdirectory of your executing file, like:
main_directory/drivers/utils/connect.py
Alternatively, you could try
from ..utils import connect as dc
This will move up a directory before import.
Lasty, you could add the directory to Path in your script via
import sys
sys.path.insert(0,'/path/to/mod_directory')
For this method, see also this question
I wanted to make a cmd tool. I created two files, one named main.py, and the other named version.py
there are in the same directory
version.py:
import os
def pyVersion():
os.system("python --version")
main.py:
import version
version.pyVersion()
I think it should work, but when I run main.py, it prints:
File "C:\Users\User\PycharmProjects\cmd tool\main.py", line 1, in <module>
import version
ModuleNotFoundError: No module named 'version'
Normally Python should use folder C:\Users\User\PycharmProjects\cmd tool\ to search imported modules and you may have this folder even on list sys.path
But if it doesn't have this folder on list then you may add it manually before importing module.
import sys
# add at the end of list
#sys.path.append(r'C:\Users\User\PycharmProjects\cmd tool\')
# add at the beginning of list
sys.path.insert(0, r'C:\Users\User\PycharmProjects\cmd tool\')
import version
# ... code ...
To make it more universal you can use os to get this folder without hardcoding
import os
BASE = os.path.dirname(os.path.abspath(__file__))
print('BASE:', BASE)
import sys
sys.path.insert(0, BASE)
import version
# ... code ...
Just import file without the .py extension.
A folder can be marked as a package, by adding an empty __init__.py file.
You can use the __import__ function, which takes the module name (without extension) as a string extension.
change please the class name , and make the first letters uppercase
Version.py
def pyVersion():
os.system("python --version")
Main.py
import Version
Version.pyVersion()
and the code must work and he will give you a result Python version
I was trying to import a function from a sibling folder and i could, i look for documentation and didnt found something useful, can you help me please?
I have a folder named fold1, inside i have fold2 and fold3, inside fold2 i have filetoimport.py, it has:
def fntest(a, b):
return print(a+b)
And i want to import that function from inside fold3 file main.py, there i have
from fold2 import filetoimport
filetoimport.fntest(2,2)
Then i get an error:
Traceback (most recent call last):
File "fold3/main.py", line 1, in <module>
fold1 import filetoimport
ImportError: No module named 'fold1'
Hope you can help me :)
I also tried
from fold1.fold2 import filetoimport
But it failed.
Alright, this should work
import sys
import os
sys.path.insert(1,os.popen('pwd').read().replace('3\n','2'))
import filetoimport
filetoimport.fntest(2,2)
you just need to add the target folder to the python runtime path
You need to import the parent folder as a path the program can check inside for more modules. I had some luck with this
import os
import sys
sys.path.append(os.path.realpath('..'))
from fold2 import filetoimport
filetoimport.fntest(2,2)
As far as I have understood, your folder structure is as below
fold1
fold2
-- filetoimport.py
fold3
-- main.py
It seems that your are executing the main.py file from terminal (by opening fold1 path) as
python3 fold3/main.py
Instead you should execute the command as
python3 -m fold3.main
Since the argument is a module name, you must not give a file extension (.py)
On the other hand if you open fold1 as a project in IDE like pycharm or intellij idea and execute main.py via IDE itself, it wont give you an error.
Hope, this will solve your problem.
I have a structure such has:
/mainfolder
file.py
//subfolder
test.py
I am trying to import file.py in test.py. for some reason I just can't.
I tried
from .file import *
returning :
Traceback (most recent call last):
ModuleNotFoundError: No module named '__main__.file'; '__main__' is not a package
also tried to add path to sys.path:
import sys
import os
sys.path.extend([os.getcwd()])
doesnt work either
Looks like you're running test.py with python test.py and as such the test module is being treated as a top level module.
You should first make your folders Python packages if they are not by adding __init__.py files:
/mainfolder
__init__.py
file.py
/subfolder
__init__.py
test.py
Then you can append the outer mainfolder to sys.path:
import sys
import os
sys.path.append(os.path.join(os.getcwd(), '..'))
After which from file import someobject without relative import works. Be wary of wild card imports.
See ModuleNotFoundError: What does it mean __main__ is not a package? and How to do relative imports in Python? for more on why your current approach does not work.
What IDE are you using? I am using Pycharm Community IDE with Python 3 and it works with from file import * or from file import some_function (I wanted to comment but I can't since I don't have 50 reputation yet)
I write some python files like this:
main.py
view/ __init__.py #empity file
MainWindow.py
ListEditor.py
And in each file I wrote those imports:
<main.py>
from view.MainWindow import MainWindow
...
-
<MainWindow.py>
from view.ListEditor import ListEditor
and ListEditor.py don't import any files.
Each MainWindow.py or ListEditor.py defines a class that named same as the file name.
when I run the program from main.py, it works. But when I run from MainWindow.py I got ImportError: No module named 'view'
If I write
from ListEditor import ListEditor
in MainWindow.py, python MainWindow.py will be OK. but python main.py will get error:
ImportError: No module named 'ListEditor'
So, is there a way to make both python main.py and python MainWindow.py get right at the same time?
I'm using python3.4
P.S.
I think I have figured out the problem here. The import command searches a module in sys.path. The sys.path is a group of predefined paths plus the running script path. When I run the code from MainWindow.py, the code import ListEditor just works, but when I run from main.py, the current path is set to the parent path. So I need import view.ListEditor.
Well, there are couple ways to deal with it. #Vincent Beltman's answer is one of it. Or just put these code in the __init__.py file:
import os, sys
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(path)
Finally, I'm new to python. And I think the import command is quite strange. I thought it should search the files relative to the path of the source file that containing the command, not just relative to the starter file. A starter file may varying and cause troubles like this one.
Try this:
try:
from view.ListEditor import ListEditor # If this one fails
except:
try:
from ListEditor import ListEditor # It will try this one