instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
What can you use Python generator functions for?
I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.
Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one...
How do I merge a 2D array in Python into one string with List Comprehension?
List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers. Say, I have a 2D list: li = [[0,1,2],[3,4,5],[6,7,8]] I would like to merge this either into one long list li2 = [0,1,2,3,4,5,6,7,8] or into a string with separators: s = "0,1,2,3,4,5,6,7,8" R...
Like so: [ item for innerlist in outerlist for item in innerlist ] Turning that directly into a string with separators: ','.join(str(item) for innerlist in outerlist for item in innerlist) Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at t...
How to generate all permutations of a list in Python
How do you generate all the permutations of a list in Python, independently of the type of elements in that list? For example: permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] EDIT: Eliben pointed to a so...
And in Python 2.6 onwards: import itertools itertools.permutations([1,2,3]) (returned as a generator. Use list(permutations(l)) to return as a list.)
What is "thread local storage" in Python, and why do I need it?
In Python specifically, how do variables get shared between threads? Although I have used threading.Thread before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to ...
In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, an...
Are locks unnecessary in multi-threaded Python code because of the GIL?
If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all? If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect? sorry if this is a dumb question...
You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code. For example: #!/usr/bin/env python import threading shared_balance = 0 class Deposit(threading.Thread): def run(self): for _ in xrange(1...
Making a beta code for a public django site
I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django. I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just tha...
Start with this Django snippet, but modify it to check request.session['has_beta_access']. If they don't have it, then have it return a redirect to a "enter beta code" page that, when posted to with the right code, sets that session variable to True. Making it a public beta then just consists of removing that middlewar...
How to bundle a Python application including dependencies?
I need to package my python application, its dependencies and python into a single MSI installer. The end result should desirably be: Python is installed in the standard location the package and its dependencies are installed in a separate directory (possibly site-packages) the installation directory should contain th...
Kind of a dup of this question about how to make a python into an executable. It boils down to: py2exe on windows, Freeze on Linux, and py2app on Mac.
Unit Testing File Modifications
A common task in programs I've been working on lately is modifying a text file in some way. (Hey, I'm on Linux. Everything's a file. And I do large-scale system admin.) But the file the code modifies may not exist on my desktop box. And I probably don't want to modify it if it IS on my desktop. I've read about unit tes...
You're talking about testing too much at once. If you start trying to attack a testing problem by saying "Let's verify that it modifies its environment correctly", you're doomed to failure. Environments have dozens, maybe even millions of potential variations. Instead, look at the pieces ("units") of your program. F...
How do you send a HEAD HTTP request in Python 2?
What I'm trying to do here is get the headers of a given URL so I can determine the MIME type. I want to be able to see if http://somedomain/foo/ will return an HTML document or a JPEG image for example. Thus, I need to figure out how to send a HEAD request so that I can read the MIME type without having to download th...
urllib2 can be used to perform a HEAD request. This is a little nicer than using httplib since urllib2 parses the URL for you instead of requiring you to split the URL into host name and path. >>> import urllib2 >>> class HeadRequest(urllib2.Request): ... def get_method(self): ... return "HEAD" ... >>> re...
Disable output buffering
Is output buffering enabled by default in Python's interpreter for sys.stdout? If the answer is positive, what are all the ways to disable it? Suggestions so far: Use the -u command line switch Wrap sys.stdout in an object that flushes after every write Set PYTHONUNBUFFERED env var sys.stdout = os.fdopen(sys.stdout.fi...
From Magnus Lycka answer on a mailing list: You can skip buffering for a whole python process using "python -u" (or#!/usr/bin/env python -u etc) or by setting the environment variable PYTHONUNBUFFERED. You could also replace sys.stdout with some other stream like wrapper which does a flush after every cal...
Union and Intersect in Django
class Tag(models.Model): name = models.CharField(maxlength=100) class Blog(models.Model): name = models.CharField(maxlength=100) tags = models.ManyToManyField(Tag) Simple models just to ask my question. I wonder how can i query blogs using tags in two different ways. Blog entries that are tagged with "tag1" o...
You could use Q objects for #1: # Blogs who have either hockey or django tags. from django.db.models import Q Blog.objects.filter( Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django') ) Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these. The...
Delete all data for a kind in Google App Engine
I would like to wipe out all data for a specific kind in Google App Engine. What is the best way to do this? I wrote a delete script (hack), but since there is so much data is timeout's out after a few hundred records.
I am currently deleting the entities by their key, and it seems to be faster. from google.appengine.ext import db class bulkdelete(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' try: while True: q = db.GqlQuery("SELECT __key__...
Python Music Library?
I'm looking at writing a little drum machine in Python for fun. I've googled some and found the python pages on music and basic audio as well as a StackOverflow question on generating audio files, but what I'm looking for is a decent library for music creation. Has anyone on here tried to do something like this befor...
Take a close look at cSounds. There are Python bindings allow you to do pretty flexible digital synthesis. There are some pretty complete packages available, too. See http://www.csounds.com/node/188 for a package. See http://www.csounds.com/journal/issue6/pythonOpcodes.html for information on Python scripting withi...
Is there something like 'autotest' for Python unittests?
Basically, growl notifications (or other callbacks) when tests break or pass. Does anything like this exist? If not, it should be pretty easy to write.. Easiest way would be to.. run python-autotest myfile1.py myfile2.py etc.py Check if files-to-be-monitored have been modified (possibly just if they've been saved). Ru...
I found autonose to be pretty unreliable but sniffer seems to work very well. $ pip install sniffer $ cd myproject Then instead of running "nosetests", you run: $ sniffer Or instead of nosetests --verbose --with-doctest, you run: $ sniffer -x--verbose -x--with-doctest As described in the readme, it's a good idea to ...
How to get instance variables in Python?
Is there a built-in method in Python to get an array of all a class' instance variables? For example, if I have this code: class hi: def __init__(self): self.ii = "foo" self.kk = "bar" Is there a way for me to do this: >>> mystery_method(hi) ["ii", "kk"] Thanks guys! Edit: I originally had asked for class v...
Every object has a __dict__ variable containing all the variables and its values in it. Try this >>> hi_obj = hi() >>> hi_obj.__dict__.keys()
Change the width of form elements created with ModelForm in Django
How can i change the width of a textarea form element if i used ModelForm to create it? Here is my product class: class ProductForm(ModelForm): long_desc = forms.CharField(widget=forms.Textarea) short_desc = forms.CharField(widget=forms.Textarea) class Meta: model = Product And the template code......
The easiest way for your use case is to use CSS. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS. Example for long_desc field in your ProductForm (when your form does not have a cust...
Is there an easy way to request a URL in python and NOT follow redirects?
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
Here is the Requests way: import requests r = requests.get('http://github.com', allow_redirects=False) print(r.status_code)
Dirty fields in django
In my app i need to save changed values (old and new) when model gets saved. Any examples or working code? I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.
I've found Armin's idea very useful. Here is my variation; class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) self._original_state = self._as_dict() def _as_dict(self): return dict([(f.name, getattr(self, f.name))...
Close a tkinter window?
How do I end a Tkinter program? Let's say I have this code: from Tkinter import * def quit(): # code to exit root = Tk() Button(root, text="Quit", command=quit).pack() root.mainloop() How should I define the quit function?
We can use: def quit(): root.quit() or def quit(): root.destroy()
How do I handle the window close event in Tkinter?
How do I handle the window close event (user clicking the 'X' button) in a Python Tkinter program?
Tkinter supports a mechanism called protocol handlers. Here, the term protocol refers to the interaction between the application and the window manager. The most commonly used protocol is called WM_DELETE_WINDOW, and is used to define what happens when the user explicitly closes a window using the window manager. You c...
What is a "callable" in Python?
Now that it's clear what a metaclass is, there is an associated concept that I use all the time without knowing what it really means. I suppose everybody made once a mistake with parenthesis, resulting in an "object is not callable" exception. What's more, using __init__ and __new__ lead to wonder what this bloody __...
A callable is anything that can be called. The built-in callable (PyCallable_Check in objects.c) checks if the argument is either: an instance of a class with a __call__ method or is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.) The...
Is there any way to do HTTP PUT in python
I need to upload some data to a server using HTTP PUT in python. From my brief reading of the urllib2 docs, it only does HTTP POST. Is there any way to do an HTTP PUT in python?
I've used a variety of python HTTP libs in the past, and I've settled on 'Requests' as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like: payload = {'username': 'bob', 'email': 'bob@bob.com'} >>> r = requ...
Using Python's ftplib to get a directory listing, portably
You can use ftplib for full FTP support in Python. However the preferred way of getting a directory listing is: # File: ftplib-example-1.py import ftplib ftp = ftplib.FTP("www.python.org") ftp.login("anonymous", "ftplib-example-1") data = [] ftp.dir(data.append) ftp.quit() for line in data: print "-", line W...
Try to use ftp.nlst(dir). However, note that if the folder is empty, it might throw an error: files = [] try: files = ftp.nlst() except ftplib.error_perm, resp: if str(resp) == "550 No files found": print "No files in this directory" else: raise for f in files: print f
python.array versus numpy.array
If you are creating a 1d array in Python is there any benefit to using the NumPy package?
It all depends on what you plan to do with the array. If all you're doing is creating arrays of simple data types and doing I/O, the array module will do just fine. If, on the other hand, you want to do any kind of numerical calculations, the array module doesn't provide any help with that. NumPy (and SciPy) give you a...
py2exe - generate single executable file
I thought I heard that py2exe was able to do this, but I never figured it out. Has anyone successfully done this? Can I see your setup.py file, and what command line options you used? Basically I'm thinking of it giving me a single executable file that does something like unzips itself to maybe /temp and runs.
The way to do this using py2exe is to use the bundle_files option in your setup.py file. For a single file you will want to set bundle_files to 1, compressed to True, and set the zipfile option to None. That way it creates one compressed file for easy distribution. Here is a more complete description of the bundle_file...
Python - When to use file vs open
What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)
You should always use open(). As the documentation states: When opening a file, it's preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing "isinstance(f, file)"). Also, file() has been removed since Python 3.0.
Is there a function in Python to split a string without ignoring the spaces?
Is there a function in Python to split a string without ignoring the spaces in the resulting list? E.g: s="This is the string I want to split".split() gives me >>> s ['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split'] I want something like ['This',' ','is',' ', 'the',' ','string', ' ', .....]
>>> import re >>> re.split(r"(\s+)", "This is the string I want to split") ['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split'] Using the capturing parentheses in re.split() causes the function to return the separators as well.
Is there a function in python to split a word into a list?
Is there a function in python to split a word into a list of single letters? e.g: s="Word to Split" to get wordlist=['W','o','r','d','','t','o' ....]
>>> list("Word to Split") ['W', 'o', 'r', 'd', ' ', 't', 'o', ' ', 'S', 'p', 'l', 'i', 't']
Deploying Django: How do you do it?
I have tried following guides like this one but it just didnt work for me. So my question is this: What is a good guide for deploying Django, and how do you deploy your Django. I keep hearing that capastrano is pretty nifty to use, but i have no idea as to how to work it or what it does (apart from automation of deploy...
mod_wsgi in combination with a virtualenv for all the dependencies, a mercurial checkout into the virtualenv and a fabric recipe to check out the changes on the server. I wrote an article about my usual workflow: Deploying Python Web Applications. Hope that helps.
Class method differences in Python: bound, unbound and static
What is the difference between the following class methods? Is it that one is static and the other is not? class Test(object): def method_one(self): print "Called method_one" def method_two(): print "Called method_two" a_test = Test() a_test.method_one() a_test.method_two()
In Python, there is a distinction between bound and unbound methods. Basically, a call to a member function (like method_one), a bound function a_test.method_one() is translated to Test.method_one(a_test) i.e. a call to an unbound method. Because of that, a call to your version of method_two will fail with a TypeErr...
Is a Python dictionary an example of a hash table?
One of the basic data structures in Python is the dictionary, which allows one to record "keys" for looking up "values" of any type. Is this implemented internally as a hash table? If not, what is it?
Yes, it is a hash mapping or hash table. You can read a description of python's dict implementation, as written by Tim Peters, here. That's why you can't use something 'not hashable' as a dict key, like a list: >>> a = {} >>> b = ['some', 'list'] >>> hash(b) Traceback (most recent call last): File "<stdin>", line 1, ...
How can I consume a WSDL (SOAP) web service in Python?
I want to use a WSDL SOAP based web service in Python. I have looked at the Dive Into Python code but the SOAPpy module does not work under Python 2.5. I have tried using suds which works partly, but breaks with certain types (suds.TypeNotFound: Type not found: 'item'). I have also looked at Client but this does not ap...
I would recommend that you have a look at SUDS "Suds is a lightweight SOAP python client for consuming Web Services."
How do I configure the ip address with CherryPy?
I'm using python and CherryPy to create a simple internal website that about 2 people use. I use the built in webserver with CherryPy.quickstart and never messed with the config files. I recently changed machines so I installed the latest Python and cherrypy and when I run the site I can access it from localhost:8080 b...
server.socket_host: '0.0.0.0' ...would also work. That's IPv4 INADDR_ANY, which means, "listen on all interfaces". In a config file, the syntax is: [global] server.socket_host: '0.0.0.0' In code: cherrypy.server.socket_host = '0.0.0.0'
Using Pylint with Django
I would very much like to integrate pylint into the build process for my python projects, but I have run into one show-stopper: One of the error types that I find extremely useful--:E1101: *%s %r has no %r member*--constantly reports errors when using common django fields, for example: E1101:125:get_user_tags: Class '...
I use the following: pylint --generated-members=objects
How can I search a word in a Word 2007 .docx file?
I'd like to search a Word 2007 file (.docx) for a text string, e.g., "some special phrase" that could/would be found from a search within Word. Is there a way from Python to see the text? I have no interest in formatting - I just want to classify documents as having or not having "some special phrase".
After reading your post above, I made a 100% native Python docx module to solve this specific problem. # Import the module from docx import * # Open the .docx file document = opendocx('A document.docx') # Search returns true if found search(document,'your search string') The docx module is at https://python-docx...
How do you create an osx application/dmg from a python package?
I want to create a mac osx application from python package and then put it in a disk image. Because I load some resources out of the package, the package should not reside in a zip file. The resulting disk image should display the background picture to "drag here -> applications" for installation.
I don't know the correct way to do it, but this manual method is the approach I've used for simple scripts which seems to have preformed suitably. I'll assume that whatever directory I'm in, the Python files for my program are in the relative src/ directory, and that the file I want to execute (which has the proper she...
How to Retrieve name of current Windows User (AD or local) using Python?
How can I retrieve the name of the currently logged in user, using a python script? The function should work regardless of whether it is a domain/ad user or a local user.
Try this: import os; print os.environ.get( "USERNAME" ) That should do the job.
How do I get a decimal value when using the division operator in Python?
For example, the standard division symbol '/' rounds to zero: >>> 4 / 100 0 However, I want it to return 0.04. What do I use?
There are three options: >>> 4 / float(100) 0.04 >>> 4 / 100.0 0.04 which is the same behavior as the C, C++, Java etc, or >>> from __future__ import division >>> 4 / 100 0.04 You can also activate this behavior by passing the argument -Qnew to the Python interpreter: $ python -Qnew >>> 4 / 100 0.04 The second opti...
How do I use timezones with a datetime object in python?
How do I properly represent a different timezone in my timezone? The below example only works because I know that EDT is one hour ahead of me, so I can uncomment the subtraction of myTimeZone() import datetime, re from datetime import tzinfo class myTimeZone(tzinfo): """docstring for myTimeZone""" def utfoffse...
I recommend babel and pytz when working with timezones. Keep your internal datetime objects naive and in UTC and convert to your timezone for formatting only. The reason why you probably want naive objects (objects without timezone information) is that many libraries and database adapters have no idea about timezones...
How can i parse a comma delimited string into a list (caveat)?
I need to be able to take a string like: '''foo, bar, "one, two", three four''' into: ['foo', 'bar', 'one, two', 'three four'] I have an feeling (with hints from #python) that the solution is going to involve the shlex module.
It depends how complicated you want to get... do you want to allow more than one type of quoting. How about escaped quotes? Your syntax looks very much like the common CSV file format, which is supported by the Python standard library: import csv reader = csv.reader(['''foo, bar, "one, two", three four'''], skipinitia...
How to start IDLE (Python editor) without using the shortcut on Windows Vista?
I'm trying to teach Komodo to fire up IDLE when I hit the right keystrokes. I can use the exact path of the shortcut in start menu in the Windows Explorer location bar to launch IDLE so I was hoping Komodo would be able to use it as well. But, giving this path to Komodo causes it to say that 1 is returned. This appe...
There's a file called idle.py in your Python installation directory in Lib\idlelib\idle.py If you run that file with Python, then IDLE should start. c:\Python25\pythonw.exe c:\Python25\Lib\idlelib\idle.py
How do you use the ellipsis slicing syntax in Python?
This came up in Hidden features of Python, but I can't see good documentation or examples that explain how the feature works.
The ellipsis is used to slice higher-dimensional data structures. It's designed to mean at this point, insert as many full slices (:) to extend the multi-dimensional slice to all dimensions. Example: >>> from numpy import arange >>> a = arange(16).reshape(2,2,2,2) Now, you have a 4-dimensional matrix of order 2x2x2x2...
Is there a way to convert indentation in Python code to braces?
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and...
There's a solution to your problem that is distributed with python itself. pindent.py, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have grab it from svn.python.org if you are running on Linux or OSX. It adds comments when blocks are...
Iron python, beautiful soup, win32 app
Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was a...
How do I uninstall python from OSX Leopard so that I can use the MacPorts version?
I want to use the macports version of python instead of the one that comes with Leopard.
Don't. Apple ships various system utilities that rely on the system Python (and particularly the Python "framework" build); removing it will cause you problems. Instead, modify your PATH environ variable in your ~/.bash_profile to put /opt/local/bin first.
Adding code to __init__.py
I'm taking a look at how the model system in django works and I noticed something that I don't understand. I know that you create an empty __init__.py file to specify that the current directory is a package. And that you can set some variable in __init__.py so that import * works properly. But django adds a bunch of f...
All imports in __init__.py are made available when you import the package (directory) that contains it. Example: ./dir/__init__.py: import something ./test.py: import dir # can now use dir.something EDIT: forgot to mention, the code in __init__.py runs the first time you import any module from that directory. So it's...
time length of an mp3 file
What is the simplest way to determine the length (in seconds) of a given mp3 file, without using outside libraries? (python source highly appreciated)
You can use pymad. It's an external library, but don't fall for the Not Invented Here trap. Any particular reason you don't want any external libraries? import mad mf = mad.MadFile("foo.mp3") track_length_in_milliseconds = mf.total_time() Spotted here. -- If you really don't want to use an external library, have a ...
Tabs versus spaces in Python programming
I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes. How does that make a difference? Are there other reasons why one would use spaces in...
Tired of chasing after indentation typos ( 8 spaces ? no, 7 oops 9 ... ) I switched my sources to 'tabs only'. 1 tab == 1 indent level, full stop The point is: if you want to display the indentation as 4, 8 or pi / 12 character width, just change the settings in your text editor, don't mess with the code :p (personally...
Parse DICOM files in native Python
What is the simplest and most-pythonic way to parse a DICOM file? A native Python implementation without the use of non-Python libraries would be much preferred. DICOM is the standard file format in digital medical imaging (look here for more information). There are some C/C++ libraries that support reading (a subset)...
I'm using pydicom heavily these days, and it rocks. It's pretty easy to start playing with it: import dicom data = dicom.read_file("yourdicomfile.dcm") To get the interesting stuff out of that "data" object, somehow resembling dcmdump output: for key in data.dir(): value = getattr(data, key, '') if t...
Using **kwargs with SimpleXMLRPCServer in python
I have a class that I wish to expose as a remote service using pythons SimpleXMLRPCServer. The server startup looks like this: server = SimpleXMLRPCServer((serverSettings.LISTEN_IP,serverSettings.LISTEN_PORT)) service = Service() server.register_instance(service) server.serve_forever() I then have a ServiceRemote cl...
You can't do this with plain xmlrpc since it has no notion of keyword arguments. However, you can superimpose this as a protocol on top of xmlrpc that would always pass a list as first argument, and a dictionary as a second, and then provide the proper support code so this becomes transparent for your usage, example be...
Fetch a Wikipedia article with Python
I try to fetch a Wikipedia article with Python's urllib: f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes") s = f.read() f.close() However instead of the html page I get the following response: Error - Wikimedia Foundation: Request: GET http://en.wikipedia.org/w/in...
You need to use the urllib2 that superseedes urllib in the python std library in order to change the user agent. Straight from the examples import urllib2 opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] infile = opener.open('http://en.wikipedia.org/w/index.php?title=Albert_Einstein&p...
SVG rendering in a PyGame application
In a pyGame application, I would like to render resolution-free GUI widgets described in SVG. What tool and/or library can I use to reach this goal ? (I like the OCEMP GUI toolkit but it seems to be bitmap dependent for its rendering)
This is a complete example which combines hints by other people here. It should render a file called test.svg from the current directory. It was tested on Ubuntu 10.10, python-cairo 1.8.8, python-pygame 1.9.1, python-rsvg 2.30.0. #!/usr/bin/python import array import math import cairo import pygame import rsvg WIDT...
Directory listing in Python
How do I get a list of all files (and directories) in a given directory in Python?
This is a way to traverse every file and directory in a directory tree: import os for dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in file...
Why does Python pep-8 strongly recommend spaces over tabs for indentation?
I see on Stack Overflow and PEP 8 that the recommendation is to use spaces only for indentation in Python programs. I can understand the need for consistent indentation and I have felt that pain. Is there an underlying reason for spaces to be preferred? I would have thought that tabs were far easier to work with.
The answer was given right there in the PEP [ed: this passage has been edited out in 2013]. I quote: The most popular way of indenting Python is with spaces only. What other underlying reason do you need? To put it less bluntly: Consider also the scope of the PEP as stated in the very first paragraph: This document ...
How can I normalize a URL in python
I'd like to know do I normalize a URL in python. For example, If I have a url string like : "http://www.example.com/foo goo/bar.html" I need a library in python that will transform the extra space (or any other non normalized character) to a proper URL.
Have a look at this module: werkzeug.utils. (now in werkzeug.urls) The function you are looking for is called "url_fix" and works like this: >>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffsklärung)') 'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29' It's implemented in Werkzeug as follows: impor...
Accessing object memory address
When you call the object.__repr__() method in python you get something like this back: <__main__.Test object at 0x2aba1c0cf890>, is there any way to get a hold of the memory address if you overload __repr__(), other then calling super(Class, obj).__repr__() and regexing it out?
The Python manual has this to say about id(): Return the ``identity'' of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value. (Implementation note: this i...
How do I include a stacktrace in my Django 500.html page?
I'm running Django 1.0 and I'm close to deploying my app. As such, I'll be changing the DEBUG setting to False. With that being said, I'd still like to include the stacktrace on my 500.html page when errors occur. By doing so, users can copy-and-paste the errors and easily email them to the developers. Any thoughts o...
Automatically log your 500s, that way: You know when they occur. You don't need to rely on users sending you stacktraces. Joel recommends even going so far as automatically creating tickets in your bug tracker when your application experiences a failure. Personally, I create a (private) RSS feed with the stacktraces,...
How do you translate this regular-expression idiom from Perl into Python?
I switched from Perl to Python about a year ago and haven't looked back. There is only one idiom that I've ever found I can do more easily in Perl than in Python: if ($var =~ /foo(.+)/) { # do something with $1 } elsif ($var =~ /bar(.+)/) { # do something with $1 } elsif ($var =~ /baz(.+)/) { # do something with...
Using named groups and a dispatch table: r = re.compile(r'(?P<cmd>foo|bar|baz)(?P<data>.+)') def do_foo(data): ... def do_bar(data): ... def do_baz(data): ... dispatch = { 'foo': do_foo, 'bar': do_bar, 'baz': do_baz, } m = r.match(var) if m: dispatch[m.group('cmd')](m.group('data')) W...
How do I find the location of my Python site-packages directory?
How do I find the location of my site-packages directory?
>>> import site; site.getsitepackages() ['/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] (or just first item with site.getsitepackages()[0])
How do I copy a file in python?
How do I copy a file in Python? I couldn't find anything under os.
shutil has many methods you can use. One of which is: from shutil import copyfile copyfile(src, dst) Copy the contents of the file named src to a file named dst. The destination location must be writable; otherwise, an IOError exception will be raised. If dst already exists, it will be replaced. Special files such as...
What is the intended use of the DEFAULT section in config files used by ConfigParser?
I've used ConfigParser for quite a while for simple configs. One thing that's bugged me for a long time is the DEFAULT section. I'm not really sure what's an appropriate use. I've read the documentation, but I would really like to see some clever examples of its use and how it affects other sections in the file (someth...
I found an explanation here by googling for "windows ini" "default section". Summary: whatever you put in the [DEFAULT] section gets propagated to every other section. Using the example from the linked website, let's say I have a config file called test1.ini: [host 1] lh_server=192.168.0.1 vh_hosts = PloneSite1:8080 ...
extracting text from MS word files in python
for working with MS word files in python, there is python win32 extensions, which can be used in windows. How do I do the same in linux? Is there any library?
Use the native Python docx module. Here's how to extract all the text from a doc: document = docx.Document(filename) docText = '\n\n'.join([ paragraph.text.encode('utf-8') for paragraph in document.paragraphs ]) print docText See Python DocX site Also check out Textract which pulls out tables etc. Parsing XML wit...
How do I modify a text file in Python?
I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it. This is an operating system thing, not a Python...
Python library for rendering HTML and javascript
Is there any python module for rendering a HTML page with javascript and get back a DOM object? I want to parse a page which generates almost all of its content using javascript.
The big complication here is emulating the full browser environment outside of a browser. You can use stand alone javascript interpreters like Rhino and SpiderMonkey to run javascript code but they don't provide a complete browser like environment to full render a web page. If I needed to solve a problem like this I wo...
Iterate a list with indexes in Python
I could swear I've seen the function (or method) that takes a list, like this [3, 7, 19] and makes it into iterable list of tuples, like so: [(0,3), (1,7), (2,19)] to use it instead of: for i in range(len(name_of_list)): name_of_list[i] = something but I can't remember the name and googling "iterate list" gets not...
>>> a = [3,4,5,6] >>> for i, val in enumerate(a): ... print i, val ... 0 3 1 4 2 5 3 6 >>>
Find out number of capture groups in Python regular expressions
Is there a way to determine how many capture groups there are in a given regular expression? I would like to be able to do the follwing: def groups(regexp, s): """ Returns the first result of re.findall, or an empty default >>> groups(r'(\d)(\d)(\d)', '123') ('1', '2', '3') >>> groups(r'(\d)(\d)(\d)', ...
def num_groups(regex): return re.compile(regex).groups
How to parse an ISO 8601-formatted date in Python?
I need to parse RFC 3339 strings like "2008-09-03T20:56:35.450686Z" into Python's datetime type. I have found strptime in the Python standard library, but it is not very convenient. What is the best way to do this?
The python-dateutil package can parse not only RFC 3339 datetime strings like the one in the question, but also other ISO 8601 date and time strings that don't comply with RFC 3339 (such as ones with no UTC offset, or ones that represent only a date). >>> import dateutil.parser >>> dateutil.parser.parse('2008-09-03T20...
Should Python import statements always be at the top of a module?
PEP 08 states: Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants. However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed? Isn't this: class S...
Module importing is quite fast, but not instant. This means that: Putting the imports at the top of the module is fine, because it's a trivial cost that's only paid once. Putting the imports within a function will cause calls to that function to take longer. So if you care about efficiency, put the imports at the top...
Using property() on classmethods
I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() function with these, but it results in an error. I was able to reproduce the error with the following in the interpreter: >>> class foo(object): ... ...
Reading the Python 2.2 release notes, I find the following. The get method [of a property] won't be called when the property is accessed as a class attribute (C.x) instead of as an instance attribute (C().x). If you want to override the __get__ operation for properties when used as a class attribute, you c...
Generic Exception Handling in Python the "Right Way"
Sometimes I find myself in the situation where I want to execute several sequential commands like such: try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... This same pattern occurs when exceptions simply need to be ignored. This feels redundant and the excessive sy...
You could use the with statement if you have python 2.5 from __future__ import with_statement import contextlib @contextlib.contextmanager def handler(): try: yield except Exception, e: baz(e) Your example now becomes: with handler(): foo(a, b) with handler(): bar(c, d)
How do you test that a Python function throws an exception?
How does one write a unittest that fails only if a function doesn't throw an expected exception?
Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example: import mymod class MyTestCase(unittest.TestCase): def test1(self): self.assertRaises(SomeCoolException, mymod.myfunc)
Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch?
python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring: time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert...
There is actually an inverse function, but for some bizarre reason, it's in the calendar module: calendar.timegm(). I listed the functions in this answer.
How do I efficiently filter computed values within a Python list comprehension?
The Python list comprehension syntax makes it easy to filter values within a comprehension. For example: result = [x**2 for x in mylist if type(x) is int] Will return a list of the squares of integers in mylist. However, what if the test involves some (costly) computation and you want to filter on the result? One o...
Came up with my own answer after a minute of thought. It can be done with nested comprehensions: result = [y for y in (expensive(x) for x in mylist) if y] I guess that works, though I find nested comprehensions are only marginally readable
Python Date Comparisons
I would like to find out if a particular python datetime object is older than X hours or minutes. I am trying to do something similar to: if (datetime.now() - self.timestamp) > 100 # Where 100 is either seconds or minutes This generates a type error. What is the proper way to do date time comparison in python? I al...
Use the datetime.timedelta class: >>> from datetime import datetime, timedelta >>> then = datetime.now() - timedelta(hours = 2) >>> now = datetime.now() >>> (now - then) > timedelta(days = 1) False >>> (now - then) > timedelta(hours = 1) True Your example could be written as: if (datetime.now() - self.timestamp) > tim...
Request UAC elevation from within a Python script?
I want my Python script to copy files on Vista. When I run it from a normal cmd.exe window, no errors are generated, yet the files are NOT copied. If I run cmd.exe "as administator" and then run my script, it works fine. This makes sense since User Account Control (UAC) normally prevents many file system actions. Is th...
It took me a little while to get dguaraglia's answer working, so in the interest of saving others time, here's what I did to implement this idea: import os import sys import win32com.shell.shell as shell ASADMIN = 'asadmin' if sys.argv[-1] != ASADMIN: script = os.path.abspath(sys.argv[0]) params = ' '.join([sc...
Showing the stack trace from a running Python application
I have this Python application that gets stuck from time to time and I can't find out where. Is there any way to signal Python interpreter to show you the exact code that's running? Some kind of on-the-fly stacktrace? Related questions: Print current call stack from a method in Python code Check what a running proces...
I have module I use for situations like this - where a process will be running for a long time but gets stuck sometimes for unknown and irreproducible reasons. Its a bit hacky, and only works on unix (requires signals): import code, traceback, signal def debug(sig, frame): """Interrupt running process, and provid...
Is there a difference between `==` and `is` in Python?
My Google-fu has failed me. In Python, are the following two tests for equality equivalent (ha!)? n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' Does this hold true for objects where you would be comparing instances (a list say)? Okay, so this kind of answers my question: L = []...
is will return True if two variables point to the same object, == if the objects referred to by the variables are equal. >>> a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True >>> b = a[:] >>> b is a False >>> b == a True In your case, the second test only works because Python caches small integer objects, which...
Efficiently match multiple regexes in Python
Lexical analyzers are quite easy to write when you have regexes. Today I wanted to write a simple general analyzer in Python, and came up with: import re import sys class Token(object): """ A simple Token structure. Contains the token type, value and position. """ def __init__(self, type, val, pos...
I suggest using the re.Scanner class, it's not documented in the standard library, but it's well worth using. Here's an example: import re scanner = re.Scanner([ (r"-?[0-9]+\.[0-9]+([eE]-?[0-9]+)?", lambda scanner, token: float(token)), (r"-?[0-9]+", lambda scanner, token: int(token)), (r" +", lambda scann...
Which is more preferable to use in Python: lambda functions or nested functions ('def')?
I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. Here are some trivial examples where they functionally do the same thing if either were found within another function: Lambda function >>> a = lambda x : 1 + x >>> a(5) 6 Nested function >>> def b(x): return 1 + x...
If you need to assign the lambda to a name, use a def instead. defs are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable. lambdas can be used for use once, throw away functions which won't have a name. However, this use case is very rare. You rarely need t...
Display number with leading zeros
Given: a = 1 b = 10 c = 100 I want to display a leading zero for all numbers with less than 2 digits, i.e.: 01 10 100
Here you are: print "%02d" % (1,) Basically % is like printf or sprint.
Python Library Path
In ruby the library path is provided in $:, in perl it's in @INC - how do you get the list of paths that Python searches for modules when you do an import?
I think you're looking for sys.path import sys print (sys.path)
Should you always favor xrange() over range()?
Why or why not?
For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range(): In python 3, range() does what xrange() used to do and xrange() does not exist. If you want to write code that will run on both Python 2 and Python 3, y...
How many bytes per element are there in a Python list (tuple)?
For example, how much memory is required to store a list of one million (32-bit) integers? alist = range(1000000) # or list(range(1000000)) in Python 3.0
"It depends." Python allocates space for lists in such a way as to achieve amortized constant time for appending elements to the list. In practice, what this means with the current implementation is... the list always has space allocated for a power-of-two number of elements. So range(1000000) will actually allocate ...
Python: SWIG vs ctypes
In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). What are the performance metrics of the two?
I have a rich experience of using swig. SWIG claims that it is rapid solution for wrapping things. But in the real life... Cons: SWIG is developed to be general, for everyone and for 20+ languages. Generally it leads to drawbacks: - needs configuration (SWIG .i templates), sometimes it is tricky, - lack of treatment o...
Python web development - with or without a framework
I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface. I did not use a fra...
The command-line Python, IMO, definitely comes first. Get that to work, since that's the core of what you're doing. The issue is that using a web framework's ORM from a command line application isn't obvious. Django provides specific instructions for using their ORM from a command-line app. Those are annoying at fir...
What is the difference between @staticmethod and @classmethod in Python?
What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?
Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo: class A(object): def foo(self,x): print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(cls,x): print "executing class_foo(%s,%s)"%(cls,x) @staticmethod ...
Get last n lines of a file with Python, similar to tail
I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom. So I need a tail() method that can read n lines from the bottom and supports an offset. What I came up with looks like this: d...
This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it's found the right number of '\n' characters. def tail( f, lines=20 ): total_lines_wanted = lines BLOCK_SIZE = 1024 f.seek(0, 2) block_end_byte = f.tell() lines_to_go = total_...
Key Presses in Python
Is it possible to make it appear to a system that a key was pressed, for example I need to make A key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python. A better way to put it, I need to em...
Install the pywin32 extensions. Then you can do the following: import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.AppActivate("Notepad") # select another application wsh.SendKeys("a") # send the keys you want Search for documentation of the WScript.Shell object (I believe installed by default i...
Is there something like Python's getattr() in C#?
Is there something like Python's getattr() in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.
There is also Type.InvokeMember. public static class ReflectionExt { public static object GetAttr(this object obj, string name) { Type type = obj.GetType(); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | Bind...
How can I read the RGB value of a given pixel in Python?
If I open an image with open("image.jpg"), how can I get the RGB values of a pixel, if I have the coordinates of the pixel? Then how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value? It would be so much better if I didn't have to download any additional libraries.
It's probably best to use the Python Image Library to do this which I'm afraid is a separate download. The easiest way to do what you want is via the load() method on the Image object which returns a pixel access object which you can manipulate like an array: from PIL import Image im = Image.open("dead_parrot.jpg") #Ca...
Pure Python XSLT library
Is there an XSLT library that is pure Python? Installing libxml2+libxslt or any similar C libraries is a problem on some of the platforms I need to support. I really only need basic XSLT support, and speed is not a major issue.
Unfortunately there are no pure-python XSLT processors at the moment. If you need something that is more platform independent, you may want to use a Java-based XSLT processor like Saxon. 4Suite is working on a pure-python XPath parser, but it doesn't look like a pure XSLT processor will be out for some time. Perhaps it...
Is it feasible to compile Python to machine code?
How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code? Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too. Also, you would need to bun...
As @Greg Hewgill says it, there are good reasons why this is not always possible. However, certain kinds of code (like very algorithmic code) can be turned into "real" machine code. There are several options: Use Psyco, which emits machine code dynamically. You should choose carefully which methods/functions to conve...
listing all functions in a python module
I have a python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. I want to call the doc function on each one. In ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in pytho...
You can use dir(module) to see all available methods/attributes. Also check out PyDocs.
Authenticating against active directory using python + ldap
How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears. I can't even bind to perform a simple query: import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.SCOPE_S...
I was missing l.set_option(ldap.OPT_REFERRALS, 0) From the init.
How to list only top level directories in Python?
I want to be able to list only the directories inside some folder. This means I don't want filenames listed, nor do I want additional sub-folders. Let's see if an example helps. In the current directory we have: >>> os.listdir(os.getcwd()) ['cx_Oracle-doc', 'DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'mod_p...
os.walk('.').next()[1]
How do I find what is using memory in a Python process in a production system?
My production system occasionally exhibits a memory leak I have not been able to reproduce in a development environment. I've used a Python memory profiler (specifically, Heapy) with some success in the development environment, but it can't help me with things I can't reproduce, and I'm reluctant to instrument our pro...
Using Python's gc garbage collector interface and sys.getsizeof() it's possible to dump all the python objects and their sizes. Here's the code I'm using in production to troubleshoot a memory leak: rss = psutil.Process(os.getpid()).get_memory_info().rss # Dump variables if using more than 100MB of memory if rss > 100 ...
How do I wrap a string in a file in Python?
How do I create a file-like object (same duck type as File) with the contents of a string?
Use the StringIO module. For example: >>> from cStringIO import StringIO >>> f = StringIO('foo') >>> f.read() 'foo' I use cStringIO (which is faster), but note that it doesn't accept Unicode strings that cannot be encoded as plain ASCII strings. (You can switch to StringIO by changing "from cStringIO" to "from Stri...
Is there an easy way to populate SlugField from CharField?
class Foo(models.Model): title = models.CharField(max_length=20) slug = models.SlugField() Is there a built-in way to get the slug field to autopopulate based on the title? Perhaps in the Admin and outside of the Admin.
for Admin in Django 1.0 and up, you'd need to use prepopulated_fields = {'slug': ('title',), } in your admin.py Your key in the prepopulated_fields dictionary is the field you want filled, and the value is a tuple of fields you want concatenated. Outside of admin, you can use the slugify function in your views. In tem...
overloading __init__ in python
Let's say I have a class that has a member called data which is a list. I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list. What's your technique for doing this? Do you just check the type by looking at __class__? Is there some t...
A much neater way to get 'alternate constructors' is to use classmethods. For instance: >>> class MyData: ... def __init__(self, data): ... "Initialize MyData from a sequence" ... self.data = data ... ... @classmethod ... def fromfilename(cls, filename): ... "Initialize MyData f...
What limitations have closures in Python compared to language X closures?
Where X is any programming language (C#, Javascript, Lisp, Perl, Ruby, Scheme, etc) which supports some flavour of closures. Some limitations are mentioned in the Closures in Python (compared to Ruby's closures), but the article is old and many limitations do not exist in modern Python any more. Seeing a code example...
The most important limitation, currently, is that you cannot assign to an outer-scope variable. In other words, closures are read-only: >>> def outer(x): ... def inner_reads(): ... # Will return outer's 'x'. ... return x ... def inner_writes(y): ... # Will assign to a local 'x', not the...