Error with GDAL - python-2.7

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.

Related

'Wit' object has no attribute 'message'

Just trying to experiment with Wit.ai & Python but getting the following error. What am I doing wrong here??
Error:
Traceback (most recent call last):
File "C:/Python27/mx1.py", line 7, in <module>
resp = client.message(my_message)
AttributeError: 'Wit' object has no attribute 'message'
Code:
from wit import Wit
access_token='B3GHXHLTXIASO7S4KY7UC65LMSTCDEHK'
client = Wit(access_token)
my_message='who are you?'
resp = client.message(my_message)
print(resp)
So, it seems like you're using an older (actually unofficial) version of the Python pywit package, last updated on 2015-11-07 (version 0.4.0).
You should remove the pywit package and install wit, just like they say in the docs/install section:
pip uninstall pywit
pip install wit
Just for completeness, if you look inside the wit.py of your older pywit package, inside your python2.7/site-packages/wit/wit.py, you'll see the definition of old Wit class, with a get_message() method instead of the current message(). So, in the pywit, your code will run if you say:
resp = client.get_message(my_message)
instead of
resp = client.message(my_message)
But you should really switch to the current (official) version.

Concatenation of 2 strings failing because of incompatible operands error returned by PyCharm

I'm trying to run the following code :
# -*- coding: utf8 -*-
import requests
from bs4 import BeautifulSoup
link = "https://www.emploi-public.ma/ar/index.asp?p="
number_of_jobs = 0
houceima = u"الحسيمة"
print type(houceima)
for i in range(1,3):
page_link = link+str(i)
print page_link
emp_pub = requests.get(page_link)
soup = BeautifulSoup(emp_pub.content,"lxml")
for link in soup.find_all("a"):
if houceima in link :
print link
But I'm getting following error :
Traceback (most recent call last):
File "scrape_houceima", line 9, in <module>
page_link = link+str(i)
TypeError: unsupported operand type(s) for +: 'Tag' and 'str'
I'm using PyCharm. I stated my IDE because the same concatenation page_link = link+str(i) executed well in IDLE.
What could be the problem here ?
You re-used link in your code:
link = "https://www.emploi-public.ma/ar/index.asp?p="
and
for link in soup.find_all("a"):
The latter use replaces the first link reference, so it is no longer a string object but a Tag object.
Don't mask variables like that, rename one or the other. Perhaps the first use could be named base_url?

How to solve AttributeError in python active_directory?

Running the below script works for 60% of the entries from the MasterGroupList however suddenly fails with the below error. although my questions seem to be poor ou guys have been able to help me before. Any idea how I can avoid getting this error? or what is trhoughing off the script? The masterGroupList looks like:
Groups Pulled from AD
SET00 POWERUSER
SET00 USERS
SEF00 CREATORS
SEF00 USERS
...another 300 entries...
Error:
Traceback (most recent call last):
File "C:\Users\ks185278\OneDrive - NCR Corporation\Active Directory Access Scr
ipt\test.py", line 44, in <module>
print group.member
File "C:\Python27\lib\site-packages\active_directory.py", line 805, in __getat
tr__
raise AttributeError
AttributeError
Code:
from active_directory import *
import os
file = open("C:\Users\NAME\Active Directory Access Script\MasterGroupList.txt", "r")
fileAsList = file.readlines()
indexOfTitle = fileAsList.index("Groups Pulled from AD\n")
i = indexOfTitle + 1
while i <= len(fileAsList):
fileLocation = 'C:\\AD Access\\%s\\%s.txt' % (fileAsList[i][:5], fileAsList[i][:fileAsList[i].find("\n")])
#Creates the dir if it does not exist already
if not os.path.isdir(os.path.dirname(fileLocation)):
os.makedirs(os.path.dirname(fileLocation))
fileGroup = open(fileLocation, "w+")
#writes group members to the open file
group = find_group(fileAsList[i][:fileAsList[i].find("\n")])
print group.member
for group_member in group.member: #this is line 44
fileGroup.write(group_member.cn + "\n")
fileGroup.close()
i+=1
Disclaimer: I don't know python, but I know Active Directory fairly well.
If it's failing on this:
for group_member in group.member:
It could possibly mean that the group has no members.
Depending on how phython handles this, it could also mean that the group has only one member and group.member is a plain string rather than an array.
What does print group.member show?
The source code of active_directory.py is here: https://github.com/tjguk/active_directory/blob/master/active_directory.py
These are the relevant lines:
if name not in self._delegate_map:
try:
attr = getattr(self.com_object, name)
except AttributeError:
try:
attr = self.com_object.Get(name)
except:
raise AttributeError
So it looks like it just can't find the attribute you're looking up, which in this case looks like the 'member' attribute.

During migrating tool from windows to linux lxml error

I have developed a tool in python 2.7 that take xsd file as input ,
and give the process data into a test file
During processing the xsd file I used lxml, I am unable to resolve this sort of error.
AttributeError: 'Element' object has no attribute 'iterdescendants'
I don`t know what wrong with the lxml lib.
I want to know is there any lxml Linux compatible version for python 2.7
I have imported in the file like below:
try:
from lxml import etree
except ImportError:
import xml.etree.ElementTree as etree
I have imported only in file , and sending the element tree pointer to process the the element into another file ,
it is OK in the declared file , giving error in another file only.
the code throw the error is :
for tdocNode in lincFileRootNode:
rootNode = tdocNode.getroot()
lchildren = rootNode.getchildren()
for elt in lchildren:
if 'complex' == elt.tag:
if 'name' in elt.attrib:
if 'element' == item.tag:
if 'type' in item.attrib:
if elt.attrib['name'] == item.attrib['type']:
for key in elt.iterdescendants(tag='element'):
bIsElemTypeSimple = false
bIsElemTypeSimple = process_elementtype(key, lincFileRootNode)
where :
lincFileRootNode --> is list that containe the xsd file pointer to be processed
the error thrown is :
Traceback (most recent call last):
File "run.py", line 1210, in <module>
iret = xsd2dic_main()
File "run.py", line 71, in xsd2dic_main
iRet = yxsdtodic()
File "run.py", line 352, in yxsdtodic
iret = process_xsdfile(sXsdPath)
File "run.py", line 485, in xsdfile
sRet = process_dic_elementtype(item,lincFileRootNode)
File "run.py", line 817, in process_dic_elementtype
for key in elt.iterdescendants(tag='element'):
AttributeError: 'Element' object has no attribute 'iterdescendants'
i tired in the both the cases :
1:writing all code in a same file
2:writing different files
still i am getting the same error
This is mostly a guess, but look into it.
You appear to be calling iterdescendants from lxml's implementation of the Element type. However, if lxml fails to import, you fall back on Python's built in xml library instead. But it's implementation of Element doesn't have an iterdescendants methods of any kind. In other words, the two implementations have different public APIs. Add some print statements to see which library you're importing and do some additionally checking to see exactly what type elt is. If you want to be able to fall back on Python's built in xml, you'll need to structure your code to accommodate the different APIs.

__import__ vs imp.load_module

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 ?