re-import a Python Module from a different location - python-2.7

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!

Related

Python 2.7 cannot find module in its search path

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.

Why can't I import WD_ALIGN_PARAGRAPH from docx.enum.text?

I transferred some code from IDLE 3.5 (64 bits) to pycharm (Python 2.7). Most of the code is still working, for example I can import WD_LINE_SPACING from docx.enum.text, but for some reason I can't import WD_ALIGN_PARAGRAPH.
At first, nearly non of the imports worked, but after I did
pip install python-docx
instead of
pip install docx
most of the imports worked except for WD_ALIGN_PARAGRAPH.
# works
from __future__ import print_function
import xlrd
import xlwt
import os
import subprocess
from calendar import monthrange
import datetime
from docx import Document
from datetime import datetime
from datetime import date
from docx.enum.text import WD_LINE_SPACING
from docx.shared import Pt
# does not work
from docx.enum.text import WD_ALIGN_PARAGRAPH
I don't get any error messages but Pycharm marks the line as error:
"Cannot find reference 'WD_ALIGN_PARAGRAPH' in 'text.py'".
You can use this instead:
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
and then substitute WD_PARAGRAPH_ALIGNMENT wherever WD_ALIGN_PARAGRAPH would have appeared before.
The reason this is happening is that the actual enum object is named WD_PARAGRAPH_ALIGNMENT, and a decorator is applied that also allows it to be referenced as WD_ALIGN_PARAGRAPH (which is a little shorter, and possibly clearer). I expect the syntax checker in PyCharm is operating on direct module attributes and doesn't pick up the alias, which is resolved by the Python parser/compiler.
Interestingly, I expect your code would work fine either way. But to get rid of the annoying message you can use the base name.
If someone uses pylint it can be easily suppressed with # pylint: disable=E0611 added at the end of the import line.

how can I import subfolders module python to another file?

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

How do I import files from other directory in python 2.7

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'.

I have a flask application that I would like to convert into an executable

I have a flask application that I would like to convert into an executable for deploying elsewhere. I have used py2exe for that. I am getting jinja2:TemplateNotFound error. I have copied the static and templates folders into the dist folder where the exe files reside. Pls let me know if I am missing something. My setup file is as follows:
from distutils.core import setup
import py2exe
import os
from glob import glob
import sys
from distutils.filelist import findall
import matplotlib
matplotlibdatadir = matplotlib.get_data_path()
matplotli bdata = findall(matplotlibdatadir)
matplotlibdata_files = []
for f in matplotlibdata:
dirname = os.path.join('matplotlibdata', f[len(matplotlibdatadir)+1:])
matplotlibdata_files.append((os.path.split(dirname)[0], [f]))
data_files=[('static', glob("D:\\pythonLearning\\static\\*.*")), ('templates', glob("D:\\pythonLearning\\templates\\login.html"))]
data_files.extend(matplotlibdata_files)
print data_files
sys.path.append('C:\\Windows\\winsxs\\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.6161_none_50934f2ebcb7eb57')
setup( console=['myfile.py'],
options={ 'py2exe': { 'packages' : ['matplotlib', 'pytz','werkzeug','email','jinja2.ext'],
'includes': ['flask','jinja2'] } },
data_files=data_files )
This is because jinja expects your egg to be unzipped and available via the filepath. See for more information.
You can workaround this for typical data files using this
but jinja2 has no direct support for this and you would have to implement this yourself