python

Best way for Parsing ANSI and UTF-16LE files using Python 2/3?

I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa. Is there a straightforward way to open up the files using the correct file encoding? ...

How do I handle exceptions when using threading and Queue?

If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs). from threading import Thread from Queue import Queue from time import sleep def do_work(item): sleep(0.5) print "working" , ...

Render PyCairo onto PyOpenGL surface?

I've recently started playing with pycairo - is it easy enough to render this to an pyopengl surface (e.g. on the side of a cube?)... my opengl is really non-existant so I'm not sure the best way to go about this. ...

How can I make a change to a module without restarting python interpreter?

I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing. Is there an easier way to do this? Thanks, Charlie ...

rules for slugs and unicode

After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles. url encoding is very restrictive. See http://www.blooberry.com/indexdot/html/topics/urlencoding.htm So, for example how do folks deal with for title slugs for things like "Una lágrima cayó en l...

python, __slots__ and "attribute is read-only"

Hello I want to create an object in python that have a few attributes and i want to protect myself from accidently using wrong attribute name. The code is following: class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = test() # create one a.m = "?" # here is a PROBLEM But ...

Why is Maya 2009 TreeView control giving a syntax error on drag?

I'm using the TreeView control in Maya 2009 but I'm getting a syntax error on drag and drop. My code is as follows (simplified for brevity): class View(event.Dispatcher): def __init__(self): self.window = cmds.window() tree_view = cmds.treeView( numberOfButtons=1, allowReparenting=True, dragAndDropComman...

How to bestow string-ness on my class?

I want a string with one additional attribute, let's say whether to print it in red or green. Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying. Can multiple inheritence help? I never used that. Inheriting only object and using self.value=str means I have to implement all string-ness messages ...

SyntaxError in finally (Django)

Hello! I'm using Django, and I have the following error: Exception Type: SyntaxError Exception Value: invalid syntax (views.py, line 115) My viws.py code looks like this: def myview(request): try: [...] except MyExceptionClass, e: [...] finally: render_to_response('template.html', {}, context_instance = RequestContext(req...

Where can I find some "hello world"-simple Beautiful Soup examples?

I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that? ...

SQL TOP 1 analog for lists in Python

Here is an example of my input csv file: ... 0.7,0.5,0.35,14.4,0.521838919218 0.7,0.5,0.35,14.4,0.521893472678 0.7,0.5,0.35,14.4,0.521948026139 0.7,0.5,0.35,14.4,0.522002579599 ... I need to select the top row where the last float > random number. My current implementation is very slow (script has a lot of iterations of this and ou...

what python feature is illustrated in this code?

I read Storm ORM's tutorial at https://storm.canonical.com/Tutorial, and I stumbled upon the following piece of code : store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") I'm not sure that the second argument of the find method will be evaluated to True/False. I think it will be interpreted as a lambda. If th...

Python sockets buffering

Let's say I want to read a line from a socket, using the standard socket module: def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret What exactly happens in s.recv(1)? Will it issue a system call each time? I guess ...

How to separate content from a file that is a container for binary and other forms of content

I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file (say a gif or jpg). ...

Emacs Pabbrev and Python

Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it without writing any elisp?...

I need a regex for the href attribute for an mp3 file url in python

Hi, Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module: import re urls = re.finditer('http://(.*?).mp3', htmlcode) The variable urls is an iterable object and I can use a loop to access each mp3 file url individually if there is more than one : for url in u...

How do I iterate over the HTML attributes of a Beautiful Soup element?

How do I iterate over the HTML attributes of a Beautiful Soup element? Like, given: <foo bar="asdf" blah="123">xyz</foo> I want "bar" and "blah". ...

logging in mod_python/apache

What is the standard way to make python's logging module work with apache/modpython? I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request. Is there an easy way to set this up? ...

Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?

Hi! I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically: I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So: >>> type(myDict) <type 'dict'> >>> type(myDict[u'myKey']) <type 'dict'> >>> type(myDict[u'myKey'][u'myKey2']) <type...

What's the best way to record the type of every variable assignment in a Python program?

Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file. One way to compensate might be to write a special ...