instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
How do I dump an entire Python process for later debugging inspection?
I have a Python application in a strange state. I don't want to do live debugging of the process. Can I dump it to a file and examine its state later? I know I've restored corefiles of C programs in gdb later, but I don't know how to examine a Python application in a useful way from gdb. (This is a variation on my q...
There is no builtin way other than aborting (with os.abort(), causing the coredump if resource limits allow it) -- although you can certainly build your own 'dump' function that dumps relevant information about the data you care about. There are no ready-made tools for it. As for handling the corefile of a Python proce...
Python: How to make a cross-module variable?
The __debug__ variable is handy in part because it affects every module. If I want to create another variable that works the same way, how would I do it? The variable (let's be original and call it 'foo') doesn't have to be truly global, in the sense that if I change foo in one module, it is updated in others. I'd be f...
If you need a global cross-module variable maybe just simple global module-level variable will suffice. a.py: var = 1 b.py: import a print a.var import c print a.var c.py: import a a.var = 2 Test: $ python b.py # -> 1 2 Real-world example: Django's global_settings.py (though in Django apps settings are used by imp...
Does Python have a bitfield type?
I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution?
If you mainly want to be able to name your bit fields and easily manipulate them, e.g. to work with flags represented as single bits in a communications protocol, then you can use the standard Structure and Union features of ctypes, as described at How Do I Properly Declare a ctype Structure + Union in Python? - Stack ...
Drag and drop onto Python script in Windows Explorer
I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target. Is there some kind of configuration that needs to be done ...
Sure. From a mindless technology article called "Make Python Scripts Droppable in Windows", you can add a drop handler by adding a registry key: Here’s a registry import file that you can use to do this. Copy the following into a .reg file and run it (Make sure that your .py extensions are mapped to Python.Fil...
Has anyone found a good set of python plugins for vim -- specifically module completion?
I'm looking for a suite of plugins that can help me finally switch over to vim full-time. Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it. What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by import...
Here you can find some info about this. It covers code completion, having a list of classes and functions in open files. I haven't got around to do a full configuration for vim, since I don't use Python primarily, but I have the same interests in transforming vim in a better Python IDE. Edit: The original site is down,...
Python PostgreSQL modules. Which is best?
I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore. Which module do you recommend? Why?
psycopg2 seems to be the most popular. I've never had any trouble with it. There's actually a pure Python interface for PostgreSQL too, called bpgsql. I wouldn't recommend it over psycopg2, but it's recently become capable enough to support Django and is useful if you can't compile C modules.
Calling C/C++ from python?
What would be the quickest way to construct a python binding to a C or C++ library? (using windows if this matters)
I like ctypes a lot, swig always tended to give me problems. Also ctypes has the advantage that you don't need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against. Suppose you have a simple C++ example class you want to tal...
Text difference algorithm
I need an algorithm that can compare two text files and highlight their difference and ( even better!) can compute their difference in a meaningful way (like two similar files should have a similarity score higher than two dissimilar files, with the word "similar" defined in the normal terms). It sounds easy to implem...
I can recommend to take a look at Neil Fraser's code and articles: google-diff-match-patch Currently available in Java, JavaScript, C++ and Python. Regardless of language, each library features the same API and the same functionality. All versions also have comprehensive test harnesses. Neil Fraser: Diff St...
How does one do the equivalent of "import * from module" with Python's __import__ function?
Given a string with a module name, how do you import everything in the module as if you had called: from module import * i.e. given string S="module", how does one get the equivalent of the following: __import__(S, fromlist="*") This doesn't seem to perform as expected (as it doesn't import anything). Thanks!
Please reconsider. The only thing worse than import * is magic import *. If you really want to: m = __import__ (S) try: attrlist = m.__all__ except AttributeError: attrlist = dir (m) for attr in attrlist: globals()[attr] = getattr (m, attr)
Debug Pylons application through Eclipse
I have Eclipse setup with PyDev and love being able to debug my scripts/apps. I've just started playing around with Pylons and was wondering if there is a way to start up the paster server through Eclipse so I can debug my webapp?
Create a new launch configuration (Python Run) Main tab Use paster-script.py as main module (you can find it in the Scripts sub-directory in your python installation directory) Don't forget to add the root folder of your application in the PYTHONPATH zone Arguments Set the base directory to the root folder also. As Pro...
How do I manipulate bits in Python?
In C I could, for example, zero out bit #10 in a 32 bit unsigned value like so: unsigned long value = 0xdeadbeef; value &= ~(1<<10); How do I do that in Python ?
Bitwise operations on Python ints work much like in C. The &, | and ^ operators in Python work just like in C. The ~ operator works as for a signed integer in C; that is, ~x computes -x-1. You have to be somewhat careful with left shifts, since Python integers aren't fixed-width. Use bit masks to obtain the low order b...
Character reading from file in Python
In a text file, there is a string "I don't like this". However, when I read it into a string, it becomes "I don\xe2\x80\x98t like this". I understand that \u2018 is the unicode representation of "'". I use f1 = open (file1, "r") text = f1.read() command to do the reading. Now, is it possible to read the string in suc...
Ref: http://docs.python.org/howto/unicode Reading Unicode from a file is therefore simple: import codecs f = codecs.open('unicode.rst', encoding='utf-8') for line in f: print repr(line) It's also possible to open files in update mode, allowing both reading and writing: f = codecs.open('test', encoding='utf-8', mod...
In Django is there a way to display choices as checkboxes?
In the admin interface and newforms there is the brilliant helper of being able to define choices. You can use code like this: APPROVAL_CHOICES = ( ('yes', 'Yes'), ('no', 'No'), ('cancelled', 'Cancelled'), ) client_approved = models.CharField(choices=APPROVAL_CHOICES) to create a drop down box in your for...
In terms of the forms library, you would use the MultipleChoiceField field with a CheckboxSelectMultiple widget to do that. You could validate the number of choices which were made by writing a validation method for the field: class MyForm(forms.Form): my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widg...
Preserving signatures of decorated functions
Suppose I have written a decorator that does something very generic. For example, it might convert all arguments to a specific type, perform logging, implement memoization, etc. Here is an example: def args_as_ints(f): def g(*args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) f...
Install decorator module: $ pip install decorator Adapt definition of args_as_ints(): import decorator @decorator.decorator def args_as_ints(f, *args, **kwargs): args = [int(x) for x in args] kwargs = dict((k, int(v)) for k, v in kwargs.items()) return f(*args, **kwargs) @args_as_ints def funny_function...
Caching in urllib2?
Is there an easy way to cache things when using urllib2 that I am over-looking, or do I have to roll my own?
If you don't mind working at a slightly lower level, httplib2 (http://code.google.com/p/httplib2/) is an excellent HTTP library that includes caching functionality.
Keeping GUIs responsive during long-running tasks
Keeping the GUI responsive while the application does some CPU-heavy processing is one of the challenges of effective GUI programming. Here's a good discussion of how to do this in wxPython. To summarize, there are 3 ways: Use threads Use wxYield Chunk the work and do it in the IDLE event handler Which method have yo...
Threads. They're what I always go for because you can do it in every framework you need. And once you're used to multi-threading and parallel processing in one language/framework, you're good on all frameworks.
BeautifulSoup's Python 3 compatibility
Does BeautifulSoup work with Python 3? If not, how soon will there be a port? Will there be a port at all? Google doesn't turn up anything to me (Maybe it's 'coz I'm looking for the wrong thing?)
Beautiful Soup 4.x officially supports Python 3. pip install beautifulsoup4
How do you break into the debugger from Python source code?
What do you insert into Python source code to have it break into pdb (when execution gets to that spot)?
import pdb; pdb.set_trace() See Python: Coding in the Debugger for Beginners for this and more helpful hints.
How do I calculate number of days betwen two dates using Python?
If I have two dates (ex. '8/18/2008' and '9/26/2008') what is the best way to get the difference measured in days?
If you have two date objects, you can just subtract them. from datetime import date d0 = date(2008, 8, 18) d1 = date(2008, 9, 26) delta = d0 - d1 print delta.days The relevant section of the docs: https://docs.python.org/library/datetime.html
What's the canonical way to check for type in python?
What is the best way to check whether a given object is of a given type? How about checking whether the object inherits from a given type? Let's say I have an object o. How do I check whether it's a str?
To check if the type of o is exactly str: type(o) is str To check if o is an instance of str or any subclass of str (this would be the "canonical" way): isinstance(o, str) The following also works, and can be useful in some cases: issubclass(type(o), str) type(o) in ([str] + str.__subclasses__()) See Built-in Functi...
How to iterate over a timespan after days, hours, weeks and months in Python?
How do I iterate over a timespan after days, hours, weeks or months? Something like: for date in foo(from_date, to_date, delta=HOURS): print date Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.
Use dateutil and its rrule implementation, like so: from dateutil import rrule from datetime import datetime, timedelta now = datetime.now() hundredDaysLater = now + timedelta(days=100) for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater): print dt Output is 2008-09-30 23:29:54 2008-10-30 23...
Python GUI Application redistribution
I need to develop a small-medium sized desktop GUI application, preferably with Python as a language of choice because of time constraints. What GUI library choices do I have which allow me to redistribute my application standalone, assuming that the users don't have a working Python installation and obviously don't ha...
This may help: http://stackoverflow.com/questions/49146/what-is-the-best-way-to-make-an-exe-file-from-a-python-program
How to avoid .pyc files?
Can I run the python interpreter without generating the compiled .pyc files?
From "What’s New in Python 2.6 - Interpreter Changes": Python can now be prevented from writing .pyc or .pyo files by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. This setting is available to Python pro...
Is timsort general-purpose or Python-specific?
Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays. Have you seen timsort used outside of C...
Yes, it makes quite a bit of sense to use timsort outside of CPython, in specific, or Python, in general. There is currently an effort underway to replace Java's "modified merge sort" with timsort, and the initial results are quite positive.
Python module for wiki markup
Is there a Python module for converting wiki markup to other languages (e.g. HTML)? A similar question was asked here, What's the easiest way to convert wiki markup to html, but no Python modules are mentioned. Just curious. :) Cheers.
mwlib provides ways of converting MediaWiki formatted text into HTML, PDF, DocBook and OpenOffice formats.
Python Dependency Injection Framework
Is there a framework equivalent to Guice (http://code.google.com/p/google-guice) for Python?
Spring Python is an offshoot of the Java-based Spring Framework and Spring Security, targeted for Python. This project currently contains the following features: Inversion Of Control (dependency injection) - use either classic XML, or the python @Object decorator (similar to the Spring JavaConfig subproject) to wire t...
Get timer ticks in Python
I'm just trying to time a piece of code. The pseudocode looks like: start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." How does this look in Python? More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?
In the time module, there are two timing functions: time and clock. time gives you "wall" time, if this is what you care about. However, the python docs say that clock should be used for benchmarking. Note that clock behaves different in separate systems: on MS Windows, it uses the Win32 function QueryPerformanceCount...
Emacs and Python
I recently started learning Emacs. I went through the tutorial, read some introductory articles, so far so good. Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project; and python.el, which is part of Emacs ...
If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it...
Most pythonic way of counting matching elements in something iterable
I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three. My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the split loop refactoring in...
Having to iterate over the list multiple times isn't elegant IMHO. I'd probably create a function that allows doing: twos, threes = countmatching(xrange(1,10), lambda a: a % 2 == 0, lambda a: a % 3 == 0) A starting point would be something like this: def countm...
Accurate timestamping in Python
I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that). I've been using datetime.now() as a first stab, but this is...
time.clock() only measures wallclock time on Windows. On other systems, time.clock() actually measures CPU-time. On those systems time.time() is more suitable for wallclock time, and it has as high a resolution as Python can manage -- which is as high as the OS can manage; usually using gettimeofday(3) (microsecond res...
Python 2.5 dictionary 2 key sort
I have a dictionary of 200,000 items (the keys are strings and the values are integers). What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)? a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], revers...
You can't sort dictionaries. You have to sort the list of items. Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric. a = { 'key':1, 'another':2, 'key2':1 } b= a.items() b.sort( k...
Hiding a password in a (python) script
I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. Is there an easy way to obscure this password in the file (just that nobody can read the password when ...
Base64 encoding is in the standard library and will do to stop shoulder surfers: >>> import base64 >>> print base64.b64encode("password") cGFzc3dvcmQ= >>> print base64.b64decode("cGFzc3dvcmQ=") password
Python module dependency
Ok I have two modules, each containing a class, the problem is their classes reference each other. Lets say for example I had a room module and a person module containing CRoom and CPerson. The CRoom class contains infomation about the room, and a CPerson list of every one in the room. The CPerson class however sometim...
No need to import CRoom You don't use CRoom in person.py, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time". If you actually do use CRoom in person.py, then change from room import CRoom to import room and use module-qualified form room.CRoom. See Effbot's Ci...
Getting MAC Address
I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of anothe...
Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily: from uuid import getnode as get_mac mac = get_mac() The return value is the mac address as 48 bit integer.
What is the naming convention in Python for variable and function names?
Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case: // C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() In Python, I have seen the above but I have also seen underscores being used: # python example this_is_my_variable = 'a'...
See Python PEP 8. Function names should be lowercase, with words separated by underscores as necessary to improve readability. mixedCase is allowed only in contexts where that's already the prevailing style Variables... Use the function naming rules: lowercase with words separated by underscores as neces...
urllib2 file name
If I open a file using urllib2, like so: remotefile = urllib2.urlopen('http://example.com/somefile.zip') Is there an easy way to get the file name other then parsing the original URL? EDIT: changed openfile to urlopen... not sure how that happened. EDIT2: I ended up using: filename = url.split('/')[-1].split('#')[0].s...
Did you mean urllib2.urlopen? You could potentially lift the intended filename if the server was sending a Content-Disposition header by checking remotefile.info()['Content-Disposition'], but as it is I think you'll just have to parse the url. You could use urlparse.urlsplit, but if you have any URLs like at the second...
Python - How do I pass a string into subprocess.Popen (using the stdin argument)?
If I do the following: import subprocess from cStringIO import StringIO subprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] I get: Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/python-2.4.3/lib/py...
Popen.communicate() documentation: Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too. Replacing os.popen* pipe = os.popen(...
Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?
I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField). With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see b...
As another option, you can do look ups like: class UserAdmin(admin.ModelAdmin): list_display = (..., 'get_author') def get_author(self, obj): return obj.book.author get_author.short_description = 'Author' get_author.admin_order_field = 'book__author'
How do I deploy a Python desktop application?
I have started on a personal python application that runs on the desktop. I am using wxPython as a GUI toolkit. Should there be a demand for this type of application, I would possibly like to commercialize it. I have no knowledge of deploying "real-life" Python applications, though I have used py2exe in the past with v...
You can distribute the compiled Python bytecode (.pyc files) instead of the source. You can't prevent decompilation in Python (or any other language, really). You could use an obfuscator like pyobfuscate to make it more annoying for competitors to decipher your decompiled source. As Alex Martelli says in this thread, i...
Change Django Templates Based on User-Agent
I've made a Django site, but I've drank the Koolaid and I want to make an IPhone version. After putting much thought into I've come up with two options: Make a whole other site, like i.xxxx.com. Tie it into the same database using Django's sites framework. Find some time of middleware that reads the user-agent, and ...
Rather than changing the template directories dynamically you could modify the request and add a value that lets your view know if the user is on an iphone or not. Then wrap render_to_response (or whatever you are using for creating HttpResponse objects) to grab the iphone version of the template instead of the standar...
How would I package and sell a Django app?
Currently I am hosting a Django app I developed myself for my clients, but I am now starting to look at selling it to people for them to host themselves. My question is this: How can I package up and sell a Django app, while protecting its code from pirating or theft? Distributing a bunch of .py files doesn't sound lik...
Don't try and obfuscate or encrypt the code - it will never work. I would suggest selling the Django application "as a service" - either host it for them, or sell them the code and support. Write up a contract that forbids them from redistributing it. That said, if you were determined to obfuscate the code in some way ...
Detecting Mouse clicks in windows using python
How can I detect mouse clicks regardless of the window the mouse is in? Perferabliy in python, but if someone can explain it in any langauge I might be able to figure it out. I found this on microsoft's site: http://msdn.microsoft.com/en-us/library/ms645533(VS.85).aspx But I don't see how I can detect or pick up the no...
The only way to detect mouse events outside your program is to install a Windows hook using SetWindowsHookEx. The pyHook module encapsulates the nitty-gritty details. Here's a sample that will print the location of every mouse click: import pyHook import pythoncom def onclick(event): print event.Position retur...
Python object attributes - methodology for access
Suppose I have a class with some attributes. How is it best (in the Pythonic-OOP) sense to access these attributes ? Just like obj.attr ? Or perhaps write get accessors ? What are the accepted naming styles for such things ? Edit: Can you elaborate on the best-practices of naming attributes with a single or double lea...
With regards to the single and double-leading underscores: both indicate the same concept of 'privateness'. That is to say, people will know the attribute (be it a method or a 'normal' data attribute or anything else) is not part of the public API of the object. People will know that to touch it directly is to invite d...
Sleeping in a batch file
When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ...
The timeout command is available from Vista onwards. c:\> timeout /? TIMEOUT [/T] timeout [/NOBREAK] Description: This utility accepts a timeout parameter to wait for the specified time period (in seconds) or until any key is pressed. It also accepts a parameter to ignore the key press. Parameter List: ...
Finding local IP addresses using Python's stdlib
How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library?
I just found this but it seems a bit hackish, however they say tried it on *nix and I did on windows and it worked. import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com",80)) print(s.getsockname()[0]) s.close() This assumes you have an internet access, and that there is no local pro...
Finding a public facing IP address in Python?
How can I find the public facing IP for my net work in Python?
This will fetch your remote IP address import urllib ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read() If you don't want to rely on someone else, then just upload something like this PHP script: <?php echo $_SERVER['REMOTE_ADDR']; ?> and change the URL in the Python or if you prefer ASP: <%...
Calling Python in PHP
I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac. I don't want to go through the minor trouble of installing mod_python or mod_wsgi on my Mac, so I was just going to do a system() or popen() from PHP ...
Depending on what you are doing, system() or popen() may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write data to the Python script's standard input, or read data from the Python script's standard out...
How do you get a directory listing sorted by creation date in python?
What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine?
I've done this in the past for a Python script to determine the last updated files in a directory: import glob import os search_dir = "/mydir/" # remove anything from the list that is not a file (directories, symlinks) # thanks to J.F. Sebastion for pointing out that the requirement was a list # of files (presumably...
Python - How do I convert "an OS-level handle to an open file" to a file object?
tempfile.mkstemp() returns: a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order. How do I convert that OS-level handle to a file object? The documentation for os.open() states: To wrap a file descriptor in a "file object",...
You can use os.write(tup[0], "foo\n") to write to the handle. If you want to open the handle for writing you need to add the "w" mode f = os.fdopen(tup[0], "w") f.write("foo")
Python - How do I write a decorator that restores the cwd?
How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called.
The answer for a decorator has been given; it works at the function definition stage as requested. With Python 2.5+, you also have an option to do that at the function call stage using a context manager: from __future__ import with_statement # needed for 2.5 ≤ Python < 2.6 import contextlib, os @contextlib.contextma...
Django signals vs. overriding save method
I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this: def Review(models.Model) ...fields... overall_score = models.FloatField(blank=True) def Score(models.Model) review = models.ForeignKey(Review) question = models.TextField() grade = models.I...
Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models. One common task in overridden save methods is automated generat...
Formatting a list of text into columns
I'm trying to output a list of string values into a 2 column format. The standard way of making a list of strings into "normal text" is by using the string.join method. However, it only takes 2 arguments so I can only make a single column using "\n". I thought trying to make a loop that would simply add a tab between c...
Two columns, separated by tabs, joined into lines. Look in itertools for iterator equivalents, to achieve a space-efficient solution. import string def fmtpairs(mylist): pairs = zip(mylist[::2],mylist[1::2]) return '\n'.join('\t'.join(i) for i in pairs) print fmtpairs(list(string.ascii_uppercase)) A B C D...
What is the best way to get all the divisors of a number?
Here's the very dumb way: def divisorGenerator(n): for i in xrange(1,n/2+1): if n%i == 0: yield i yield n The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-) I can find prime factors and their multiplicity fast enough. I've an g...
Given your factorGenerator function, here is a divisorGen that should work: def divisorGen(n): factors = list(factorGenerator(n)) nfactors = len(factors) f = [0] * nfactors while True: yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1) i = 0 while T...
How do you develop against OpenID locally
I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main ap...
The libraries at OpenID Enabled ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of this test provider.
How are you planning on handling the migration to Python 3?
I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction: Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished? Have you al...
Here's the general plan for Twisted. I was originally going to blog this, but then I thought: why blog about it when I could get points for it? Wait until somebody cares. Right now, nobody has Python 3. We're not going to spend a bunch of effort until at least one actual user has come forth and said "I need Python 3...
How do I split a multi-line string into multiple lines?
I have a multi-line string literal that I want to do an operation on each line, like so: inputString = """Line 1 Line 2 Line 3""" I want to do something like the following: for line in inputString: doStuff()
inputString.splitlines() Will give you a list with each item, the splitlines() method is designed to split each line into a list element.
Speeding Up Python
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: Firstly: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization? Secondly: When writing a program from scratch in python, what are some goo...
Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?" Remember the Jackson rules of optimization: Rule 1: Don't do it. Rule 2 (for experts only): Don't do it yet. And the Knuth rule: "Premature optimization is the root of all evil." The more us...
Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx)
I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format. The server runs CentOS 5.2 and has PHP/Perl/Python installed. I can execute local binaries and shell scripts if I mu...
The Office 2007 file formats are open and well documented. Roughly speaking, all of the new file formats ending in "x" are zip compressed XML documents. For example: To open a Word 2007 XML file Create a temporary folder in which to store the file and its parts. Save a Word 2007 document, containing text, pictur...
Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?
The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific sit...
You can call os._exit() to directly exit, without throwing an exception: import os os._exit(1) This bypasses all of the python shutdown logic, such as the atexit module, and will not run through the exception handling logic that you're trying to avoid in this situation. The argument is the exit code that will be ...
python dictionary update method
I have a list string tag. I am trying to initialize a dictionary with the key as the tag string and values as the array index. for i, ithTag in enumerate(tag): tagDict.update(ithTag=i) The above returns me {'ithTag': 608} 608 is the 608th index My problem is that while the i is being interpreted as a variable, Py...
You actually want to do this: for i, tag in enumerate(tag): tagDict[tag] = i The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.
Is it possible to pass arguments into event bindings?
I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO. When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way: b = wx.Button(self, 10, "Default Button", (20, 20)) self.Bind(wx.EVT_BUTTON, self.O...
You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific. b = wx.Button(self, 10, "Default Button", (20, 20)) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b) def OnClick(self, event, somearg): self.log.write("Click! (%d...
How to output CDATA using ElementTree
I've discovered that cElementTree is about 30 times faster than xml.dom.minidom and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree. Can it be done?
After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular...
How do I convert a file's format from Unicode to ASCII using Python?
I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format. What is the best way to convert the entire file format using Python?
You can convert the file easily enough just using the unicode function, but you'll run into problems with Unicode characters without a straight ASCII equivalent. This blog recommends the unicodedata module, which seems to take care of roughly converting characters without direct corresponding ASCII values, e.g. >>> ti...
Python List vs. Array - when to use?
If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays. What is the reason or circumstance where I would want to use the array module instead? Is it for performance and memory optimization, or am I missing something...
Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your array time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays....
Finding the index of an item given a list containing it in Python
For a list ["foo", "bar", "baz"] and an item in the list "bar", what's the cleanest way to get its index (1) in Python?
>>> ["foo", "bar", "baz"].index("bar") 1 Reference: Data Structures > More on Lists
Alert boxes in Python?
Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon. This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities. Update: This is intended to run in the background and alert the user when certain conditions ar...
what about this: import win32api win32api.MessageBox(0, 'hello', 'title') Additionally: win32api.MessageBox(0, 'hello', 'title', 0x00001000) will make the box appear on top of other windows, for urgent messages. See MessageBox function for other options.
Testing socket connection in Python
This question will expand on: http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail. Edit: I tried this: try: s.connect((address, '80')) except: alert('failed' + address...
It seems that you catch not the exception you wanna catch out there :) if the s is a socket.socket() object, then the right way to call .connect would be: import socket s = socket.socket() address = '127.0.0.1' port = 80 # port number is a number, not string try: s.connect((address, port)) # originally, it wa...
Python: can I have a list with named indices?
In PHP I can name my array indicies so that I may have something like: $shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'), 1 => Array('id' => 2, 'name' => 'Dora The Explorer')); Is this possible in Python?
This sounds like the PHP array using named indices is very similar to a python dict: shows = [ {"id": 1, "name": "Sesaeme Street"}, {"id": 2, "name": "Dora The Explorer"}, ] See http://docs.python.org/tutorial/datastructures.html#dictionaries for more on this.
How to handle a broken pipe (SIGPIPE) in python?
I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no long...
Assuming that you are using the standard socket module, you should be catching the socket.error: (32, 'Broken pipe') exception (not IOError as others have suggested). This will be raised in the case that you've described, i.e. sending/writing to a socket for which the remote side has disconnected. import socket, errno,...
How do I convert a list of ascii values to a string in python?
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
You are probably looking for 'chr()': >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(chr(i) for i in L) 'hello, world'
In the Django admin interface, is there a way to duplicate an item?
Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface? In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter th...
You can save as by just enabling adding this to your ModelAdmin: save_as = True This replaces the "Save and add another" button with a "Save as" button. "Save as" means the object will be saved as a new object (with a new ID), rather than the old object.
What is the difference between Python's re.search and re.match?
What is the difference between the search() and match() functions in the Python re module? I've read the documentation (current documentation), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in ...
re.match is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using ^ in the pattern. As re.match documentation says: If zero or more characters at the beginning of string match the regular expression pattern, return a corresponding MatchObject instance. Retu...
Python style: multiple-line conditions in IFs
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way u...
You don't need to use 4 spaces on your second conditional line. Maybe use: if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something Also, don't forget the whitespace is more flexible than you might think: if ( cond1 == 'val1' and cond2 == 'val2' and ...
What is the problem with reduce()?
There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot i...
As Guido says in his The fate of reduce() in Python 3000 post: So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually bei...
How do I watch a file for changes using Python?
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the win32file.FindNextChangeNotifi...
Did you try using Watchdog? Python API library and shell utilities to monitor file system events. Directory monitoring made easy with A cross-platform API. A shell tool to run commands in response to directory changes. Get started quickly with a simple example in Quickstart...
How can I use UUIDs in SQLAlchemy?
Is there a way to define a column (primary key) as a UUID in SQLAlchemy if using PostgreSQL (Postgres)?
I wrote this and the domain is gone but here's the guts.... Regardless of how my colleagues who really care about proper database design feel about UUID's and GUIDs used for key fields. I often find I need to do it. I think it has some advantages over autoincrement that make it worth it. I've been refining a UUID col...
Is this the best way to get unique version of filename w/ Python?
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there i...
One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program runni...
In Python, what is the difference between '/' and '//' when used for division?
Is there a benefit to using one over the other? They both seem to return the same results. >>> 6/3 2 >>> 6//3 2
In Python 3.0, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division. In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes ...
How do I check out a file from perforce in python?
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms: http://www.perforce.com/perforce/loadsupp.html#api You will find their documentation of the scripting API to be helpful: http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf...
Delete Folder Contents in Python
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see *nix also.
Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the elif statement. import os, shutil folder = '/path/to/folder' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.pa...
What is the best way to open a file for exclusive access in Python?
What is the most elegant way to solve this: open a file for reading, but only if it is not already opened for writing open a file for writing, but only if it is not already opened for reading or writing The built-in functions work like this >>> path = r"c:\scr.txt" >>> file1 = open(path, "w") >>> print file1 <open fi...
I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module. Fortunately, there is a portable implementation (portalocker) using the platform appropriate method at the python cookboo...
Splitting a semicolon-separated string to a dictionary, in Python
I have a string that looks like this: "Name1=Value1;Name2=Value2;Name3=Value3" Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this: dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } I have looked through the modules...
There's no builtin, but you can accomplish this fairly simply with a generator comprehension: s= "Name1=Value1;Name2=Value2;Name3=Value3" dict(item.split("=") for item in s.split(";")) [Edit] From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format...
Configuration file with list of key-value pairs in python
I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "fil...
I sometimes just write a python module (i.e. file) called config.py or something with following contents: config = { 'name': 'hello', 'see?': 'world' } this can then be 'read' like so: from config import config config['name'] config['see?'] easy.
Counting array elements in Python
How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.
The method len() returns the number of elements in the list. Syntax: len(myArray) Eg: myArray = [1, 2, 3] len(myArray) Output: 3
How do I capture an mp3 stream with python
What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python? Thus far I've tried target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) This gives me data but its garbled or wont play in mp3 players.
If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening target in binary mode: target = open(target_path, "wb")
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). Google shows many hits for explanations on how to do this. Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/au...
Follow the cmd documentation and you'll be fine import cmd addresses = [ 'here@blubb.com', 'foo@bar.com', 'whatever@wherever.org', ] class MyCmd(cmd.Cmd): def do_send(self, line): pass def complete_send(self, text, line, start_index, end_index): if text: return [ ...
Reading/Writing MS Word files in Python
Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object? I know that I can: f = open('c:\file.doc', "w") f.write(text) f.close() but Word will read it as an HTML file not a native .doc file.
See python-docx, its official documentation is available here. This has worked very well for me.
How can I, in python, iterate over multiple 2d lists at once, cleanly?
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this. for i in range(...
If anyone is interested in performance of the above solutions, here they are for 4000x4000 grids, from fastest to slowest: Brian: 1.08s (modified, with izip instead of zip) John: 2.33s DzinX: 2.36s ΤΖΩΤΖΙΟΥ: 2.41s (but object initialization took 62s) Eugene: 3.17s Robert: 4.56s Brian: 27.24s (original, with zi...
How to use Python to login to a webpage and retrieve cookies for later usage?
I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response h...
import urllib, urllib2, cookielib username = 'myuser' password = 'mypassword' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_password' : password}) opener.open('http://www.example.com/login.php', login_data) resp = ope...
How to break out of multiple loops in Python?
Given the following code (that doesn't work): while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff Is there a way ...
My first instinct would be to refactor the nested loop into a function and use return to break out.
Google App Engine and 404 error
I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like - url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static with all the static html/jpg files stored under the static directory. T...
You need to register a catch-all script handler. Append this at the end of your app.yaml: - url: /.* script: main.py In main.py you will need to put this code: from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class NotFoundPageHandler(webapp.RequestHandler): def ...
How can I quantify difference between two images?
Here's what I would like to do: I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much looks the same, I don't want to store the latest snapshot. I imagine there's some way of quantifying the difference, and I w...
General idea Option 1: Load both images as arrays (scipy.misc.imread) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference. Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than ima...
Daemon Threads Explanation
In the Python documentation it says: A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. Does anyone have a clearer explanation of what that means or a practi...
Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited. Without daemon threads, you'd have to keep track of them, and ...
Getting the pattern back from a compiled re?
Assume I have created a compiled re: x = re.compile('^\d+$') Is there a way to extract the pattern string (^\d+$) back from the x?
You can get it back with x.pattern from the Python documentation on Regular Expression Objects
How to get a complete list of object's methods and attributes?
dir(re.compile(pattern)) does not return pattern as one of the lists's elements. Namely it returns: ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] According to the manual, it is supposed to contain the object's attributes' names, the names of its class's...
For the complete list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the getattr built-in function. As the user can reimplement __getattr__, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The ...
How to convert a file to utf-8 in Python?
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: iconv -t utf-8 $file > converted/$file # this is shell code Thanks!
You can use the codecs module, like this: import codecs BLOCKSIZE = 1048576 # or some other, desired size in bytes with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile: with codecs.open(targetFileName, "w", "utf-8") as targetFile: while True: contents = sourceFile.read(BLO...
Converting XML to JSON using Python?
I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can. So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're look...
xmltodict (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this "standard". It is Expat-based, so it's very fast and doesn't need to load the whole XML tree in memory. Once you have that data structure, you can serialize it to JSON: import xmltodict, json o = xmlto...
Is there a function in Python to print all the current properties and values of an object?
So what I'm looking for here is something like PHP's print_r function. This is so I can debug my scripts by seeing what's the state of the object in question.
You want vars() mixed with pprint: from pprint import pprint pprint (vars(your_object))
How do I log an exception at warning- or info-level with trace back using the python logging framework?
Using something like this: try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) I would rather not have it on the error-level cause in my special case it is ...
From The logging documentation: There are two keyword arguments in kwargs which are inspected: exc_info which, if it does not evaluate as false, causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) is provided, it is used; other...
In Django how do I notify a parent when a child is saved in a foreign key relationship?
I have the following two models: class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().d...
What you want to look into is Django's signals (check out this page too), specifically the model signals--more specifically, the post_save signal. Signals are Django's version of a plugin/hook system. The post_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if ...