python

Django: Best way to implement "status" field in modules

I have a field in my module that is used to hold the status of the object. So far I have used: ORDER_STATUS = ((0, 'Started'), (1, 'Done'), (2, 'Error')) status = models.SmallIntegerField(choices=ORDER_STATUS) Its easy to convert one way: def status_str(self): return ORDER_STATUS[self.status][1] The problem is when updating. I find...

Strip whitespace in generated HTML using pure Python code

I am using Jinja2 to generate HTML files which are typically very huge in size. I noticed that the generated HTML had a lot of whitespace. Is there a pure-Python tool that I can use to minimize this HTML? When I say "minimize", I mean remove unnecessary whitespace from the HTML (much like Google does -- look at the source for google.com,...

Implementation of an async method in Python DBus

How do I implement an async method in Python DBus? An Example below: class LastfmApi(dbus.service.Object): def __init__(self): bus_name = dbus.service.BusName('fm.lastfm.api', bus=dbus.SessionBus()) dbus.service.Object.__init__(self, bus_name, '/') @dbus.service.method('fm.last.api.account', out_signature="s") ...

Handle 404 throw by code in appengine

I manage the "real" 404 errors in this way: application = webapp.WSGIApplication([ ('/', MainPage), #Some others urls ('/.*',Trow404) #I got the 404 page ],debug=False) But in some parts of my code i throw a 404 error self.error(404) and i wanna show the same page that mentioned before, ¿there is any way to catch...

What are acceptable use-cases for python's `assert` statement?

I often use python's assert statement to check user input and fail-fast if we're in a corrupt state. I'm aware that assert gets removed when python with the -o(optimized) flag. I personally don't run any of my apps in optimized mode, but it feels like I should stay away from assert just in-case. It feels much cleaner to write assert fi...

Python: Analysis on CSV files 100,000 lines x 40 columns

I have about a 100 csv files each 100,000 x 40 rows columns. I'd like to do some statistical analysis on it, pull out some sample data, plot general trends, do variance and R-square analysis, and plot some spectra diagrams. For now, I'm considering numpy for the analysis. I was wondering what issues should I expect with such large files...

getting list without k'th element efficiently and non-destructively

I have a list in python and I'd like to iterate through it, and selectively construct a list that contains all the elements except the current k'th element. one way I can do it is this: l = [('a', 1), ('b', 2), ('c', 3)] for num, elt in enumerate(l): # construct list without current element l_without_num = copy.deepcopy(l) l_witho...

pylint seems to not handle "from . import foo" style imports

If I do: from . import foo In a script and run pylint over it, I get: F: 1: Unable to import %r Is there a way a work around for getting pylint to understand this syntax? ...

What's the best way to add a GUI to a pygame application?

Are there any good GUIs that support pygame surfaces as a widget within the application? If this isn't possible or practical, what GUI toolkit has the best graphics component? I'm looking to keep the speedy rendering made possible by a SDL wrapper. ...

How do I get the "Interests" of a facebook user uing Facebook Connect? (I'm using Django/python and pyFacebook middleware)

def index(request): fbdata = [] if request.facebook.check_session(request): fbdata = request.facebook.users.getInfo(request.facebook.uid, ['name', 'pic']) print fbdata This works! I am able to get the user's picture and name. However...I'd like to get the interests of that user. How can I do that? By the way, I i...

Open a PyGTK program but do not activate it

I have a PyGTK program which is hidden most of the time, but with a keypress it shall come up as a popup. Therefore I want the program not to be activated when its opened. I tried several options to to that, with no success: self.window.show() self.window.set_focus(None) Activates the program, but sets no focus. self.wi...

Convert google search results into json in python 3.1

Hi, I am writing a Python program that feeds a search term to google using the google search API and downloads the first 10 results. I was able to do this in Python 2.6 as follows: query = urllib.parse.urlencode({'q' : 'searchterm','start' : k},doseq=false) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' \ ...

How to write a regular expression to match a string literal where the escape is a doubling of the quote character?

I am writing a parser using ply that needs to identify FORTRAN string literals. These are quoted with single quotes with the escape character being doubled single quotes. i.e. 'I don''t understand what you mean' is a valid escaped FORTRAN string. Ply takes input in regular expression. My attempt so far does not work and I don't unders...

Python indentation issue?

I'm pretty new to python. This is my first time working with classes in python. When I try to run this script, I get IndentationError: expected an indented block What is wrong with this? import random class Individual: alleles = (0,1) length = 5 string = "" def __init__(self): #some constructor work,...

csv.reader turning commas into periods throwing errors

Here is a sample of the first row: link,Title,Description,Keywords It is made from an excel workbook, I tried saving in all CSV formats (window, ms-dos, and comma delimited list) I even tried saving in 2 txt file formats (window, ms-dos) k... here is the code: csvReader = csv.reader(file('files/my_file.csv', "rU"), delimiter=',') ...

What's the easiest way to reproduce a randomly generated level in Python?

I'm making a game which uses procedurally generated levels, and when I'm testing I'll often want to reproduce a level. Right now I haven't made any way to save the levels, but I thought a simpler solution would be to just reuse the seed used by Python's random module. However I've tried using both random.seed() and random.setstate() and ...

Undefined variable from import when using wxPython in pydev

I just downloaded wxPython, and was running some of the sample programs from here. However, on every line that uses a variable from wx.*, I get a "Undefined variable from import error" For example, the following program generates five errors on lines 1,4,8, and two on line 5: import wx class MyFrame(wx.Frame): """ We simply derive ...

How do I get a content-type of a file in Python? (with url..)

Suppose I haev a video file: http://mydomain.com/thevideofile.mp4 How do I get the header and the content-type of this file? With Python. But , I don't want to download the entire file. i want it to return: video/mp4 Edit: this is what I did. What do you think? f = urllib2.urlopen(url) params['mime'] = f.headers['content-type'...

Database for web crawler in python?

Hi im writing a web crawler in python to extract news articles from news websites like nytimes.com. i want to know what would be a good db to use as a backend for this project? Thanks in advance! ...

Python DBUS SESSION_BUS - X11 dependency

I've got running sample python code which is fine in Ubuntu desktop: import dbus, gobject from dbus.mainloop.glib import DBusGMainLoop from dbus.mainloop.glib import threads_init import subprocess from subprocess import call gobject.threads_init() threads_init() dbus.mainloop.glib.DBusGMainLoop( set_as_default = True ) p = subprocess....