__import__ vs imp.load_module - python-2.7

I got an error while trying to install autopep8 with ironpython:
ImportError: No module named logilab
The code snippet it failed is:
def load_module(self, fullname):
self._reopen()
try:
mod = imp.load_module(fullname, self.file, self.filename, self.etc)
finally:
if self.file:
self.file.close()
# Note: we don't set __loader__ because we want the module to look
# normal; i.e. this is just a wrapper for standard import machinery
return mod
using the interpreter ipy64 importing logilab did not fail.
I added a print statement for the filename and it showed:
C:\Program Files (x86)\IronPython 2.7\Lib\site-packages\logilab_common-0.59.1-py2.7.egg\logilab
The path exists and it contains a init.py with the following content:
"""generated file, don't modify or your data will be lost"""
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
pass
I fixed the error quick and dirty by adding
except ImportError:
mod = __import__(fullname)
but I do not have a good feeling about this fix as I don't know the possible impacts.
Now, why does using imp.load_module fail and what is the difference using import ?

Related

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

IOError while parsing a XML file

I wanted to use Python and XML to easily create objects in my Autodesk Maya Scene.
As soon as I try to parse my XML file, I get this Error :
Error: IOError: file C:\Program Files\Autodesk\Maya2016\bin\python27.zip\xml\dom\expatbuilder.py line 922: 2 #
The code that I wrote is this one :
import maya.cmds as cmds
import xml.dom.minidom as xd
class readXML():
def __init__(self):
path = "mRigger/XML/arm.rig"
print path
xFile = xd.parse(path)
init = readXML()
I only get the problem if I run it in Maya (Python 2.7) but not if I run it in PyCharm
Try switching to an absolute path. Your Maya may be running from a different working directory than PyCharm. an IOError 2 usually means 'file not found'

Fix pcap checksum using Python Scapy

I've written one small python script to fix the checksum of L3-4 protocols using scapy. When I'm running the script it is not taking command line argument or may be some other reason it is not generating the fix checksum pcap. I've verified the rdpcap() from scapy command line it is working file using script it is not getting executed. My program is
import sys
import logging
logging.getLogger("scapy").setLevel(1)
try:
from scapy.all import *
except ImportError:
import scapy
if len(sys.argv) != 3:
print "Usage:./ChecksumFixer <input_pcap_file> <output_pcap_file>"
print "Example: ./ChecksumFixer input.pcap output.pcap"
sys.exit(1)
#------------------------Command Line Argument---------------------------------------
input_file = sys.argv[1]
output_file = sys.argv[2]
#------------------------Get The layer and Fix Checksum-------------------------------
def getLayer(p):
for paktype in (scapy.IP, scapy.TCP, scapy.UDP, scapy.ICMP):
try:
p.getlayer(paktype).chksum = None
except: AttributeError
pass
return p
#-----------------------FixPcap in input file and write to output fi`enter code here`le----------------
def fixpcap():
paks = scapy.rdpcap(input_file)
fc = map(getLayer, paks)
scapy.wrpcap(output_file, fc)
The reason your function is not executed is that you're not invoking it. Adding a call to fixpcap() at the end of your script shall fix this issue.
Furthermore, here are a few more corrections & suggestions:
The statement following except Exception: should be indented as well, as follows:
try:
from scapy.all import *
except ImportError:
import scapy
Use argparse to parse command-line arguments.
Wrap your main code in a if __name__ == '__main__': block.

Error with GDAL

I have tried and run this script from Rutger Kassies.
import gdal
import matplotlib.pyplot as plt
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
data = ds.ReadAsArray()
ds = None
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(data[0,:,:], cmap=plt.cm.Greys, vmin=1000, vmax=6000)
But then an error always occured:
Traceback (most recent call last):
File "D:\path\to\python\stackoverflow.py", line 5, in <module>
data = ds.ReadAsArray()
AttributeError: 'NoneType' object has no attribute 'ReadAsArray'
What's wrong with the script? Am I missing something? In installing GDAL I have followed this instruction http://pythongisandstuff.wordpress.com/2011/07/07/installing-gdal-and-ogr-for-python-on-windows/
Am using windows 7/32 bit/Python 2.7.
Thanks!
gdal.Open() is failing and returning 'None'. This produces the sometimes counterintuitive message "NoneType' object has no attribute ...". Quoting from Python: Attribute Error - 'NoneType' object has no attribute 'something', "NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result."
Apparently GDAL is correctly installed. It could be that the file is not readable or that there is an issue with the HDF driver. Are you getting any error message like:
`HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not
exist in the file system, and is not recognised as a supported dataset
name.
To get additional information you can try something like this instead of the gdal.Open() line in your script:
gdal.UseExceptions()
ds=None
try:
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
except RuntimeError, err:
print "Exception: ", err
exit(1)
Also, there's an extra '}' at the end of the script.
By default, osgeo.gdal returns None on error, and does not normally raise informative exceptions. You can change this with gdal.UseExceptions().
Try something like this:
from osgeo import gdal
gdal.UseExceptions()
source_path = r'HDF4_SDS:sample:"D:\path\to\file\A2002037045000.L2_LAC.SAMPLE.hdf":01'
try:
ds = gdal.Open(source_path)
except RuntimeError as ex:
raise IOError(ex)
The last bit just re-raises the exception as an IOError rather than a RuntimeException.
The solution is to modify source_path to a working path to your data source, e.g., I see
IOError: `HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not exist in the file system, and is not recognised as a supported dataset name.

Unit testing in Web2py

I'm following the instructions from this post but cannot get my methods recognized globally.
The error message:
ERROR: test_suggest_performer (__builtin__.TestSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
File "applications/myapp/tests/test_search.py", line 24, in test_suggest_performer
suggs = suggest_flavors("straw")
NameError: global name 'suggest_flavors' is not defined
My test file:
import unittest
from gluon.globals import Request
db = test_db
execfile("applications/myapp/controllers/search.py", globals())
class TestSearch(unittest.TestCase):
def setUp(self):
request = Request()
def test_suggest_flavors(self):
suggs = suggest_flavors("straw")
self.assertEqual(len(suggs), 1)
self.assertEqual(suggs[0][1], 'Strawberry')
My controller:
def suggest_flavors(term):
return []
Has anyone successfully completed unit testing like this in web2py?
Please see: http://web2py.com/AlterEgo/default/show/260
Note that in your example the function 'suggest_flavors' should be defined at 'applications/myapp/controllers/search.py'.
I don't have any experience with web2py, but used other frameworks a lot. And looking at your code I'm confused a bit. Is there an objective reason why execfile should be used? Isn't it better to use regular import statement. So instead of execfile you may write:
from applications.myapp.controllers.search import suggest_flavors
It's more clear code for pythoners.
Note, that you should place __init__.py in each directory along the path in this case, so that dirs will form package/module hierarchy.