instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
How can I find the full path to a font from its display name on a Mac?
I am using the Photoshop's javascript API to find the fonts in a given PSD. Given a font name returned by the API, I want to find the actual physical font file that that font name corresponds to on the disc. This is all happening in a python program running on OSX so I guess I'm looking for one of: Some Photoshop java...
Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef. Cocoa doesn't have any native support,...
Get a preview JPEG of a PDF on Windows?
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF. On the Mac I am spawning sips. Is there something similarly simple I can do on Windows?
ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the ps:alpha delegate in ImageMagick, just adjusted to use JPEG as output): gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \ -dMaxBitmap=500000000 -dLastPage=1 ...
Continuous Integration System for a Python Codebase
I'm starting work on a hobby project with a python codebase and would like to set up some form of continuous integration (i.e. running a battery of test-cases each time a check-in is made and sending nag e-mails to responsible persons when the tests fail) similar to CruiseControl or TeamCity. I realize I could do this ...
One possibility is Hudson. It's written in Java, but there's integration with Python projects: Hudson embraces Python I've never tried it myself, however. (Update, Sept. 2011: After a trademark dispute Hudson has been renamed to Jenkins.)
cx_Oracle: How do I iterate over a result set?
There are several ways to iterate over a result set. What are the tradeoff of each?
The canonical way is to use the built-in cursor iterator. curs.execute('select * from people') for row in curs: print row You can use fetchall() to get all rows at once. for row in curs.fetchall(): print row It can be convenient to use this to create a Python list containing the values returned: curs.execute...
Using 'in' to match an attribute of Python objects in an array
I don't remember whether I was dreaming or not but I seem to recall there being a function which allowed something like, foo in iter_attr(array of python objects, attribute name) I've looked over the docs but this kind of thing doesn't fall under any obvious listed headers
Using a list comprehension would build a temporary list, which could eat all your memory if the sequence being searched is large. Even if the sequence is not large, building the list means iterating over the whole of the sequence before in could start its search. The temporary list can be avoiding by using a generator ...
Class views in Django
Django view points to a function, which can be a problem if you want to change only a bit of functionality. Yes, I could have million keyword arguments and even more if statements in the function, but I was thinking more of an object oriented approach. For example, I have a page that displays a user. This page is very ...
I've created and used my own generic view classes, defining __call__ so an instance of the class is callable. I really like it; while Django's generic views allow some customization through keyword arguments, OO generic views (if their behavior is split into a number of separate methods) can have much more fine-graine...
Python and MySQL
I can get Python to work with Postgresql but I cannot get it to work with MySQL. The main problem is that on the shared hosting account I have I do not have the ability to install things such as Django or PySQL, I generally fail when installing them on my computer so maybe it's good I can't install on the host. I found...
MySQLdb is what I have used before. If you host is using Python version 2.5 or higher, support for sqlite3 databases is built in (sqlite allows you to have a relational database that is simply a file in your filesystem). But buyer beware, sqlite is not suited for production, so it may depend what you are trying to do ...
How do I use Python's itertools.groupby()?
I haven't been able to find an understandable explanation of how to actually use Python's itertools.groupby() function. What I'm trying to do is this: Take a list - in this case, the children of an objectified lxml element Divide it into groups based on some criteria Then later iterate over each of these groups separ...
As Sebastjan said, you first have to sort your data. This is important. The part I didn't get is that in the example construction groups = [] uniquekeys = [] for k, g in groupby(data, keyfunc): groups.append(list(g)) # Store group iterator as a list uniquekeys.append(k) k is the current grouping key, and g is...
Adding a Method to an Existing Object Instance
I've read that it is possible to add a method to an existing object (e.g. not in the class definition) in Python, I think this is called Monkey Patching (or in some cases Duck Punching). I understand that it's not always a good decision to do so. But, how might one do this? UPDATE 8/04/2008 00:21:01 EST: That looks lik...
In Python, there is a difference between functions and bound methods. >>> def foo(): ... print "foo" ... >>> class A: ... def bar( self ): ... print "bar" ... >>> a = A() >>> foo <function foo at 0x00A98D70> >>> a.bar <bound method A.bar of <__main__.A instance at 0x00A9BC88>> >>> Bound methods have be...
How do you express binary literals in Python?
How do you express an integer as a binary number with Python literals? I was easily able to find the answer for hex: >>> 0x12AF 4783 >>> 0x100 256 and octal: >>> 01267 695 >>> 0100 64 How do you use literals to express binary in Python? Summary of Answers Python 2.5 and earlier: can ...
For reference—future Python possibilities: Starting with Python 2.6 you can express binary literals using the prefix 0b or 0B: >>> 0b101111 47 You can also use the new bin function to get the binary representation of a number: >>> bin(173) '0b10101101' Development version of the documentation: What's New in Python 2....
Any experiences with Protocol Buffers?
I was just looking through some information about Google's protocol buffers data interchange format. Has anyone played around with the code or even created a project around it? I'm currently using XML in a Python project for structured content created by hand in a text editor, and I was wondering what the general opin...
Protocol buffers are intended to optimize communications between machines. They are really not intended for human interaction. Also, the format is binary, so it could not replace XML in that use case. I would also recommend JSON as being the most compact text-based format.
How do I make a menu that does not require the user to press [enter] to make a selection?
I've got a menu in Python. That part was easy. I'm using raw_input() to get the selection from the user. The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far: import sys ...
On Linux: set raw mode select and read the keystroke restore normal settings import sys import select import termios import tty def getkey(): old_settings = termios.tcgetattr(sys.stdin) tty.setraw(sys.stdin.fileno()) select.select([sys.stdin], [], [], 0) answer = sys.stdin.read(1) termios.tcseta...
How to check what OS am I running on in Python?
What do I need to look at to see if I'm on Windows, Unix, etc?
>>> import os >>> print os.name posix >>> import platform >>> platform.system() 'Linux' >>> platform.release() '2.6.22-15-generic' See: platform — Access to underlying platform’s identifying data
Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?
In many places, (1,2,3) and [1,2,3] can be used interchangeably. When should I use one or the other, and why?
From the Python FAQ: Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a...
File size differences after copying a file to a server vía FTP
I have created a PHP-script to update a webserver that is live inside a local directory. I'm migrating the script into Python. It works fine for the most part, but after a PUT command the size of the file appears to change. Thus, the size of the file is different from that of the file on the server. Once I download ag...
Do you need to open the locfile in binary using rb? f = open (locfile, "rb")
How can I create a directly-executable cross-platform GUI app using Python?
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux. The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the ...
First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables. Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac) Of course, there are many, but the most popular that I've seen in wild are: Tkinter -...
Calling a function of a module from a string with the function's name in Python
What is the best way to go about calling a function given a string with the function's name in a Python program. For example, let's say that I have a module foo, and I have a string whose contents are "bar". What is the best way to go about calling foo.bar()? I need to get the return value of the function, which is wh...
Assuming module foo with method bar: import foo methodToCall = getattr(foo, 'bar') result = methodToCall() As far as that goes, lines 2 and 3 can be compressed to: result = getattr(foo, 'bar')() if that makes more sense for your use case. You can use getattr in this fashion on class instance bound methods, module-le...
Programmatically talking to a Serial Port in OS X or Linux
I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . When i do this everything seems to be hunky...
/dev/cu.xxxxx is the "callout" device, it's what you use when you establish a connection to the serial device and start talking to it. /dev/tty.xxxxx is the "dialin" device, used for monitoring a port for incoming calls for e.g. a fax listener.
How do you set up Python scripts to work in Apache 2.0?
I tried to follow a couple of googled up tutorials on setting up mod_python, but failed every time. Do you have a good, step-by step, rock-solid howto? My dev box is OS X, production - Centos.
There are two main ways of running Python on Apache. The simplest would be to use CGI and write normal Python scripts while the second is using a web framework like Django or Pylons. Using CGI is straightforward. Make sure your Apache config file has a cgi-bin set up. If not, follow their documentation (http://httpd.ap...
Cross Platform, Language Agnostic GUI Markup Language?
I learned Swing back in the day but now I've moved to Python and want to make some apps with GUIs. I haven't had the time to learn a new GUI API so I've been using Jython, but I would prefer to use CPython. It would be great if I can have one simple markup that allows me to switch GUI libraries. It would be even bette...
erm.. HTML? (trying to be funny here... while we wait for real answers..)
Convert Bytes to Floating Point Numbers in Python
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
>>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
Python, Unicode, and the Windows console
When I try to print a Unicode string in a Windows console, I get a UnicodeEncodeError: 'charmap' codec can't encode character .... error. I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a ? ins...
Note: This answer is sort of outdated (from 2008). Please use the solution below with care!! Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance): PrintFails - Python Wiki Here's a code excerpt from that page: $ python -c 'import sys, codecs, locale...
Get size of a file before downloading in Python
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? import urllib import re url = "http://www.someurl.com" # Download the ...
I have reproduced what you are seeing: import urllib, oslink = "http://python.org"print "opening url:", linksite = urllib.urlopen(link)meta = site.info()print "Content-Length:", meta.getheaders("Content-Length")[0]f = open("out.txt", "r")print "File on disk:",len(f.read())f.close()f = open("out.txt", "w")f.write(site.r...
How to use Xpath in Python?
What is the library? Is there a full implementation? How is the library used? Where is its website?
libxml2 has a number of advantages: Compliance to the spec Active development and a community participation Speed. This is really a python wrapper around a C implementation. Ubiquity. The libxml2 library is pervasive and thus well tested. Downsides include: Compliance to the spec. It's strict. Things like default ...
Accessing mp3 Meta-Data with Python
What is the best way to retrieve mp3 metadata in python? I've seen a couple frameworks out there, but I'm unsure as to which would be the best to use.... Any ideas?
I used eyeD3 the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to download the tar and execute python setup.py install from the source folder. Relevant examples from the website are below. Reading the contents of an mp3 fi...
How should I unit test a code-generator?
This is a difficult and open-ended question I know, but I thought I'd throw it to the floor and see if anyone had any interesting suggestions. I have developed a code-generator that takes our python interface to our C++ code (generated via SWIG) and generates code needed to expose this as WebServices. When I developed...
I started writing up a summary of my experience with my own code generator, then went back and re-read your question and found you had already touched upon the same issues yourself, focus on the execution results instead of the code layout/look. Problem is, this is hard to test, the generated code might not be suited t...
Can you check that an exception is thrown with doctest in Python?
Is it possible to write a doctest unit test that will check that an exception is raised? For example, if I have a function foo(x) that is supposed to raise an exception if x<0, how would I write the doctest for that?
Yes. You can do it. The doctest module documentation and Wikipedia has an example of it. >>> x Traceback (most recent call last): ... NameError: name 'x' is not defined
Can you explain closures (as they relate to Python)?
I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.
Closure on closures Objects are data with methods attached, closures are functions with data attached. def make_counter(): i = 0 def counter(): # counter() is a closure nonlocal i i += 1 return i return counter c1 = make_counter() c2 = make_counter() print (c1(), c1(), c2(), ...
Python Sound ("Bell")
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use import os and then use a command line speech program to say "Process complete." I much rather it be a simple "bell." I know that there's a function that can be used in Cocoa apps, NSBeep, but I don't th...
Have you tried : import sys sys.stdout.write('\a') sys.stdout.flush() That works for me here on Mac OS 10.5 Actually, I think your original attempt works also with a little modification: print('\a') (You just need the single quotes around the character sequence).
Regex and unicode
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi) The script works fine, that is until you try and use it on files that have Unicode show-names (...
Use a subrange of [\u0000-\uFFFF] for what you want. You can also use the re.UNICODE compile flag. The docs say that if UNICODE is set, \w will match the characters [0-9_] plus whatever is classified as alphanumeric in the Unicode character properties database. See also http://coding.derkeiler.com/Archive/Python/comp....
How do I validate xml against a DTD file in Python
I need to validate an XML string (and not a file) against a DTD description file. How can that be done in python?
Another good option is lxml's validation which I find quite pleasant to use. A simple example taken from the lxml site: from StringIO import StringIO from lxml import etree dtd = etree.DTD(StringIO("""<!ELEMENT foo EMPTY>""")) root = etree.XML("<foo/>") print(dtd.validate(root)) # True root = etree.XML("<foo>bar</fo...
Prototyping with Python code before compiling
I have been mulling over writing a peak fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually. IIRC, one of Python's original remits was as a prototyping languag...
Finally a question that I can really put a value answer to :). I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown: Disclaimer: This is my pers...
Sanitising user input using Python
What's the best way to sanitise user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an XSS or SQL injection attack?
Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use onclick). It is a modified version of http://www.djangosnippets.org/snippets/205/, with the regex on the attribute values to prevent people from using href="javascript:...", and oth...
Create an encrypted ZIP file in Python
I'm creating an ZIP file with ZipFile in Python 2.5, it works ok so far: import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() but I couldn't find how to encrypt the files in the ZIP file. I could use system and call...
I created a simple library to create a password encrypted zip file in python. - here import pyminizip compression_level = 5 # 1-9 pyminizip.compress("src.txt", "dst.zip", "password", compression_level) The library requires zlib. I have checked that the file can be extracted in WINDOWS/MAC.
What's the best way to distribute python command-line tools?
My current setup.py script works okay, but it installs tvnamer.py (the tool) as "tvnamer.py" into site-packages or somewhere similar.. Can I make setup.py install tvnamer.py as tvnamer, and/or is there a better way of installing command-line applications?
Try the entry_points.console_scripts parameter in the setup() call. As described in the setuptools docs, this should do what I think you want. To reproduce here: from setuptools import setup setup( # other arguments here... entry_points = { 'console_scripts': [ 'foo = package.module:func', ...
Build a Basic Python Iterator
How would one create an iterative function (or iterator object) in python?
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: __iter__() and next(). The __iter__ returns the iterator object and is implicitly called at the start of loops. The next() method returns the next value and is implicitly called at each loop increment. next...
A Transpose/Unzip Function in Python (inverse of zip)
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. For example: original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) Is there a bui...
zip is its own inverse! Provided you use the special * operator. >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] The way this works is by calling zip with the arguments: zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) … except the arguments are passed to zip directly (after being...
What's the best way to grab/parse command line arguments passed to a Python script?
What's the easiest, tersest, and most flexible method or library for parsing Python command line arguments?
This answer suggests optparse which is appropriate for older Python versions. For Python 2.7 and above, argparse replaces optparse. See this answer for more information. As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3)...
Find broken symlinks with Python
If I call os.stat() on a broken symlink, python throws an OSError exception. This makes it useful for finding them. However, there are a few other reasons that os.stat() might throw a similar exception. Is there a more precise way of detecting broken symlinks with Python under Linux?
A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two call...
Specifying a mySQL ENUM in a Django model
How do I go about specifying and using an ENUM in a Django model?
From the Django documentation: MAYBECHOICE = ( ('y', 'Yes'), ('n', 'No'), ('u', 'Unknown'), ) And you define a charfield in your model : married = models.CharField(max_length=1, choices=MAYBECHOICE) You can do the same with integer fields if you don't like to have letters in your db. In that case, rewrite...
Why Java and Python garbage collection methods are different?
Python uses the reference count method to handle object life time. So an object that has no more use will be immediately destroyed. But, in Java, the GC(garbage collector) destroys objects which are no longer used at a specific time. Why does Java choose this strategy and what is the benefit from this? Is this better t...
There are drawbacks of using reference counting. One of the most mentioned is circular references: Suppose A references B, B references C and C references B. If A were to drop its reference to B, both B and C will still have a reference count of 1 and won't be deleted with traditional reference counting. CPython (refer...
Unicode vs UTF-8 confusion in Python / Django?
I stumbled over this passage in the Django tutorial: Django models have a default str() method that calls unicode() and converts the result to a UTF-8 bytestring. This means that unicode(p) will return a Unicode string, and str(p) will return a normal string, with characters encoded as UTF-8. Now, I'm confused becaus...
what is a "Unicode string" in Python? Does that mean UCS-2? Unicode strings in Python are stored internally either as UCS-2 (fixed-length 16-bit representation, almost the same as UTF-16) or UCS-4/UTF-32 (fixed-length 32-bit representation). It's a compile-time option; on Windows it's always UTF-16 whilst many Linux ...
Format numbers to strings in Python
I need to find out how to format numbers as strings. My code is here: return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm"...
Formatting in Python is done via the string formatting (%) operator: "%02d:%02d:%02d" % (hours, minutes, seconds) /Edit: There's also strftime.
How do I download a file over HTTP using Python?
I have a small utility that I use to download a MP3 from a website on a schedule and then builds/updates a podcast XML file which I've obviously added to iTunes. The text processing that creates/updates the XML file is written in Python. I use wget inside a Windows .bat file to download the actual MP3 however. I would ...
One more, using urlretrieve: import urllib urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3") (for Python 3+ use 'import urllib.request' and urllib.request.urlretrieve) Yet another one, with a "progressbar" import urllib2 url = "http://download.thinkbroadband.com/10MB.zip" file_name = url.split('...
What's the best way to duplicate fork() in windows?
How do I implement some logic that will allow me to reproduce on Windows the functionality that I have on Linux with the fork() system call, using Python? I'm specifically trying to execute a method on the SAPI Com component, while continuing the other logic in the main thread without blocking or waiting.
Use the python multiprocessing module which will work everywhere. Here is a IBM developerWords article that shows how to convert from os.fork() to the multiprocessing module.
How can I graph the Lines of Code history for git repo?
Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run "wc -l *", and a script that run git reset --hard on each commit, then ran wc -l To make it a bit clearer, when the tool is run, it would output the line...
You may get both added and removed lines with git log, like: git log --shortstat --reverse --pretty=oneline From this, you can write a similar script to the one you did using this info. In python: #!/usr/bin/python """ Display the per-commit size of the current git branch. """ import subprocess import re import sys ...
Binary buffer in Python
In Python you can use StringIO for a file-like buffer for character data. Memory-mapped file basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's ByteArrayOutputStream? The...
You are probably looking for io.BytesIO class. It works exactly like StringIO except that it supports binary data: from io import BytesIO bio = BytesIO(b"some initial binary data: \x00\x01") StringIO will throw TypeError: from io import StringIO sio = StringIO(b"some initial binary data: \x00\x01")
Python super class reflection
If I have Python code class A(): pass class B(): pass class C(A, B): pass and I have class C, is there a way to iterate through it's super classed (A and B)? Something like pseudocode: >>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>) One solution seems to be inspect module and getclasstree function. d...
C.__bases__ is an array of the super classes, so you could implement your hypothetical function like so: def magicGetSuperClasses(cls): return cls.__bases__ But I imagine it would be easier to just reference cls.__bases__ directly in most cases.
Is there any difference between "foo is None" and "foo == None"?
Is there any difference between: if foo is None: pass and if foo == None: pass The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, r...
is always returns True if it compares the same object instance Whereas == is ultimately determined by the __eq__() method i.e. >>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False
What refactoring tools do you use for Python?
I have a bunch of classes I want to rename. Some of them have names that are small and that name is reused in other class names, where I don't want that name changed. Most of this lives in Python code, but we also have some XML code that references class names. Simple search and replace only gets me so far. In my ca...
In the meantime, I've tried it two tools that have some sort of integration with vim. The first is Rope, a python refactoring library that comes with a Vim (and emacs) plug-in. I tried it for a few renames, and that definitely worked as expected. It allowed me to preview the refactoring as a diff, which is nice. It ...
How do I create an xml document in python
Here is my sample code: from xml.dom.minidom import * def make_xml(): doc = Document() node = doc.createElement('foo') node.innerText = 'bar' doc.appendChild(node) return doc if __name__ == '__main__': make_xml().writexml(sys.stdout) when I run the above code I get this: <?xml version="1.0" ?> ...
Setting an attribute on an object won't give a compile-time or a run-time error, it will just do nothing useful if the object doesn't access it (i.e. "node.noSuchAttr = 'bar'" would also not give an error). Unless you need a specific feature of minidom, I would look at ElementTree: import sys from xml.etree.cElementTre...
Python distutils - does anyone know how to use it?
I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in *nix anyway so I'm not worried about it being cross platform. my main goal is to create a .deb package for debian/ubu...
See the distutils simple example. That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installed. Sometimes you need to give it some mapping dicts...
How do threads work in Python, and what are common Python-threading specific pitfalls?
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up. From what I can tel...
Yes, because of the Global Interpreter Lock (GIL) there can only run one thread at a time. Here are some links with some insights about this: http://www.artima.com/weblogs/viewpost.jsp?thread=214235 http://smoothspan.wordpress.com/2007/09/14/guido-is-right-to-leave-the-gil-in-python-not-for-multicore-but-for-utility-c...
How can I render a tree structure (recursive) using a django template?
I have a tree structure in memory that I would like to render in HTML using a Django template. class Node(): name = "node name" children = [] There will be some object root that is a Node, and children is a list of Nodes. root will be passed in the content of the template. I have found this one discussion of how ...
Using with template tag, I could do tree/recursive list. Sample code: main template: assuming 'all_root_elems' is list of one or more root of tree <ul> {%for node in all_root_elems %} {%include "tree_view_template.html" %} {%endfor%} </ul> tree_view_template.html renders the nested ul, li and uses node template v...
Is it possible to run a Python script as a service in Windows? If possible, how?
I am sketching the architecture for a set of programs that share various interrelated objects stored in a database. I want one of the programs to act as a service which provides a higher level interface for operations on these objects, and the other programs to access the objects through that service. I am currently ai...
Yes you can. I do it using the pythoncom libraries that come included with ActivePython or can be installed with pywin32 (Python for Windows extensions). This is a basic skeleton for a simple service: import win32serviceutil import win32service import win32event import servicemanager import socket class AppServerSvc ...
How to generate dynamic (parametrized) unit tests in python?
I have some kind of test data and want to create an unit test for each item. My first idea was to do it like this: import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequence(unittest.TestCase): def testsample(self): for name, a,b in l: print "test", name ...
i use something like this: import unittest l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]] class TestSequense(unittest.TestCase): pass def test_generator(a, b): def test(self): self.assertEqual(a,b) return test if __name__ == '__main__': for t in l: test_name = 'test_%...
Find out how much memory is being used by an object in Python
How would you go about finding out how much memory is being used by an object? I know it is possible to find out how much is used by a block of code, but not by an instantiated object (anytime during its life), which is what I want.
There's no easy way to find out the memory size of a python object. One of the problems you may find is that Python objects - like lists and dicts - may have references to other python objects (in this case, what would your size be? The size containing the size of each object or not?). There are some pointers overhead ...
Are Python threads buggy?
A reliable coder friend told me that Python's current multi-threading implementation is seriously buggy - enough to avoid using altogether. What can said about this rumor?
Python threads are good for concurrent I/O programming. Threads are swapped out of the CPU as soon as they block waiting for input from file, network, etc. This allows other Python threads to use the CPU while others wait. This would allow you to write a multi-threaded web server or web crawler, for example. However, P...
How to specify an authenticated proxy for a python http connection?
What's the best way to specify a proxy with username and password for an http connection in python?
This works for me: import urllib2 proxy = urllib2.ProxyHandler({'http': 'http:// username:password@proxyurl:proxyport'}) auth = urllib2.HTTPBasicAuthHandler() opener = urllib2.build_opener(proxy, auth, urllib2.HTTPHandler) urllib2.install_opener(opener) conn = urllib2.urlopen('http://python.org') return_str = conn....
Finding what methods an object has
Given a Python object of any kind, is there an easy way to get a list of all methods that this object has? Or, if this is not possible, is there at least an easy way to check if it has a particular method other than simply checking if an error occurs when the method is called?
It appears you can use this code, replacing 'object' with the object you're interested in:- [method for method in dir(object) if callable(getattr(object, method))] I discovered it at this site, hopefully that should provide some further detail!
Validate (X)HTML in Python
What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.
http://countergram.com/software/pytidylib is a nice python binding for HTML Tidy. Their example: from tidylib import tidy_document document, errors = tidy_document('''<p>f&otilde;o <img src="bar.jpg">''', options={'numeric-entities':1}) print document print errors
Is Python good for big software projects (not web based)?
Right now I'm developing mostly in C/C++, but I wrote some small utilities in Python to automatize some tasks and I really love it as language (especially the productivity). Except for the performances (a problem that could be sometimes solved thanks to the ease of interfacing Python with C modules), do you think it i...
We've used IronPython to build our flagship spreadsheet application (40kloc production code - and it's Python, which IMO means loc per feature is low) at Resolver Systems, so I'd definitely say it's ready for production use of complex apps. There are two ways in which this might not be a useful answer to you :-) We're...
Why is my instance variable not in __dict__?
If I create a class A as follows: class A: def __init__(self): self.name = 'A' Inspecting the __dict__ member looks like {'name': 'A'} If however I create a class B: class B: name = 'B' __dict__ is empty. What is the difference between the two, and why doesn't name show up in B's __dict__?
B.name is a class attribute, not an instance attribute. It shows up in B.__dict__, but not in b = B(); b.__dict__. The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, b.name will give you the value of B.name.
How to escape os.system() calls in Python?
When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash. I'm currently doing the following, but am sure there must be a library function...
shlex.quote() does what you want since python 3. (Use pipes.quote to support both python 2 and python 3)
Django templates and variable attributes
I'm using Google App Engine and Django templates. I have a table that I want to display the objects look something like: Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] The Django template is: <table> <tr align="center"> <th>user</th> {% for item in result.items %} ...
I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works. You install a custom filter into django which gets the key of your dict as a parameter To make it work in google app-engine you need to add a file to your main directory, I called mine *django_hack.py* which contains ...
C-like structures in Python
Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like: class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3
Use a named tuple, which was added to the collections module in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's named tuple recipe if you need to support Python 2.4. It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment ...
How do I sort a list of strings in Python?
What is the best way of creating an alphabetically sorted list in Python?
Basic answer: mylist = ["b", "C", "A"] mylist.sort() This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function: for x in sorted(mylist): print x However, the examples above are a bit naive, because they don't take locale into...
What does ** (double star) and * (star) do for Python parameters?
In the following method definitions, what does the * and ** do for param2? def foo(param1, *param2): def bar(param1, **param2):
The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation. The *args will give you all function parameters as a tuple: In [1]: def foo(*args): ...: for a in args: ...: print a ...: ...
How can I represent an 'Enum' in Python?
I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python?
Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi. For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you'll need __order__ in pyt...
Resources for lexing, tokenising and parsing in python
Can people point me to resources on lexing, parsing and tokenising with Python? I'm doing a little hacking on an open source project (hotwire) and wanted to do a few changes to the code that lexes, parses and tokenises the commands entered into it. As it is real working code it is fairly complex and a bit hard to work...
I'm a happy user of PLY. It is a pure-Python implementation of Lex & Yacc, with lots of small niceties that make it quite Pythonic and easy to use. Since Lex & Yacc are the most popular lexing & parsing tools and are used for the most projects, PLY has the advantage of standing on giants' shoulders. A lot of knowledge ...
Filter out HTML tags and resolve entities in python
Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.
Use lxml which is the best xml/html library for python. import lxml.html t = lxml.html.fromstring("...") t.text_content() And if you just want to sanitize the html look at the lxml.html.clean module
What's the easiest way to read a FoxPro DBF file from Python?
I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too. Update: Thanks @cnu, I used Yusdi Santoso's dbf.py and it works nicely. One gotcha: The memo file name extension must be lower...
I prefer dbfpy. It supports both reading and writing of .DBF files and can cope with most variations of the format. It's the only implementation I have found that could both read and write the legacy DBF files of some older systems I have worked with.
What are Class methods in Python for?
I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions. I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'm not sure when I would use them. All the advic...
Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functio...
What's the best way to return multiple values from a function in Python?
I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python...
def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically succeeded, b = f("a") # Automatic tuple unpacking
Using Django time/date widgets in custom form
How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view? I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it? Here is my template that I want it applied on. <form action="." method="PO...
The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another...
How to merge two Python dictionaries in a single expression?
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place. >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>> x {'a...
In your case, what you can do is: z = dict(x.items() + y.items()) This will, as you want it, put the final dict in z, and make the value for key b be properly overridden by the second (y) dict's value: >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = dict(x.items() + y.items()) >>> z {'a': 1, 'c': 11, 'b': 10...
Search and replace a line in a file in Python
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? f = open(file) ...
The shortest way would probably be to use the fileinput module. For example, the following adds line numbers to a file, in-place: import fileinput for line in fileinput.input("test.txt", inplace=True): print "%d: %s" % (fileinput.filelineno(), line), What happens here is: The original file is moved to a backup f...
Finding a file in a Python module distribution
I've written a Python package that includes a bsddb database of pre-computed values for one of the more time-consuming computations. For simplicity, my setup script installs the database file in the same directory as the code which accesses the database (on Unix, something like /usr/lib/python2.5/site-packages/mypacka...
Try using pkg_resources, which is part of setuptools (and available on all of the pythons I have access to right now): >>> import pkg_resources >>> pkg_resources.resource_ filename(__name__, "foo.config") 'foo.config' >>> pkg_resources.resource_filename('tempfile', "foo.config") '/usr/lib/python2.4/foo.config' There's...
What is the best way to do Bit Field manipulation in Python?
I'm reading some MPEG Transport Stream protocol over UDP and it has some funky bitfields in it (length 13 for example). I'm using the "struct" library to do the broad unpacking, but is there a simple way to say "Grab the next 13 bits" rather than have to hand-tweak the bit manipulation? I'd like something like the way ...
The bitstring module is designed to address just this problem. It will let you read, modify and construct data using bits as the basic building blocks. The latest versions are for Python 2.6 or later (including Python 3) but version 1.0 supported Python 2.4 and 2.5 as well. A relevant example for you might be this, whi...
javascript locals()?
In python one can get a dictionary of all local and global variables in the current scope with the built-in functions locals() and globals(). Is there some equivalent way of doing this in javascript? For instance, I would like to do something like the following: var foo = function(){ alert('foo'); }; var bar = functi...
locals() - No. globals() - Yes. window is a reference to the global scope, like globals() in python. globals()["foo"] is the same as: window["foo"]
Python deployment and /usr/bin/env portability
At the beginning of all my executable Python scripts I put the shebang line: #!/usr/bin/env python I'm running these scripts on a system where env python yields a Python 2.2 environment. My scripts quickly fail because I have a manual check for a compatible Python version: if sys.version_info < (2, 4): raise Impor...
"env" simply executes the first thing it finds in the PATH env var. To switch to different python, prepend the directory for that python's executable to the path before invoking your script.
Always including the user in the django template context
I am working on a small intranet site for a small company, where user should be able to post. I have imagined a very simple authentication mechanism where people just enter their email address, and gets sent a unique login url, that sets a cookie that will always identify them for future requests. In my template setup,...
There is no need to write a context processor for the user object if you already have the "django.core.context_processors.auth" in TEMPLATE_CONTEXT_PROCESSORS and if you're using RequestContext in your views. if you are using django 1.4 or latest the module has been moved to django.contrib.auth.context_processors.auth...
Splitting tuples in Python - best practice?
I have a method in my Python code that returns a tuple - a row from a SQL query. Let's say it has three fields: (jobId, label, username) For ease of passing it around between functions, I've been passing the entire tuple as a variable called 'job'. Eventually, however, I want to get at the bits, so I've been using code...
I'd say that a dictionary is definitely the best way to do it. It's easily extensible, allows you to give each value a sensible name, and Python has a lot of built-in language features for using and manipulating dictionaries. If you need to add more fields later, all you need to change is the code that converts the t...
What is a tuple useful for?
I am learning Python for a class now, and we just covered tuples as one of the data types. I read the Wikipedia page on it, but, I could not figure out where such a data type would be useful in practice. Can I have some examples, perhaps in Python, where an immutable set of numbers would be needed? How is this differen...
Tuples are used whenever you want to return multiple results from a function. Since they're immutable, they can be used as keys for a dictionary (lists can't).
Best way to extract text from a Word doc without using COM/automation?
Is there a reasonable way to extract plain text from a Word file that doesn't depend on COM automation? (This is a a feature for a web app deployed on a non-Windows platform - that's non-negotiable in this case.) Antiword seems like it might be a reasonable option, but it seems like it might be abandoned. A Python sol...
(Same answer as extracting text from MS word files in python) Use the native Python docx module which I made this week. Here's how to extract all the text from a doc: document = opendocx('Hello world.docx') # This location is where most document content lives docbody = document.xpath('/w:document/w:body', namespaces=...
Python re.sub MULTILINE caret match
The Python docs say: re.MULTILINE: When specified, the pattern character '^' matches at the beginning of the string and at the beginning of each line (immediately following each newline)... By default, '^' matches only at the beginning of the string... So what's going on when I get the following unexpected result? >>...
Look at the definition of re.sub: sub(pattern, repl, string[, count]) The 4th argument is the count, you are using re.MULTILINE (which is 8) as the count, not as a flag. You have to compile your regex if you wish to use flags. re.sub(re.compile('^//', re.MULTILINE), '', s) A flags argument was added in Python 2.7, so...
Get Last Day of the Month in Python
Is there a way using Python's standard library to easily determine (i.e. one function call) the last day of a given month? If the standard library doesn't support that, does the dateutil package support this?
I didn't notice this earlier when I was looking at the documentation for the calendar module, but a method called monthrange provides this information: monthrange(year, month)     Returns weekday of first day of the month and number of days in month, for the specified year and month. >>> import calendar >>> calend...
How to generate urls in django
In Django's template language, you can use {% url [viewname] [args] %} to generate a URL to a specific view with parameters. How can you programatically do the same in Python code? What I need is to create a list of menu items where each item has name, URL, and an active flag (whether it's the current page or not). Th...
If you need to use something similar to the {% url %} template tag in your code, Django provides the django.core.urlresolvers.reverse(). The reverse function has the following signature: reverse(viewname, urlconf=None, args=None, kwargs=None) https://docs.djangoproject.com/en/dev/ref/urlresolvers/
Can I write native iPhone apps using Python
Using PyObjC, you can use Python to write Cocoa applications for OS X. Can I write native iPhone apps using Python and if so, how?
You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See iPhone Applications in Python. Note that this requires a jailbroken iPhone at the moment.
A python web application framework for tight DB/GUI coupling?
I'm a firm believer of the heretic thought of tight coupling between the backend and frontend: I want existing, implied knowledge about a backend to be automatically made use of when generating user interfaces. E.g., if a VARCHAR column has a maximum with of 20 characters, there GUIs should automatically constrain the ...
web2py does most of what you ask: Based on a field type and its validators it will render the field with the appropriate widget. You can override with db.table.field.widget=... and use a third party widget. web2py has js to blocks the user from entering a non-integer in a integer field or a non-double in a double fiel...
How to find the mime type of a file in python?
Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer. Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in th...
The python-magic method suggested by toivotuo is outdated. Python-magic's current trunk is at Github and based on the readme there, finding the MIME-type, is done like this. # For MIME types >>> import magic >>> mime = magic.Magic(mime=True) >>> mime.from_file("testdata/test.pdf") 'application/pdf' >>>
Pros and Cons of different approaches to web programming in Python
I'd like to do some server-side scripting using Python. But I'm kind of lost with the number of ways to do that. It starts with the do-it-yourself CGI approach and it seems to end with some pretty robust frameworks that would basically do all the job themselves. And a huge lot of stuff in between, like web.py, Pyroxide...
CGI is great for low-traffic websites, but it has some performance problems for anything else. This is because every time a request comes in, the server starts the CGI application in its own process. This is bad for two reasons: 1) Starting and stopping a process can take time and 2) you can't cache anything in mem...
Modulus operation with negatives values - weird thing?
Can you please tell me how much is (-2) % 5? According to my Python interpreter is 3, but do you have a wise explanation for this? I've read that in some languages the result can be machine-dependent, but I'm not sure though.
By the way: most programming languages would disagree with Python and give the result -2. Depending on the interpretation of modulus this is correct. However, the most agreed-upon mathematical definition states that the modulus of a and b is the (strictly positive) rest r of the division of a / b. More precisely, 0 <= ...
How do I document a module in Python?
That's it. If you want to document a function or a class, you put a string just after the definition. For instance: def foo(): """This function does nothing.""" pass But what about a module? How can I document what a file.py does?
For the packages, you can document it in __init__.py. For the modules, you can add a docstring simply in the module file. All the information is here: http://www.python.org/dev/peps/pep-0257/
Iterate over subclasses of a given class in a given module
In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?
Although Quamrana's suggestion works fine, there are a couple of possible improvements I'd like to suggest to make it more pythonic. They rely on using the inspect module from the standard library. You can avoid the getattr call by using inspect.getmembers() The try/catch can be avoided by using inspect.isclass() Wit...
How would you make a comma-separated string from a list?
What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, [ 'a', 'b', 'c' ] to 'a,b,c'? (The cases [ s ] and [] should be mapped to s and '', respectively.) I usually end up using something like ''.join(ma...
myList = ['a','b','c','d'] myString = ",".join(myList ) This won't work if the list contains numbers. As Ricardo Reyes suggested, if it contains non-string types (such as integers, floats, bools, None) then do: myList = ','.join(map(str, myList))
Can someone explain __all__ in Python?
I have been using Python more and more, and I keep seeing the variable __all__ set in different __init__.py files. Can someone explain what this does?
Linked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module. For example, the following code in a foo.py explicitly exports the symbols bar and baz: __all__ = ['bar', 'baz'] w...
Python packages - import by class, not file
Say I have the following file structure: app/ app.py controllers/ __init__.py project.py plugin.py If app/controllers/project.py defines a class Project, app.py would import it like this: from app.controllers.project import Project I'd like to just be able to do: from app.controllers import Project H...
You need to put from project import Project in controllers/__init__.py. Note that when Absolute imports become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named project), i.e., from .project import Project
Where can I find the time and space complexity of the built-in sequence types in Python
I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
Checkout the TimeComplexity page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.
Is there a Python library for generating .ico files?
I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files.
Perhaps the following would work: Generate your icon image using PIL Convert the image to .ico format using the python interface to ImageMagick, PythonMagick I have not tried this approach. The ImageMagick convert command line program was able to convert a .png file to .ico format, so at least ImageMagick supports th...