I wanted to test the relative import model of Python 2.X
Directory tree:
exercises/
dir1/
dir2/
mod.py
dir3/
mod2.py
mod3.py
mod.py
import sys
print 'in dir1/dir2/mod.py'
path = [name for name in sys.path if 'Frameworks' not in name].
print 'Module search path of mod is:\n' + str(path)
import dir3.mod2
mod2.py
print 'in dir1/dir2/dir3/mod2.py'
import mod3
mod3.py
print 'in dir1/dir2/dir3/mod3.py by relative import'
'mod' would import 'mod2' from 'dir3', which would then import 'mod3'. In Python 3.X, this would fail because the path to 'mod3' is not provided; in Python 2.X, the interpreter searches the same directory containing 'mod2' before searching the rest of the path starting from the top level directory of 'mod'.
This is the error message I get:
MacBook-Pro-9 exercises % python dir1/dir2/mod.py
in dir1/dir2/mod.py
Module search path of mod is:
['Users/arthur/Desktop/learning_python/exercises/dir1/dir2', '/Library/Python/2.7/site-packages']
Traceback (most recent call last):
File "Desktop/learning_python/exercises/dir1/dir2/mod.py", line 8, in <module>
import dir3.mod2
ImportError: No module named dir3.mod2
I know 'dir2' contains 'dir3/mod2', but for some reason, Python can't find it. I'm pretty sure that the syntax for the import statement is correct.
I modified the print statements and changed 'mod2.py' code to read from . import mod3. I edited nothing else, and it ran just fine in Python 3.8 There was no problem finding 'dir3.mod2'
You have to add an empty file inside dir3 named init.py for python to be able to recognize the directory as a Python package directory. If you have these files
dir3/__init__.py
dir3/mod2.py
dir3/mod3.py
You can now import the code in mod2.py and mod3.py as
import dir3.mod2
import dir3.mod3
or
from dir3 import mod2
from dir3 import mod3
If you remove the init.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.
Here is the a link.
Related
I want to access to my modules.module function A in my main , but when I do this I have an error that I cannot import that.. how can I fix it? I Have seen multiples articles but i hadnt a chance, how can I fix this error of importing modules from subfolders?
**/tool
main.py
/google
/modules
__init__.py
module.py**
ImportError: cannot import name google
main.py
#!/usr/bin/python
import sys
import core.settings
from google.modules import google
if __name__ == '__main__':
try:
core.settings.settings()
google()
except KeyboardInterrupt:
print "interrupted by user.."
except:
sys.exit()
module.py
def google():
print 'A'
the easiest way to work this out is have your main.py in your highest directory (it makes sense anyway for main to be there) and if you really want the real main to be in a sub directory have a dummy main at the top level you can call that just calls the actual main, that way python can see your entire directory tree and will know how to import any sub directory.
alternatively
you could add your parent directory to the sys.path:
parent_dir = os.path.realpath(os.path.join(os.getcwd(),'..')))
sys.path.append(parent_dir)
which will add that directory to the places python searches for when you try to import stuff.
but then you will need to keep track of how deep your main is in the directory tree and its a pretty unelegant solution in my opinion
I would like to import a module from one location, unload it, and then import a module of the same name from another location in python. Something like:
sys.path.append(module_location_1)
import module
unload module
....
sys.path.append(module_location_2)
import module
I tried the following approach below but have had no luck:
sys.path.insert(0, /path1)
import my_module
print my_module # <module 'my_module' from '/path1/__init__.pyc'>
sys.path.insert(0, /path2)
import my_module
print my_module # still gives: <module 'my_module' from '/path1/__init__.pyc'
Unfortunately after the second input I see the the module is still be loaded from the original location I added to my path. I have tried:
1
removing the first location from sys.path all together between imports
imp.reload(my_module).
both appending and prepending to the path
Thanks!
I have been experimenting with python by creating some programs .The thing is, I have no idea how to import something OUT of the default python directory.
OK
So I did some heavy research and the conclusion is
if u want to access a file saved at different location
use
f = open('E:/somedir/somefile.txt', 'r')
r = f.read()
NOTE: Dont use '\' that were I went wrong.Our system addresses uses '\' So be careful
If you need to just read in a file and not import a module the documentation covers this extensively.
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
Specifically for Windows file systems you will need to do one of the following:
1.) Use forwardslashes vs backslashes. This should work with most OSes.
f = open("c:/somedir/somefile.txt", "r")
2.) Use a raw string.
f = open(r"c:\somedir\somefile.txt", "r")
3.) Escape the backslashes.
f = open("c:\\somedir\\somefile.txt", "r")
If you need to import a module to use in your program from outside your programs directory you can use the below information.
Python looks in the sys.path to see if the module exists there and if so does the import. If the path where you files/modules are located is not in the sys.path, Python will raise an ImportError. You can update the path programmatically by using the sys module.
import sys
dir = "path to mymodule"
if dir not in sys.path:
sys.path.append(dir)
import mymodule
You can check the current sys.path by using:
print(sys.path)
Example:
>>> print(sys.path)
['', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages']
>>> sys.path.append("/Users/ddrummond/pymodules")
>>> print(sys.path)
['', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python34.zip', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/plat-darwin', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages', '/Users/ddrummond/pymodules']
>>>
You can see that sys.path now contains '/Users/ddrummond/pymodules'.
Continusly to Unzip zip files in folders and subfolders with python this code work with python 3:
#!/usr/bin/env python3
import logging
from pathlib import Path
from shutil import unpack_archive
zip_files = Path(r"C:\Project\layers").rglob("*.zip")
while True:
try:
path = next(zip_files)
except StopIteration:
break # no more files
except PermissionError:
logging.exception("permission error")
else:
extract_dir = path.with_name(path.stem)
unpack_archive(str(path), str(extract_dir), 'zip')
i work with python 2.7.8 and can't change the version of python because it affect other important programs. When i run the code i get an error:
ImportError: No module named pathlib
How can i change the code so it will work?
In shell_plus, is there a way to automatically import selected helper methods, like the models are?
I often open the shell to type:
proj = Project.objects.get(project_id="asdf")
I want to replace that with:
proj = getproj("asdf")
Found it in the docs. Quoted from there:
Additional Imports
In addition to importing the models you can specify other items to
import by default. These are specified in SHELL_PLUS_PRE_IMPORTS and
SHELL_PLUS_POST_IMPORTS. The former is imported before any other
imports (such as the default models import) and the latter is imported
after any other imports. Both have similar syntax. So in your
settings.py file:
SHELL_PLUS_PRE_IMPORTS = (
('module.submodule1', ('class1', 'function2')),
('module.submodule2', 'function3'),
('module.submodule3', '*'),
'module.submodule4'
)
The above example would directly translate to the following python
code which would be executed before the automatic imports:
from module.submodule1 import class1, function2
from module.submodule2 import function3
from module.submodule3 import *
import module.submodule4
These symbols will be available as soon as the shell starts.
ok, two ways:
1) using PYTHONSTARTUP variable (see this Docs)
#in some file. (here, I'll call it "~/path/to/foo.py"
def getproj(p_od):
#I'm importing here because this script run in any python shell session
from some_app.models import Project
return Project.objects.get(project_id="asdf")
#in your .bashrc
export PYTHONSTARTUP="~/path/to/foo.py"
2) using ipython startup (my favourite) (See this Docs,this issue and this Docs ):
$ pip install ipython
$ ipython profile create
# put the foo.py script in your profile_default/startup directory.
# django run ipython if it's installed.
$ django-admin.py shell_plus