I have a test.py file that I try to run in VSCode with the "Run" button.
I have a string from file_folder.file import something inside it. When I try to run my test, VSCode gives me an error ModuleNotFoundError: No module named 'file_folder'.
My project tree looks something like this:
root_folder -- file_folder -- file.py
-- test_folder -- my_folder -- test.py
Can I make it work in VSCode somehow?
You can try something like this:
import sys
sys.path.insert(1, '<pathToFolder>/file_folder')
from file import something
For cross directory access, we usually use relative paths to facilitate code portability.
import sys
from os.path import dirname, abspath
project_path = dirname(dirname(abspath(__file__)))
sys.path.append(project_path + "\\file_folder")
from file import *
Related
I want to import function from bot/main.py into bybitapi/server.py. The structure of project looks like this:
So, in server.py I was trying to do it like this:
from bot.main import notifyuserwithtriggeredalarms
But it doesn't work, it was about bot package doesn't exists. Also, I was trying to solve this using os and sys, I couldn't, so, how can I import function in server.py though other folder?
mport a Module From the Parent Directory in Python by Adding It to PYTHONPATH
import os, sys
p = os.path.abspath('.')
sys.path.insert(1, p)
from main import notifyuserwithtriggeredalarms
I have a directory like this:
-RootFolder/
- lib/
- file.py
- source/
- book.py
I'm at the book.py, how do I import a class from the file.py?
When you are running book.py, only it's directory is gonna be added to the sys.path automatically. You need to make sure that the path to the RootFolder directory is in sys.path(this is where Python searches for module and packages) then you can use absolute import :
# in book.py
import sys
sys.path.insert(0, r'PATH TO \RootFolder')
from lib.file import ClassA
print(ClassA)
Since you added that directory, Python can find the lib package(namespace package, since it doesn't have __init__.py)
If you start your program from RootFolder (e.g. python -m source.book), the solution by Irfan wani should be perfectly fine. However, if not, then some hacking is required, to let Python know lib also contains relevant code:
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent / "lib"))
import file
from lib.file import some_module
I think this should work fine if the rootfolder is added to path.
If not, we need to do that first as shown by #Amadan and #SorousH Bakhtiary (just wanted to add some explanation);
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent.parent))
So here, Path(__file__) gives the path to the file where we are writing this code and .parent gives its parent directory path and so on.
Thus, str(Path(__file__).parent.parent) gives us path to the RootFolder and we are just adding that to the path.
I have the following the directory structure
pytest_testing/
__init__.py
math_ops.py
dbs/
__init__.py
dbConnect.py
tests/
test1.py
Now in test1.py i am trying to do import a function from dbConnect module, like this from pytest_testing.dbs.dbConnect import query_data but i get error "No Module named pytest_testin.
If i try the same in a directory above pytest_testing everything works just fine. Am i missing something here ?
Well, you can just type this from dbs.dbConnect import query_data.
I think this can work well
If you are using Linux or Windows use the code:
# test1.py
import sys
sys.path.append(/path/to/pytest_testing/dbs/)
from dbConnect import functionName #dbConnect without .py extension
I have a folder structure like so:
/mylib/
/mylib/__init__.py
/mylib/my_class.py
/mylib/tests/test_my_lib.py
In my test, I have:
from mylib import MyClass
import unittest
I'm getting:
File "test_edgecast_mcc_client.py", line 1, in <module>
from mylib import MyClass
ImportError: No module named mylib
Which, I think, makes sense because the import would be looking inside the tests directory for mylib when it should be looking in ../mylib?
Can anyone share some light on how to get the import to work properly?
I believe your tests package needs an __init__.py file too
Add primary directory to $PYTHONPATH. You can do it from your test_my_lib.py using something like this:
import sys
import os.path
d = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, d)
try using this from command line and see if that eliminates the error
export PYTHONPATH="$PYTHONPATH:/path/to/mylib/"
I have a python script that is trying to import another script somewhere in the file-system (path is only known at runtime).
To my understanding I need to use the imp module and this might work, but when loading the module I get an error that modules used by the imported module are not found.
Heres the code:
importer.py:
import imp
imp.load_compiled("my_module","full_path_to_my_module\\my_module.pyc")
my_module.py:
import sys
import another_module
When I run importer.py I get htis error message:
ImportError: No module named another_module
Whats going wrong here ?
I suspect that when 'importer.py' is loading 'my_module.pyc' hes also trying to load 'another_module' (thats good) but is looking in the wrong place (eg not 'full_path_to_my_module')
EDIT:
I tried adding 'full_path_to_my_module' to the system path:
import imp
import sys
sys.path.append(full_path_to_my_module)
imp.load_compiled("my_module",full_path_to_my_module+my_module)
But I still get the same error
Maybe I do something thats not necessary - Here's my goal:
I want to be able to use all functionality of 'my_module.pyc' inside 'importer.py'. But the location of 'my_module.pyc' is given as a parameter to 'importer.py'.
imp.load_compiled returns the compiled module object, it is different to the import statement which also binds the module to a name
import imp
my_module = imp.load_compiled("my_module", "full_path_to_my_module/my_module.pyc")
Then you can do something like:
my_module.yayfunctions('a')
Complete example session:
$ cat /tmp/my_module.py
def yayfunctions(a):
print a
$ python -m compileall /tmp/my_module.py
$ ls /tmp/my_module.py*
my_module.py my_module.pyc
$ python
>>> import imp
>>> my_module = imp.load_compiled("my_module", "/tmp/my_module.pyc")
>>> my_module.yayfunctions('a')
a
Edit regarding comment (ImportError: No module named another_module), I assume the error is caused by the code in my_module.pyc, and the another_module.py lives in the same directory
In that case, as others have suggested, it's simpler to just add the directory containing my_module to sys.path and use the regular import mechanism, specifically __import__
Here's a function which should do what you want:
import os
def load_path(filepath):
"""Given a path like /path/to/my_module.pyc (or .py) imports the
module and returns it
"""
path, fname = os.path.split(filepath)
modulename, _ = os.path.splitext(fname)
if path not in sys.path:
sys.path.insert(0, path)
return __import__(modulename)
if __name__ == '__main__':
# Example usage
my_module = load_path('/tmp/my_module.py')
my_module.yayfunctions('test')
It is since at the scope of import another_module your "full_path_to_my_module" isn't known.
Have you tried to add the path to known paths instead, i.e.:
import sys
sys.path.append("full_path_to_my_module")
You don't actually need to use the imp module to load pyc modules.
An easy way to try it out is to make two python modules, one importing from the other and run it. Delete then the imported .py file so you only get the .pyc file left: when running the script the import will work just fine.
But, for importing py files from random directories, you may want to add that directory to the python path first before importing it.
For instance:
import sys
sys.path.insert(0, "/home/user/myrandomdirectory")
Loading pyc files works the exact same way as loading a py file except it doesn't do a compile step. Thus just using import mymodule will work as long as the version number of the pyc is the same as the python you're running. Otherwise you'll get a magic number error.
If you module isn't in your path you'll need to add that to sys -- or if its a subdirectory, add a __init__.py file to that directory..