AttributeError: 'module' object has no attribute 'Describe' - python

I am very new to Python. Reading up on new material for class, I had to copy and paste a few examples to see how things work. So, I copied and pasted code from this website ( https://www.e-education.psu.edu/geog485/node/54 ) under the topic 'Looping in GIS Models'.
Here's mine:
import arcpy
try:
arcpy.env.workspace = "C:\Users\dan and kathryn\Desktop\school\programming\Lesson1"
fcList = arcpy.ListFeatureClasses()
for featureClass in fcList:
arcpy.CopyFeatures_management (featureClass, "C:\Users\dan and kathryn\Desktop\school\programming\Lesson 2\PracticeData/" + featureClass)
except:
print "Script failed to complete"
print arcpy.GetMessages(2)
Here's the error msg:
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.1\Lib\site-packages\pythonWin\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript
exec codeObject in __main__.__dict__
File "C:\Users\dan and kathryn\Desktop\loops_gis.py", line 1, in <module>
import arcpy
File "C:\Users\dan and kathryn\Desktop\arcpy.py", line 5, in <module>
desc = arcpy.Describe(featureClass)
AttributeError: 'module' object has no attribute 'Describe'
Contacted my teacher and he wrote code and sent it to me but everything matches. All of the backslashes, indentations, everything except for folder locations. Not sure what is going on but he suspects this problem runs beyond what I've written in my code.
I've already had to alter the site-packages folder within pythonWin and it now contains:
# .pth file for the PyWin32 extensions
win32
win32\lib
Pythonwin
C:\Program Files (x86)\ArcGIS\Desktop10.1\bin
C:\Program Files (x86)\ArcGIS\Desktop10.1\arcpy
C:\Program Files (x86)\ArcGIS\Desktop10.1\ArcToolbox\Scripts
Not sure what's going on or why 'Describe' is even popping up in the problems

Whenever writing path string, use r"path with backslash". It will take care of the backslash and forward slash problem. Use 'os' module when, the paths needed to be joined.

heres what i had the change (all in the backslashes, I had no idea):
arcpy.env.workspace = "C:/Users/dan and kathryn/Desktop/school/programming/Lesson1"
AND
arcpy.CopyFeatures_management (featureClass, "C:\Users\dan and kathryn\Desktop\school\programming\Lesson 2\PracticeData/" + featureClass)

Related

P4Python run method does not work on empty folder

I want to search a Perforce depot for files.
I do this from a python script and use the p4python library command:
list = p4.run("files", "//mypath/myfolder/*")
This works fine as long as myfolder contains some files. I get a python list as a return value. But when there is no file in myfolder the program stops running and no error message is displayed. My goal is to get an empty python list, so that I can see that this folder doesn't contain any files.
Does anybody has some ideas? I could not find information in the p4 files documentation and on StackOverflow.
I'm going to guess you've got an exception handler around that command execution that's eating the exception and exiting. I wrote a very simple test script and got this:
C:\Perforce\test>C:\users\samwise\AppData\local\programs\python\Python36-32\python files.py
Traceback (most recent call last):
File "files.py", line 6, in <module>
print(p4.run("files", "//depot/no such path/*"))
File "C:\users\samwise\AppData\local\programs\python\Python36-32\lib\site-packages\P4.py", line 611, in run
raise e
File "C:\users\samwise\AppData\local\programs\python\Python36-32\lib\site-packages\P4.py", line 605, in run
result = P4API.P4Adapter.run(self, *flatArgs)
P4.P4Exception: [P4#run] Errors during command execution( "p4 files //depot/no such path/*" )
[Error]: "//depot/no such path/* - must refer to client 'Samwise-dvcs-1509687817'."
Try something like this ?
import os
if len(os.listdir('//mypath/myfolder/') ) == 0: # Do not execute p4.run if directory is empty
list = []
else:
list = p4.run("files", "//mypath/myfolder/*")

KeyError from configparser.py when executing Twitter Bot

I tried to make a Twitter bot from https://github.com/joaquinlpereyra/twitterImgBot
The installations went well and successfully but the problem came when I tried to execute it.
Below is the code for my config in the config.py.
Keys and Tokens removed with the API key replaced with random numbers because that's the problem I'm trying to address.
import os
import configparser
import tweepy
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
# read configs from file
config = configparser.ConfigParser()
config.read(dname + '/settings')
twitter_config = config['Twitter']
api_key = twitter_config['2931928391273123']
secret_key = twitter_config['REMOVED']
token = twitter_config['REMOVED']
secret_token = twitter_config['REMOVED']
The error I'm getting when executing it in cmd is:
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
C:\Documents and Settings\Administrator>cd C:\Documents and Settings\Administrat
or\Desktop\twitterImgBot-master
C:\Documents and Settings\Administrator\Desktop\twitterImgBot- master>python twitterbot.py
Traceback (most recent call last):
File "twitterbot.py", line 3, in <module>
from settings import config
File "C:\Documents and Settings\Administrator\Desktop\twitterImgBot-master\settings\config.py", line 13, in <module>
api_key = twitter_config['2931928391273123']
File "C:\Python34\lib\configparser.py", line 1203, in __getitem__
raise KeyError(key)
KeyError: '2931928391273123'
C:\Documents and Settings\Administrator\Desktop\twitterImgBot-master>
I looked up all the questions here that has something to do with KeyError but none of them have something to do with the Twitter's API key
Again, the API key which is 2931928391273123 is just a random number to substitute the original one for obvious reasons. I did double check it to make sure I had the correct keys/tokens before resorting to here.
This is also a first for me, so I'm hoping someone can lend me a helping hand! I would have posted the 2 screenshots of the Python file and the cmd but I'm only limited to one link.
Thanks in advance!

python sqlite3 connection path with spaces

I am trying to connect with a full path but I get this problem
>>> path = "/home/astro/Fun LAB/DBlist"
>>> db = sql.connect(path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: unable to open database file
>>>
i 've also tried this
>>> path = "/home/astro/Fun\ LAB/DBlist"
>>> db = sql.connect(path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.OperationalError: unable to open database file
>>>
I know it's because of the whitespace cause I've tried this and it works
>>> path = "/home/astro/DBlist"
>>> db = sql.connect(path)
>>>
so is there is an easy way to escape the whitespaces in the path or am I doing something wrong?
You might try the uri style approach - it worked for me in getting past connection issues due to spaces in file paths with sqlite3:
Escaping the spaces with %20
prefixing the path with file:///
Examples:
file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
file:///C:/Documents%20and%20Settings/fred/Desktop/
I would suggest naming files or folders without spaces. (I don't think it's possible either) Instead, use dash or underscores.
The next problem is to see where you're running your Python interpreter. If it's nested inside a directory and you're trying to create a path from the outside, then your link would raise an error.
>>> path = "/home/astro/Fun LAB/DBlist"
or
>>> path = "/home/astro/Fun\ LAB/DBlist"
or
>>> path = "/home/astro/DBlist"
wouldn't work if you run python inside these directories or from another.
To correct this, try:
>>> path = "../home/path/to/file"
Having spaces is indeed a problem.
I would suggest bring a symlink and work with that:
!ln -sf '$path_to_db_file' .
db = sql.connect('db_file')

removing py files and retaining pyc files breaks inspection code

The function below works just fine. But if I remove all py files (and leave the pycs intact) then I get an error:
To explain what I mean by 'intact' here is more or less what I did:
1. write a bunch of py files and stick them in a friendly directory structure
2. test code code. It works
3. compile all py files to get pyc files
4. delete py files
5. test code. It fails
The function:
def get_module_name_and_line():
"""
return the name of the module from which the method calling this method was called.
"""
import inspect
lStack = inspect.stack()
oStk = lStack[2]
oMod = inspect.getmodule(oStk[0])
oInfo = inspect.getframeinfo(oStk[0])
sName = oMod.__name__ #<<<<<<<<<<<<<<<<<< ERROR HERE
iLine = oInfo.lineno
return sName,iLine
The error:
AttributeError: 'NoneType' object has no attribute '__name__'
So oMod is None in this error. If the py files are around then oMod is never None.
The question:
Why does inspect only return a module if py files are intact? How can I make this function work without py files.
Full Traceback:
Original exception was:
Traceback (most recent call last):
File "/home/criticalid/programs/damn.py", line 630, in <module>
File "/home/criticalid/programs/golly/class_foo.py", line 121, in moo
File "/home/criticalid/programs/golly/class_foo.py", line 151, in get_module_name_and_line
AttributeError: 'NoneType' object has no attribute '__name__'
This works for me. It assumes that all modules are in packages within the current working directory. And it doesn't return the __main__ module, rather its file name.
I'm sure there is a better solution but this solves my problems.
def get_module_name_and_line():
"""
return the name of the module from which the method calling this method was called.
"""
def get_name_from_path(sPath):
import os
sCWD = os.getcwd()
lCWD = list(os.path.split(sCWD))
lPath = list(os.path.split(sPath))
lPath[-1] = '.'.join(lPath[-1].split('.')[:-1]) #remove file extension
lRet = [s for s in lPath[len(lCWD)-1:]]
return '.'.join(lRet)
import inspect
lStack = inspect.stack()
oStk = lStack[2]
iLine = inspect.getlineno(oStk[0])
sName = get_name_from_path(inspect.getfile(oStk[0]))
return sName,iLine

ID3-mp3 editing in python - up-to-date package?

Edit: Trying to get these libraries to work in python 3.3 was clearly the wrong approach, and my problem now is entirely different so I'll just re-ask it in a new question.
I want to be able to edit ID3 tags of mp3 files with python commands, for example something like setAlbumName("folderPath\song.mp3", "albumname"). So far I've tried Mutagen, PyID3, pytagger, eyeD3, and they all seem to be outdated because the installation fails due to syntax errors. I tried to fix it in eyeD3, but I hit a dead end: http://i41.tinypic.com/o6zklv.png (second screenshot from after I had fixed all the prints and "except Error, e" and so on).
I tried the same with Mutagen, but I ran into a wall there as well when replacing "raise KeyError, key" with "raise KeyError as key" didn't work.
I didn't even know what to make of this one (pytagger): http://i41.tinypic.com/29fz7mh.png
It seems to suggest that there's something wrong with my python installation? Not getting into that.
So, would anyone like to point me to an ID3 package that works, or have a go at fixing an outdated one?
(Also, I tried both "python setup.py install" and "setup.py install" and it seemed to make no difference. I'm on windows 8.)
Edit: From the screenshot below, plus the source code (mutagen with python 2.7.5)
from mutagen.mp3 import MP3
p = "E:\\Musik\\Aeon\\2005 Bleeding the False\\01 Cenobites - Copy.mp3"
audio = MP3(p)
audio["title"] = "An example"
audio.pprint()
audio.save()
_
Traceback (most recent call last):
File "id3tag.py", line 5, in <module>
audio.pprint()
File "C:\Python27\lib\site-packages\mutagen\__init__.py", line 138, in pprint
try: tags = self.tags.pprint()
File "C:\Python27\lib\site-packages\mutagen\id3.py", line 190, in pprint
frames = list(map(Frame.pprint, self.values()))
TypeError: unbound method pprint() must be called with Frame instance as first a
rgument (got str instance instead)
_
from mutagen.mp3 import MP3
p = "E:\\Musik\\Aeon\\2005 Bleeding the False\\01 Cenobites - Copy.mp3"
audio = MP3(p)
audio["title"] = "An example"
audio.save()
_
Traceback (most recent call last):
File "id3tag.py", line 7, in <module>
audio.save()
File "C:\Python27\lib\site-packages\mutagen\__init__.py", line 132, in save
return self.tags.save(filename, **kwargs)
File "C:\Python27\lib\site-packages\mutagen\id3.py", line 370, in save
framedata = [self.__save_frame(frame) for (key, frame) in frames]
File "C:\Python27\lib\site-packages\mutagen\id3.py", line 461, in __save_frame
framedata = frame._writeData()
AttributeError: 'str' object has no attribute '_writeData'
mutagen works great for me with Python 2.7.
examples:
https://code.google.com/p/mutagen/wiki/Tutorial
from mutagen.mp3 import MP3
audio = MP3("example.mp3")
audio["title"] = "An example"
audio.pprint()
audio.save()
p.s. please post code samples so people can help.. not links to screenshots.
p.p.s. it looks like you are trying to install Python2 libs into Python3.
Mutagen also has an EasyID3 tool, which handles simple tasks like changing the file's title:
from mutagen.easyid3 import EasyID3
f = EasyID3("file.mp3")
f["title"] = u"Some title"
f.save()
Works like a charm. But it has very restricted functionality.
See more examples at http://code.google.com/p/mutagen/wiki/Tutorial

Categories

Resources