instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
Print in terminal with colors using Python?
How can I output colored text to the terminal, in Python? What is the best Unicode symbol to represent a solid block?
This somewhat depends on what platform you are on. The most common way to do this is by printing ANSI escape sequences. For a simple example, here's some python code from the blender build scripts: class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' To use code like this, you can do something like print bcolors.WARNING + "Warning: No active frommets remain. Continue?" + bcolors.ENDC This will work on unixes including OS X, linux and windows (provided you use ANSICON, or in Windows 10 provided you enable VT100 emulation). There are ansi codes for setting the color, moving the cursor, and more. If you are going to get complicated with this (and it sounds like you are if you are writing a game), you should look into the "curses" module, which handles a lot of the complicated parts of this for you. The Python Curses HowTO is a good introduction. If you are not using extended ASCII (i.e. not on a PC), you are stuck with the ascii characters below 127, and '#' or '@' is probably your best bet for a block. If you can ensure your terminal is using a IBM extended ascii character set, you have many more options. Characters 176, 177, 178 and 219 are the "block characters". Some modern text-based programs, such as "Dwarf Fortress", emulate text mode in a graphical mode, and use images of the classic PC font. You can find some of these bitmaps that you can use on the Dwarf Fortress Wiki see (user-made tilesets). The Text Mode Demo Contest has more resources for doing graphics in text mode. Hmm.. I think got a little carried away on this answer. I am in the midst of planning an epic text-based adventure game, though. Good luck with your colored text!
Connect to Exchange mailbox with Python
I need to connect to an Exchange mailbox in a Python script, without using any profile setup on the local machine (including using Outlook). If I use win32com to create a MAPI.Session I could logon (with the Logon() method) with an existing profile, but I want to just provide a username & password. Is this possible? If so, could someone provide example code? I would prefer if it only used the standard library and the pywin32 package. Unfortunately, enabling IMAP access for the Exchange server (and then using imaplib) is not possible. In case it is necessary: all the script will be doing is connecting to the mailbox, and running through the messages in the Inbox, retrieving the contents. I can handle writing the code for that, if I can get a connection in the first place! To clarify regarding Outlook: Outlook will be installed on the local machine, but it does not have any accounts setup (i.e. all the appropriate libraries will be available, but I need to operate independently from anything setup inside of Outlook).
I know this is an old thread, but... If you're using Exchange 2007 or newer, or Office365, take a look at Exchange Web Services. It's a pretty comprehensive SOAP-based interface for Exchange, and you can do pretty much anything Outlook is able to do, including delegate or impersonation access to other user accounts. http://msdn.microsoft.com/en-us/library/bb204119.aspx UPDATE: I have released a Python EWS client on PyPI that supports autodiscover, calendars, inbox, tasks and contacts
Can I use named groups in a Perl regex to get the results in a hash?
Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the $n values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible. Python does it like so: >>> import re >>> regex = re.compile(r'(?P<count>\d+)') >>> match = regex.match('42') >>> print match.groupdict() {'count': '42'} I know the ?P indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?
Perl uses (?<NAME>pattern) to specify names captures. You have to use the %+ hash to retrieve them. $variable =~ /(?<count>\d+)/; print "Count is $+{count}"; This is only supported on Perl 5.10 and higher though.
What's the simplest way to access mssql with python or ironpython?
I've got mssql 2005 running on my personal computer with a database I'd like to run some python scripts on. I'm looking for a way to do some really simple access on the data. I'd like to run some select statements, process the data and maybe have python save a text file with the results. Unfortunately, even though I know a bit about python and a bit about databases, it's very difficult for me to tell, just from reading, if a library does what I want. Ideally, I'd like something that works for other versions of mssql, is free of charge and licensed to allow commercial use, is simple to use, and possibly works with ironpython.
Everyone else seems to have the cPython -> SQL Server side covered. If you want to use IronPython, you can use the standard ADO.NET API to talk to the database: import clr clr.AddReference('System.Data') from System.Data.SqlClient import SqlConnection, SqlParameter conn_string = 'data source=<machine>; initial catalog=<database>; trusted_connection=True' connection = SqlConnection(conn_string) connection.Open() command = connection.CreateCommand() command.CommandText = 'select id, name from people where group_id = @group_id' command.Parameters.Add(SqlParameter('group_id', 23)) reader = command.ExecuteReader() while reader.Read(): print reader['id'], reader['name'] connection.Close() If you've already got IronPython, you don't need to install anything else. Lots of docs available here and here.
Filter a Python list by predicate
I would want to do something like: >>> lst = [1, 2, 3, 4, 5] >>> lst.find(lambda x: x % 2 == 0) 2 >>> lst.findall(lambda x: x % 2 == 0) [2, 4] Is there anything nearing such behavior in Python's standard libraries? I know it's very easy to roll-your-own here, but I'm looking for a more standard way.
You can use the filter method: >>> lst = [1, 2, 3, 4, 5] >>> filter(lambda x: x % 2 == 0, lst) [2, 4] or a list comprehension: >>> lst = [1, 2, 3, 4, 5] >>> [x for x in lst if x %2 == 0] [2, 4] EDIT: for find (single element), you could try: >>> (x for x in lst if x % 2 == 0).next() 2 Though that would throw an exception if nothing matches, so you'd probably want to wrap it in a try/catch. The () brackets make this a generator expression rather than a list comprehension. Personally though I'd just use the regular filter/comprehension and take the first element (if there is one). These raise an exception if nothing is found filter(lambda x: x % 2 == 0, lst)[0] [x for x in lst if x %2 == 0][0] These return empty lists filter(lambda x: x % 2 == 0, lst)[:1] [x for x in lst if x %2 == 0][:1]
Is it possible for a running python program to overwrite itself?
Is it possible for a python script to open its own source file and overwrite it? The idea was to have a very simple and very dirty way for a python script to download an update of itself so that the next time it is run it would be an updated version.
That's certainly possible. After the script is loaded/imported, the Python interpreter won't access it anymore, except when printing source line in a exception stack trace. Any pyc file will be regenerated the next time as the source file is newer than the pyc.
How do I split a huge text file in python
I have a huge text file (~1GB) and sadly the text editor I use won't read such a large file. However, if I can just split it into two or three parts I'll be fine, so, as an exercise I wanted to write a program in python to do it. What I think I want the program to do is to find the size of a file, divide that number into parts, and for each part, read up to that point in chunks, writing to a filename.nnn output file, then read up-to the next line-break and write that, then close the output file, etc. Obviously the last output file just copies to the end of the input file. Can you help me with the key filesystem related parts: filesize, reading and writing in chunks and reading to a line-break? I'll be writing this code test-first, so there's no need to give me a complete answer, unless its a one-liner ;-)
linux has a split command split -l 100000 file.txt would split into files of equal 100,000 line size
How do I filter ForeignKey choices in a Django ModelForm?
Say I have the following in my models.py: class Company(models.Model): name = ... class Rate(models.Model): company = models.ForeignKey(Company) name = ... class Client(models.Model): name = ... company = models.ForeignKey(Company) base_rate = models.ForeignKey(Rate) I.e. there are multiple Companies, each having a range of Rates and Clients. Each Client should have a base Rate that is chosen from it's parent Company's Rates, not another Company's Rates. When creating a form for adding a Client, I would like to remove the Company choices (as that has already been selected via an "Add Client" button on the Company page) and limit the Rate choices to that Company as well. How do I go about this in Django 1.0? My current forms.py file is just boilerplate at the moment: from models import * from django.forms import ModelForm class ClientForm(ModelForm): class Meta: model = Client And the views.py is also basic: from django.shortcuts import render_to_response, get_object_or_404 from models import * from forms import * def addclient(request, company_id): the_company = get_object_or_404(Company, id=company_id) if request.POST: form = ClientForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(the_company.get_clients_url()) else: form = ClientForm() return render_to_response('addclient.html', {'form': form, 'the_company':the_company}) In Django 0.96 I was able to hack this in by doing something like the following before rendering the template: manipulator.fields[0].choices = [(r.id,r.name) for r in Rate.objects.filter(company_id=the_company.id)] ForeignKey.limit_choices_to seems promising but I don't know how to pass in the_company.id and I'm not clear if that will work outside the Admin interface anyway. Thanks. (This seems like a pretty basic request but if I should redesign something I'm open to suggestions.)
ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField. So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly. form.rate.queryset = Rate.objects.filter(company_id=the_company.id) If you take the default ModelForm object, form.fields["rate"].queryset = ... This is done explicitly in the view. No hacking around.
Short Description of Scoping Rules
What exactly are the Python scoping rules? If I have some code: code1 class Foo: code2 def spam..... code3 for code4..: code5 x() Where is x found? Some possible choices include the list above: In the enclosing source file In the class namespace In the function definition In the for loop index variable Inside the for loop Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently? There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.
Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply) LEGB Rule. L, Local — Names assigned in any way within a function (def or lambda)), and not declared global in that function. E, Enclosing function locals — Name in the local scope of any and all enclosing functions (def or lambda), from inner to outer. G, Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file. B, Built-in (Python) — Names preassigned in the built-in names module : open,range,SyntaxError,... So, in the case of code1 class Foo: code2 def spam..... code3 for code4..: code5 x() The for loop does not have its own namespace. In LEGB order, the scopes would be L : local, in the current def. E : Enclosed function, any enclosing functions (if def spam was in another def) G : Global. Were there any declared globally in the module? B : Any builtin x() in Python.
Polling the keyboard (detect a keypress) in python
How can I poll the keyboard from a console python app? Specifically, I would like to do something akin to this in the midst of a lot of other I/O activities (socket selects, serial port access, etc.): while 1: # doing amazing pythonic embedded stuff # ... # periodically do a non-blocking check to see if # we are being told to do something else x = keyboard.read(1000, timeout = 0) if len(x): # ok, some key got pressed # do something What is the correct pythonic way to do this on Windows? Also, portability to Linux wouldn't be bad, though it's not required.
The standard approach is to use the select module. However, this doesn't work on Windows. For that, you can use the msvcrt module's keyboard polling. Often, this is done with multiple threads -- one per device being "watched" plus the background processes that might need to be interrupted by the device.
wxPython, Set value of StaticText()
I am making a little GUI frontend for a app at the moment using wxPython. I am using wx.StaticText() to create a place to hold some text, code below: content = wx.StaticText(panel, -1, "Text Here", style=wx.ALIGN_CENTRE) I have a button when clicked retrieves data from MySQL, I am wanting to change the value of the StaticText() to the MySQL data or what else could I use the hold the data. I have tried using the below method: contents = wx.TextCtrl(bkg, style=wx.TE_MULTILINE | wx.HSCROLL) content.SetValue("New Text") This displays the data fine but after the data is loaded you can edit the data and I do not want this. Hope you guys understand what I am trying to do, I am new to Python :) Cheers
If you are using a wx.StaticText() you can just: def __init__(self, parent, *args, **kwargs): #frame constructor, etc. self.some_text = wx.StaticText(panel, wx.ID_ANY, label="Awaiting MySQL Data", style=wx.ALIGN_CENTER) def someFunction(self): mysql_data = databasemodel.returnData() #query your database to return a string self.some_text.SetLabel(mysql_data) As litb mentioned, the wxWidgets docs are often much easier to use than the wxPython docs. In order to see that the SetLabel() function can be applied to a wx.StaticText instance, you have to travel up the namespace hierarchy in the wxPython docs to the wxWindow superclass, from which wx.StaticText is subclassed. There are a few things different in wxPython from wxWidgets, and it can be challenging to find out what they are. Fortunately, a lot of the time, the differences are convenience functions that have been added to wxPython and are not found in wxWidgets.
Python object deleting itself
Why won't this work? I'm trying to make an instance of a class delete itself. >>> class A(): def kill(self): del self >>> a = A() >>> a.kill() >>> a <__main__.A instance at 0x01F23170>
'self' is only a reference to the object. 'del self' is deleting the 'self' reference from the local namespace of the kill function, instead of the actual object. To see this for yourself, look at what happens when these two functions are executed: >>> class A(): ... def kill_a(self): ... print self ... del self ... def kill_b(self): ... del self ... print self ... >>> a = A() >>> b = A() >>> a.kill_a() <__main__.A instance at 0xb771250c> >>> b.kill_b() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in kill_b UnboundLocalError: local variable 'self' referenced before assignment
How do I fix wrongly nested / unclosed HTML tags?
I need to sanitize HTML submitted by the user by closing any open tags with correct nesting order. I have been looking for an algorithm or Python code to do this but haven't found anything except some half-baked implementations in PHP, etc. For example, something like <p> <ul> <li>Foo becomes <p> <ul> <li>Foo</li> </ul> </p> Any help would be appreciated :)
using BeautifulSoup: from BeautifulSoup import BeautifulSoup html = "<p><ul><li>Foo" soup = BeautifulSoup(html) print soup.prettify() gets you <p> <ul> <li> Foo </li> </ul> </p> As far as I know, you can't control putting the <li></li> tags on separate lines from Foo. using Tidy: import tidy html = "<p><ul><li>Foo" print tidy.parseString(html, show_body_only=True) gets you <ul> <li>Foo</li> </ul> Unfortunately, I know of no way to keep the <p> tag in the example. Tidy interprets it as an empty paragraph rather than an unclosed one, so doing print tidy.parseString(html, show_body_only=True, drop_empty_paras=False) comes out as <p></p> <ul> <li>Foo</li> </ul> Ultimately, of course, the <p> tag in your example is redundant, so you might be fine with losing it. Finally, Tidy can also do indenting: print tidy.parseString(html, show_body_only=True, indent=True) becomes <ul> <li>Foo </li> </ul> All of these have their ups and downs, but hopefully one of them is close enough.
unpacking an array of arguments in php
Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so: args = [3, 6] range(*args) # call with arguments unpacked from a list This is equivalent to: range(3, 6) Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?
You can use call_user_func_array() to achieve that: call_user_func_array("range", $args); to use your example.
How do I find userid by login (Python under *NIX)
I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login? I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?
You might want to have a look at the pwd module in the python stdlib, for example: import pwd pw = pwd.getpwnam("nobody") uid = pw.pw_uid it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually
Python UPnP/IGD Client Implementation?
I am searching for an open-source implementation of an UPnP client in Python, and more specifically of its Internet Gateway Device (IGD) part. For now, I have only been able to find UPnP Media Server implementations, in projects such as PyMediaServer, PyMedS, BRisa or Coherence. I am sure I could use those code bases as a start, but the Media Server part will introduce unneeded complexity. So can you recommend a client UPnP (and hopefully IGD) Python library? An alternative would be to dispatch calls to a C library such as MiniUPnP, but I would much prefer a pure Python implementation. Update: an interesting, kind of related discussion of SSDP and UPnP is available on StackOverflow.
MiniUPnP source code contains a Python sample code using the C library as an extension module (see testupnpigd.py), which I consider as a proper solution to my problem. Rationale: this is not the pure Python solution I was looking for, but: significant effort has already been invested in this library, it is lightweight (it does not address Media Server issues), IGD is typically only used at connection setup, so not integrating it tighter with the Python code does not seem like an issue, as a bonus, it also provides a NAT-PNP implementation (the Apple concurrent of IGD, part of Bonjour).
Convert a string to preexisting variable names
How do I convert a string to the variable name in Python? For example, if the program contains a object named self.post that contains a variable named, I want to do something like: somefunction("self.post.id") = |Value of self.post.id|
Note: do not use eval in any case where you are getting the name to look up from user entered input. For example, if this comes from a web page, there is nothing preventing anyone from entering: __import__("os").system("Some nasty command like rm -rf /*") as the argument. Better is to limit to well-defined lookup locations such as a dictionary or instance using getattr(). For example, to find the "post" value on self, use: varname = "post" value = getattr(self, varname) # Gets self.post Similarly to set it, use setattr(): value = setattr(self, varname, new_value) To handle fully qualified names, like "post.id", you could use something like the below functions in place of getattr() / setattr(). def getattr_qualified(obj, name): for attr in name.split("."): obj = getattr(obj, attr) return obj def setattr_qualified(obj, name, value): parts = name.split(".") for attr in parts[:-1]: obj = getattr(obj, attr) setattr(obj, parts[-1], value)
Turn a string into a valid filename in Python
I have a string that I want to use as a filename, so I want to remove all characters that wouldn't be allowed in filenames, using Python. I'd rather be strict than otherwise, so let's say I want to retain only letters, digits, and a small set of other characters like "_-.() ". What's the most elegant solution? The filename needs to be valid on multiple operating systems (Windows, Linux and Mac OS) - it's an MP3 file in my library with the song title as the filename, and is shared and backed up between 3 machines.
You can look at the Django framework for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly. Their template/defaultfilters.py (at around line 183) defines a function, slugify, that's probably the gold standard for this kind of thing. Essentially, their code is the following. def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) value = unicode(re.sub('[-\s]+', '-', value)) There's more, but I left it out, since it doesn't address slugification, but escaping.
How can one mock/stub python module like urllib
I need to test a function that needs to query a page on an external server using urllib.urlopen (it also uses urllib.urlencode). The server could be down, the page could change; I can't rely on it for a test. What is the best way to control what urllib.urlopen returns?
Another simple approach is to have your test override urllib's urlopen() function. For example, if your module has import urllib def some_function_that_uses_urllib(): ... urllib.urlopen() ... You could define your test like this: import mymodule def dummy_urlopen(url): ... mymodule.urllib.urlopen = dummy_urlopen Then, when your tests invoke functions in mymodule, dummy_urlopen() will be called instead of the real urlopen(). Dynamic languages like Python make it super easy to stub out methods and classes for testing. See my blog posts at http://softwarecorner.wordpress.com/ for more information about stubbing out dependencies for tests.
How do I use subprocess.Popen to connect multiple processes by pipes?
How do I execute the following shell command using the Python subprocess module? echo "input data" | awk -f script.awk | sort > outfile.txt The input data will come from a string, so I don't actually need echo. I've got this far, can anyone explain how I get it to pipe through sort too? p_awk = subprocess.Popen(["awk","-f","script.awk"], stdin=subprocess.PIPE, stdout=file("outfile.txt", "w")) p_awk.communicate( "input data" ) UPDATE: Note that while the accepted answer below doesn't actually answer the question as asked, I believe S.Lott is right and it's better to avoid having to solve that problem in the first place!
You'd be a little happier with the following. import subprocess awk_sort = subprocess.Popen( "awk -f script.awk | sort > outfile.txt", stdin=subprocess.PIPE, shell=True ) awk_sort.communicate( b"input data\n" ) Delegate part of the work to the shell. Let it connect two processes with a pipeline. You'd be a lot happier rewriting 'script.awk' into Python, eliminating awk and the pipeline. Edit. Some of the reasons for suggesting that awk isn't helping. [There are too many reasons to respond via comments.] Awk is adding a step of no significant value. There's nothing unique about awk's processing that Python doesn't handle. The pipelining from awk to sort, for large sets of data, may improve elapsed processing time. For short sets of data, it has no significant benefit. A quick measurement of awk >file ; sort file and awk | sort will reveal of concurrency helps. With sort, it rarely helps because sort is not a once-through filter. The simplicity of "Python to sort" processing (instead of "Python to awk to sort") prevents the exact kind of questions being asked here. Python -- while wordier than awk -- is also explicit where awk has certain implicit rules that are opaque to newbies, and confusing to non-specialists. Awk (like the shell script itself) adds Yet Another Programming language. If all of this can be done in one language (Python), eliminating the shell and the awk programming eliminates two programming languages, allowing someone to focus on the value-producing parts of the task. Bottom line: awk can't add significant value. In this case, awk is a net cost; it added enough complexity that it was necessary to ask this question. Removing awk will be a net gain. Sidebar Why building a pipeline (a | b) is so hard. When the shell is confronted with a | b it has to do the following. Fork a child process of the original shell. This will eventually become b. Build an os pipe. (not a Python subprocess.PIPE) but call os.pipe() which returns two new file descriptors that are connected via common buffer. At this point the process has stdin, stdout, stderr from its parent, plus a file that will be "a's stdout" and "b's stdin". Fork a child. The child replaces its stdout with the new a's stdout. Exec the a process. The b child closes replaces its stdin with the new b's stdin. Exec the b process. The b child waits for a to complete. The parent is waiting for b to complete. I think that the above can be used recursively to spawn a | b | c, but you have to implicitly parenthesize long pipelines, treating them as if they're a | (b | c). Since Python has os.pipe(), os.exec() and os.fork(), and you can replace sys.stdin and sys.stdout, there's a way to do the above in pure Python. Indeed, you may be able to work out some shortcuts using os.pipe() and subprocess.Popen. However, it's easier to delegate that operation to the shell.
Does python optimize modules when they are imported multiple times?
If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again? For example: I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so import MyLib ReallyBigLib = MyLib.SomeModule.ReallyBigLib or just import MyLib import ReallyBigLib
Python modules could be considered as singletons... no matter how many times you import them they get initialized only once, so it's better to do: import MyLib import ReallyBigLib Relevant documentation on the import statement: https://docs.python.org/2/reference/simple_stmts.html#the-import-statement Once the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), searching for the module or package can begin. The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import. The imported modules are cached in sys.modules: This is a dictionary that maps module names to modules which have already been loaded. This can be manipulated to force reloading of modules and other tricks. Note that removing a module from this dictionary is not the same as calling reload() on the corresponding module object.
How do I copy files with specific file extension to a folder in my python (version 2.5) script?
I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use os.walk but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.
import glob, os, shutil files = glob.iglob(os.path.join(source_dir, "*.ext")) for file in files: if os.path.isfile(file): shutil.copy2(file, dest_dir) Read the documentation of the shutil module to choose the function that fits your needs (shutil.copy(), shutil.copy2() or shutil.copyfile()).
How do I zip the contents of a folder using python (version 2.5)?
Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. Is this possible? And how could I go about doing it? A point in the right direction (i.e. a link with an example) or an example that I can see would be extremely helpful. Thanks in advance.
On python 2.7 you might use: shutil.make_archive(base_name, format[, root_dir[, base_dir[, verbose[, dry_run[, owner[, group[, logger]]]]]]]). base_name archive name minus extension format format of the archive root_dir directory to compress. For example shutil.make_archive(target_file, format="bztar", root_dir=compress_me)
Performance comparison of Thrift, Protocol Buffers, JSON, EJB, other?
We're looking into transport/protocol solutions and were about to do various performance tests, so I thought I'd check with the community if they've already done this: Has anyone done server performance tests for simple echo services as well as serialization/deserialization for various messages sizes comparing EJB3, Thrift, and Protocol Buffers on Linux? Primarily languages will be Java, C/C++, Python, and PHP. Update: I'm still very interested in this, if anyone has done any further benchmarks please let me know. Also, very interesting benchmark showing compressed JSON performing similar / better than Thrift / Protocol Buffers, so I'm throwing JSON into this question as well.
Latest comparison available here at the thrift-protobuf-compare project wiki. It includes many other serialization libraries.
Why doesn't xpath work when processing an XHTML document with lxml (in python)?
I am testing against the following test document: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>hi there</title> </head> <body> <img class="foo" src="bar.png"/> </body> </html> If I parse the document using lxml.html, I can get the IMG with an xpath just fine: >>> root = lxml.html.fromstring(doc) >>> root.xpath("//img") [<Element img at 1879e30>] However, if I parse the document as XML and try to get the IMG tag, I get an empty result: >>> tree = etree.parse(StringIO(doc)) >>> tree.getroot().xpath("//img") [] I can navigate to the element directly: >>> tree.getroot().getchildren()[1].getchildren()[0] <Element {http://www.w3.org/1999/xhtml}img at f56810> But of course that doesn't help me process arbitrary documents. I would also expect to be able to query etree to get an xpath expression that will directly identify this element, which, technically I can do: >>> tree.getpath(tree.getroot().getchildren()[1].getchildren()[0]) '/*/*[2]/*' >>> tree.getroot().xpath('/*/*[2]/*') [<Element {http://www.w3.org/1999/xhtml}img at fa1750>] But that xpath is, again, obviously not useful for parsing arbitrary documents. Obviously I am missing some key issue here, but I don't know what it is. My best guess is that it has something to do with namespaces but the only namespace defined is the default and I don't know what else I might need to consider in regards to namespaces. So, what am I missing?
The problem is the namespaces. When parsed as XML, the img tag is in the http://www.w3.org/1999/xhtml namespace since that is the default namespace for the element. You are asking for the img tag in no namespace. Try this: >>> tree.getroot().xpath( ... "//xhtml:img", ... namespaces={'xhtml':'http://www.w3.org/1999/xhtml'} ... ) [<Element {http://www.w3.org/1999/xhtml}img at 11a29e0>]
Create a zip file from a generator in Python?
I've got a large amount of data (a couple gigs) I need to write to a zip file in Python. I can't load it all into memory at once to pass to the .writestr method of ZipFile, and I really don't want to feed it all out to disk using temporary files and then read it back. Is there a way to feed a generator or a file-like object to the ZipFile library? Or is there some reason this capability doesn't seem to be supported? By zip file, I mean zip file. As supported in the Python zipfile package.
The only solution is to rewrite the method it uses for zipping files to read from a buffer. It would be trivial to add this to the standard libraries; I'm kind of amazed it hasn't been done yet. I gather there's a lot of agreement the entire interface needs to be overhauled, and that seems to be blocking any incremental improvements. import zipfile, zlib, binascii, struct class BufferedZipFile(zipfile.ZipFile): def writebuffered(self, zipinfo, buffer): zinfo = zipinfo zinfo.file_size = file_size = 0 zinfo.flag_bits = 0x00 zinfo.header_offset = self.fp.tell() self._writecheck(zinfo) self._didModify = True zinfo.CRC = CRC = 0 zinfo.compress_size = compress_size = 0 self.fp.write(zinfo.FileHeader()) if zinfo.compress_type == zipfile.ZIP_DEFLATED: cmpr = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15) else: cmpr = None while True: buf = buffer.read(1024 * 8) if not buf: break file_size = file_size + len(buf) CRC = binascii.crc32(buf, CRC) & 0xffffffff if cmpr: buf = cmpr.compress(buf) compress_size = compress_size + len(buf) self.fp.write(buf) if cmpr: buf = cmpr.flush() compress_size = compress_size + len(buf) self.fp.write(buf) zinfo.compress_size = compress_size else: zinfo.compress_size = file_size zinfo.CRC = CRC zinfo.file_size = file_size position = self.fp.tell() self.fp.seek(zinfo.header_offset + 14, 0) self.fp.write(struct.pack("<LLL", zinfo.CRC, zinfo.compress_size, zinfo.file_size)) self.fp.seek(position, 0) self.filelist.append(zinfo) self.NameToInfo[zinfo.filename] = zinfo
Dynamically update ModelForm's Meta class
I am hoping to dynamically update a ModelForm's inline Meta class from my view. Although this code seems to update the exclude list in the Meta class, the output from as_p(), as_ul(), etc does not reflect the updated Meta exclude. I assume then that the html is generated when the ModelForm is created not when the as_*() is called. Is there a way to force the update of the HTML? Is this even the best way to do it? I just assumed this should work. Thoughts? from django.forms import ModelForm from testprogram.online_bookings.models import Passenger class PassengerInfoForm(ModelForm): def set_form_excludes(self, exclude_list): self.Meta.exclude = excludes_list class Meta: model = Passenger exclude = []
The Meta class is used to dynamically construct the form definition - so by the time you've created the ModelForm instance, the fields not in the exclude have already been added as the new object's attributes. The normal way to do it would be to just have multiple class definitions for each possible exclude list. But if you want the form itself to be dynamic, you'll have to create a class definition on the fly. Something like: def get_form(exclude_list): class MyForm(ModelForm): class Meta: model = Passenger exclude = exclude_list return MyForm form_class = get_form(('field1', 'field2')) form = form_class() UPDATE: I just revisited this post and thought I'd post a little more idiomatic way to handle a dynamic class: def PassengerForm(exclude_list, *args, **kwargs): class MyPassengerForm(ModelForm): class Meta: model = Passenger exclude = exclude_list def __init__(self): super(MyPassengerForm, self).__init__(*args, **kwargs) return MyPassengerForm() form = PassengerForm(('field1', 'field2'))
Django Template Variables and Javascript
When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}. Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.
The {{variable}} is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text. Having said that, you can put this kind of substitution into your JavaScript. <script type="text/javascript"> var a = "{{someDjangoVariable}}"; </script> This gives you "dynamic" javascript.
Validating with an XML schema in Python
I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema. How do I do this in Python? I'd prefer something using the standard library, but I can install a third-party package if necessary.
I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check Validation with lxml. The page also lists how to use lxml to validate with other schema types.
How to unquote a urlencoded unicode string in python?
I have a unicode string like "Tanım" which is encoded as "Tan%u0131m" somehow. How can i convert this encoded string back to original unicode. Apparently urllib.unquote does not support unicode.
%uXXXX is a non-standard encoding scheme that has been rejected by the w3c, despite the fact that an implementation continues to live on in JavaScript land. The more common technique seems to be to UTF-8 encode the string and then % escape the resulting bytes using %XX. This scheme is supported by urllib.unquote: >>> urllib2.unquote("%0a") '\n' Unfortunately, if you really need to support %uXXXX, you will probably have to roll your own decoder. Otherwise, it is likely to be far more preferable to simply UTF-8 encode your unicode and then % escape the resulting bytes. A more complete example: >>> u"Tanım" u'Tan\u0131m' >>> url = urllib.quote(u"Tanım".encode('utf8')) >>> urllib.unquote(url).decode('utf8') u'Tan\u0131m'
Python - Backslash Quoting in String Literals
I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example: >>> foo = 'baz "\"' >>> foo 'baz ""' So instead of baz "\" like I want I'm getting baz "". If I then try to escape the backslash, it doesn't help either: >>> foo = 'baz "\\"' >>> foo 'baz "\\"' Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?
You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :) >>> foo = 'baz "\\"' >>> foo 'baz "\\"' >>> print foo baz "\" Incidentally, there's another string form which might be a bit clearer: >>> print r'baz "\"' baz "\"
Dynamic module import in Python
I'm writing a Python application that takes as a command as an argument, for example: $ python myapp.py command1 I want the application to be extensible, that is, to be able to add new modules that implement new commands without having to change the main application source. The tree looks something like: myapp/ __init__.py commands/ __init__.py command1.py command2.py foo.py bar.py So I want the application to find the available command modules at runtime and execute the appropriate one. Currently this is implemented something like: command = sys.argv[1] try: command_module = __import__("myapp.commands.%s" % command, fromlist=["myapp.commands"]) except ImportError: # Display error message command_module.run() This works just fine, I'm just wondering if there is possibly a more idiomatic way to accomplish what we are doing with this code. Note that I specifically don't want to get in to using eggs or extension points. This is not an open-source project and I don't expect there to be "plugins". The point is to simplify the main application code and remove the need to modify it each time a new command module is added.
With Python older than 2.7/3.1, that's pretty much how you do it. For newer versions, see importlib.import_module for 2.7+ and for 3.1+. You can use exec if you want to as well. Note you can import a list of modules by doing this: >>> moduleNames = ['sys', 'os', 're', 'unittest'] >>> moduleNames ['sys', 'os', 're', 'unittest'] >>> modules = map(__import__, moduleNames) Ripped straight from Dive Into Python.
Which language is easiest and fastest to work with XML content?
We have developers with knowledge of these languages - Ruby , Python, .Net or Java. We are developing an application which will mainly handle XML documents. Most of the work is to convert predefined XML files into database tables, providing mapping between XML documents through database, creating reports from database etc. Which language will be the easiest and fastest to work with? (It is a web-app)
A dynamic language rules for this. Why? The mappings are easy to code and change. You don't have to recompile and rebuild. Indeed, with a little cleverness, you can have your "XML XPATH to a Tag -> DB table-field" mappings as disjoint blocks of Python code that your main application imports. The block of Python code is your configuration file. It's not an .ini file or a .properties file that describes a configuration. It is the configuration. We use Python, xml.etree and the SQLAlchemy (to separate the SQL out of your programs) for this because we're up and running with very little effort and a great deal of flexibility. source.py """A particular XML parser. Formats change, so sometimes this changes, too.""" import xml.etree.ElementTree as xml class SSXML_Source( object ): ns0= "urn:schemas-microsoft-com:office:spreadsheet" ns1= "urn:schemas-microsoft-com:office:excel" def __init__( self, aFileName, *sheets ): """Initialize a XML source. XXX - Create better sheet filtering here, in the constructor. @param aFileName: the file name. """ super( SSXML_Source, self ).__init__( aFileName ) self.log= logging.getLogger( "source.PCIX_XLS" ) self.dom= etree.parse( aFileName ).getroot() def sheets( self ): for wb in self.dom.getiterator("{%s}Workbook" % ( self.ns0, ) ): for ws in wb.getiterator( "{%s}Worksheet" % ( self.ns0, ) ): yield ws def rows( self ): for s in self.sheets(): print s.attrib["{%s}Name" % ( self.ns0, ) ] for t in s.getiterator( "{%s}Table" % ( self.ns0, ) ): for r in t.getiterator( "{%s}Row" % ( self.ns0, ) ): # The XML may not be really useful. # In some cases, you may have to convert to something useful yield r model.py """This is your target object. It's part of the problem domain; it rarely changes. """ class MyTargetObject( object ): def __init__( self ): self.someAttr= "" self.anotherAttr= "" self.this= 0 self.that= 3.14159 def aMethod( self ): """etc.""" pass builder_today.py One of many mapping configurations """One of many builders. This changes all the time to fit specific needs and situations. The goal is to keep this short and to-the-point so that it has the mapping and nothing but the mapping. """ import model class MyTargetBuilder( object ): def makeFromXML( self, element ): result= model.MyTargetObject() result.someAttr= element.findtext( "Some" ) result.anotherAttr= element.findtext( "Another" ) result.this= int( element.findtext( "This" ) ) result.that= float( element.findtext( "that" ) ) return result loader.py """An application that maps from XML to the domain object using a configurable "builder". """ import model import source import builder_1 import builder_2 import builder_today # Configure this: pick a builder is appropriate for the data: b= builder_today.MyTargetBuilder() s= source.SSXML_Source( sys.argv[1] ) for r in s.rows(): data= b.makeFromXML( r ) # ... persist data with a DB save or file write To make changes, you can correct a builder or create a new builder. You adjust the loader source to identify which builder will be used. You can, without too much trouble, make the selection of builder a command-line parameter. Dynamic imports in dynamic languages seem like overkill to me, but they are handy.
Convert a string with date and time to a date
I've got this date time string: post["date"] = "2007-07-18 10:03:19" I'd like to extract just "2007-07-18" as a date. I've seen some reference to strptime but I'm not sure how to use it. How can I extract the date from this string?
The other two answers are fine, but if you actually want the date for something else, you can use the datetime module: from datetime import datetime d = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S') day_string = d.strftime('%Y-%m-%d') It might be overkill for now, but it'll come in useful. You can see all of the format specifiers here.
Python: urllib/urllib2/httplib confusion
I'm trying to test the functionality of a web app by scripting a login sequence in Python, but I'm having some troubles. Here's what I need to do: Do a POST with a few parameters and headers. Follow a redirect Retrieve the HTML body. Now, I'm relatively new to python, but the two things I've tested so far haven't worked. First I used httplib, with putrequest() (passing the parameters within the URL), and putheader(). This didn't seem to follow the redirects. Then I tried urllib and urllib2, passing both headers and parameters as dicts. This seems to return the login page, instead of the page I'm trying to login to, I guess it's because of lack of cookies or something. Am I missing something simple? Thanks.
Focus on urllib2 for this, it works quite well. Don't mess with httplib, it's not the top-level API. What you're noting is that urllib2 doesn't follow the redirect. You need to fold in an instance of HTTPRedirectHandler that will catch and follow the redirects. Further, you may want to subclass the default HTTPRedirectHandler to capture information that you'll then check as part of your unit testing. cookie_handler= urllib2.HTTPCookieProcessor( self.cookies ) redirect_handler= HTTPRedirectHandler() opener = urllib2.build_opener(redirect_handler,cookie_handler) You can then use this opener object to POST and GET, handling redirects and cookies properly. You may want to add your own subclass of HTTPHandler to capture and log various error codes, also.
Use only some parts of Django?
I like Django, but for a particular application I would like to use only parts of it, but I'm not familiar enough with how Django works on the inside, so maybe someone can point me into the right direction as to what I have to check out. Specifically, I want to use: The models and database abstraction The caching API, although I want to avoid database lookups by caching, not HTML generation, and since the caching framework in Django is intended for the latter, I'm not sure yet whether that's really appropriate. I would not use: Templating urlconfigs Or, more exactly, I'm neither using HTTP nor HTML. So basically, I have a different input / output chain than usual. Can this work? My personal killer feature in Django is the Object / database mapping that I can do with the models, so if there's another technology (doesn't have to be Python, I'm in the design phase and I'm pretty agnostic about languages and platforms) that gives me the same abilities, that would be great, too.
I myself use Django for its object/db mapping without using its urlconfigs. Simply create a file called djangosettings.py and insert the necessary configuration, for example: DATABASE_ENGINE = 'oracle' DATABASE_HOST = 'localhost' DATABASE_NAME = 'ORCL' DATABASE_USER = 'scott' DATABASE_PASSWORD = 'tiger' Then in your regular Python code, do import os os.environ["DJANGO_SETTINGS_MODULE"] = "djangosettings" before you import any Django modules. This will let you use Django's object/db mappings without actually having a Django project, so you can use it for standalone scripts or other web applications or whatever you want. As for caching, if you don't want to use Django then you should probably decide what you are using and go from there. I recommend using CherryPy, which doesn't use Django-style regular expression URL mapping, but instead automatically maps URLs to functions based on the function names. There's an example right at the top of the CherryPy home page: http://cherrypy.org/ CherryPy has its own caching system, so you can accomplish exactly the same thing as what Django does but without needing to use Django's urlconfig system.
Best Django 'CMS' component for integration into existing site
So I have a relatively large (enough code that it would be easier to write this CMS component from scratch than to rewrite the app to fit into a CMS) webapp that I want to add basic Page/Menu/Media management too, I've seen several Django pluggables addressing this issue, but many seem targeted as full CMS platforms. Does anyone know of a plugin that can easily integrate with existing templates/views and still sports a powerful/comprehensive admin interface?
I have worked with all three (and more) and they are all built for different use cases IMHO. I would agree that these are the top-teir choices. The grid comparison at djangopluggables.com certainly can make evaluating each of these easier. django-cms is the most full-featured and is something you could actually hand over to clients without being irresponsible. Even though it has features for integrating other apps, it doesn't have the extensibility/integration of FeinCMS or the simplicity of django-page-cms. That being said, I think the consensus is that this is the best Open Source CMS for Django. However, it's docs are a little lacking. update: I have been told that integrating apps into DjangoCMS 2.1 has been improved. FeinCMS - Is a great set of tools for combining and building CMS functionality into your own apps. It's not "out of the box" at all, which means that you can integrate it however you want. It doesn't want to take over your urls.py or control how you route pages. It's probably a prototype for the next-generation of truly pluggable apps in Django. - We are moving from django-page-cms to FeinCMS because our primary models is high volume eCommerce and I have custom content-types I want to integrate that aren't blogs or flash. Good documentation and support as well. Django-page-cms - Is great if you want to just have some "About Us" pages around your principle application. Its menu system is not truly hierarchical and building your page presentation is up to you. But it's very simple, unobtrusive, and very easy to slap into your app and get a navigation going that clients can manage, or even for yourself. It has no docs that I know of, but you won't really need any. Read the code and you will get it all in 30 minutes or less. update Mezzanine - Is a very well designed CMS and one that I have finally settled on for most of my client work, mostly because it has an integrated eCommerce portion. But beyond that it has very extensible page models, and a custom admin interface that a client might be willing to use. It also has the best "out of the box" experience i.e. You can have a full fledged site up with one command.
How do I remove/delete a folder that is not empty with Python?
I am getting an 'access is denied' error when I attempt to delete a folder that is not empty. I used the following command in my attempt: os.remove("/folder_name"). What is the most effective way of removing/deleting a folder/directory that is not empty?
import shutil shutil.rmtree('/folder_name') Standard Library Reference: shutil.rmtree.
Emacs 23 and iPython
Is there anyone out there using iPython with emacs 23? The documents on the emacs wiki are a bit of a muddle and I would be interested in hearing from anyone using emacs for Python development. Do you use the download python-mode and ipython.el? What do you recommend?
I got it working quite well with emacs 23. The only open issue is the focus not returning to the python buffer after sending the buffer to the iPython interpreter. http://www.emacswiki.org/emacs/PythonMode#toc10 (setq load-path (append (list nil "~/.emacs.d/python-mode-1.0/" "~/.emacs.d/pymacs/" "~/.emacs.d/ropemacs-0.6" ) load-path)) (setq py-shell-name "ipython") (defadvice py-execute-buffer (around python-keep-focus activate) "return focus to python code buffer" (save-excursion ad-do-it)) (setenv "PYMACS_PYTHON" "python2.5") (require 'pymacs) (pymacs-load "ropemacs" "rope-") (provide 'python-programming)
What's the best way to find the inverse of datetime.isocalendar()?
The Python datetime.isocalendar() method returns a tuple (ISO_year, ISO_week_number, ISO_weekday) for the given datetime object. Is there a corresponding inverse function? If not, is there an easy way to compute a date given a year, week number and day of the week?
I recently had to solve this problem myself, and came up with this solution: import datetime def iso_year_start(iso_year): "The gregorian calendar date of the first day of the given ISO year" fourth_jan = datetime.date(iso_year, 1, 4) delta = datetime.timedelta(fourth_jan.isoweekday()-1) return fourth_jan - delta def iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" year_start = iso_year_start(iso_year) return year_start + datetime.timedelta(days=iso_day-1, weeks=iso_week-1) A few test cases: >>> iso = datetime.date(2005, 1, 1).isocalendar() >>> iso (2004, 53, 6) >>> iso_to_gregorian(*iso) datetime.date(2005, 1, 1) >>> iso = datetime.date(2010, 1, 4).isocalendar() >>> iso (2010, 1, 1) >>> iso_to_gregorian(*iso) datetime.date(2010, 1, 4) >>> iso = datetime.date(2010, 1, 3).isocalendar() >>> iso (2009, 53, 7) >>> iso_to_gregorian(*iso) datetime.date(2010, 1, 3)
What do I use on linux to make a python program executable
I just installed a linux system (Kubuntu) and was wondering if there is a program to make python programs executable for linux.
Just put this in the first line of your script : #!/usr/bin/env python Make the file executable with chmod +x myfile.py Execute with ./myfile.py
Correct way to detect sequence parameter?
I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don't want it to be restricted to a hardcoded list. In other words, I want to know if the parameter X is a sequence or something I have to convert to a sequence to avoid special-casing later. I could do type(X) in (list, tuple) but there may be other sequence types I'm not aware of, and no common base class. -N. Edit: See my "answer" below for why most of these answers don't help me. Maybe you have something better to suggest.
As of 2.6, use abstract base classes. >>> import collections >>> isinstance([], collections.Sequence) True >>> isinstance(0, collections.Sequence) False Furthermore ABC's can be customized to account for exceptions, such as not considering strings to be sequences. Here an example: import abc import collections class Atomic(object): __metaclass__ = abc.ABCMeta @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(basestring) After registration the Atomic class can be used with isinstance and issubclass: assert isinstance("hello", Atomic) == True This is still much better than a hard-coded list, because you only need to register the exceptions to the rule, and external users of the code can register their own. Note that in Python 3 the syntax for specifying metaclasses changed and the basestring abstract superclass was removed, which requires something like the following to be used instead: class Atomic(metaclass=abc.ABCMeta): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented Atomic.register(str) If desired, it's possible to write code which is compatible both both Python 2.6+ and 3.x, but doing so requires using a slightly more complicated technique which dynamically creates the needed abstract base class, thereby avoiding syntax errors due to the metaclass syntax difference. This is essentially the same as what Benjamin Peterson's six module'swith_metaclass()function does. class _AtomicBase(object): @classmethod def __subclasshook__(cls, other): return not issubclass(other, collections.Sequence) or NotImplemented class Atomic(abc.ABCMeta("NewMeta", (_AtomicBase,), {})): pass try: unicode = unicode except NameError: # 'unicode' is undefined, assume Python >= 3 Atomic.register(str) # str includes unicode in Py3, make both Atomic Atomic.register(bytes) # bytes will also be considered Atomic (optional) else: # basestring is the abstract superclass of both str and unicode types Atomic.register(basestring) # make both types of strings Atomic In versions before 2.6, there are type checkers in theoperatormodule. >>> import operator >>> operator.isSequenceType([]) True >>> operator.isSequenceType(0) False
List of tables, db schema, dump etc using the Python sqlite3 API
For some reason I can't find a way to get the equivalents of sqlite's interactive shell commands: .tables .dump using the Python sqlite3 API. Is there anything like that?
In Python: con = sqlite3.connect('database.db') cursor = con.cursor() cursor.execute("SELECT name FROM sqlite_master WHERE type='table';") print(cursor.fetchall()) Watch out for my other answer. There is a much faster way using pandas.
Python decorator makes function forget that it belongs to a class
I am trying to write a decorator to do logging: def logger(myFunc): def new(*args, **keyargs): print 'Entering %s.%s' % (myFunc.im_class.__name__, myFunc.__name__) return myFunc(*args, **keyargs) return new class C(object): @logger def f(): pass C().f() I would like this to print: Entering C.f but instead I get this error message: AttributeError: 'function' object has no attribute 'im_class' Presumably this is something to do with the scope of 'myFunc' inside 'logger', but I've no idea what.
Claudiu's answer is correct, but you can also cheat by getting the class name off of the self argument. This will give misleading log statements in cases of inheritance, but will tell you the class of the object whose method is being called. For example: from functools import wraps # use this to preserve function signatures and docstrings def logger(func): @wraps(func) def with_logging(*args, **kwargs): print "Entering %s.%s" % (args[0].__class__.__name__, func.__name__) return func(*args, **kwargs) return with_logging class C(object): @logger def f(self): pass C().f() As I said, this won't work properly in cases where you've inherited a function from a parent class; in this case you might say class B(C): pass b = B() b.f() and get the message Entering B.f where you actually want to get the message Entering C.f since that's the correct class. On the other hand, this might be acceptable, in which case I'd recommend this approach over Claudiu's suggestion.
"is" operator behaves unexpectedly with integers
Why does the following behave unexpectedly in Python? >>> a = 256 >>> b = 256 >>> a is b True # This is an expected result >>> a = 257 >>> b = 257 >>> a is b False # What happened here? Why is this False? >>> 257 is 257 True # Yet the literal numbers compare properly I am using Python 2.5.2. Trying some different versions of Python, it appears that Python 2.3.3 shows the above behaviour between 99 and 100. Based on the above, I can hypothesize that Python is internally implemented such that "small" integers are stored in a different way than larger integers and the is operator can tell the difference. Why the leaky abstraction? What is a better way of comparing two arbitrary objects to see whether they are the same when I don't know in advance whether they are numbers or not?
Take a look at this: >>> a = 256 >>> b = 256 >>> id(a) 9987148 >>> id(b) 9987148 >>> a = 257 >>> b = 257 >>> id(a) 11662816 >>> id(b) 11662828 EDIT: Here's what I found in the Python 2 documentation, "Plain Integer Objects" (It's the same for Python 3): The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
How do I randomly select an item from a list using Python?
Assume I have the following list: foo = ['a', 'b', 'c', 'd', 'e'] What is the simplest way to retrieve an item at random from this list?
Use random.choice: import random foo = ['a', 'b', 'c', 'd', 'e'] print(random.choice(foo))
What does functools.wraps do?
In a comment on the answer to another question, someone said they weren't sure what functools.wraps was doing. So I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does functools.wraps do, exactly?
When you use a decorator, you're replacing one function with another. In other words, if you have a decorator def logged(func): def with_logging(*args, **kwargs): print func.__name__ + " was called" return func(*args, **kwargs) return with_logging then when you say @logged def f(x): """does some math""" return x + x * x it's exactly the same as saying def f(x): """does some math""" return x + x * x f = logged(f) and your function f is replaced with the function with_logging. Unfortunately, this means that if you then say print f.__name__ it will print with_logging because that's the name of your new function. In fact, if you look at the docstring for f, it will be blank because with_logging has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument x; instead it'll be listed as taking *args and **kwargs because that's what with_logging takes. If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have functools.wraps. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since wraps is itself a decorator, the following code does the correct thing: from functools import wraps def logged(func): @wraps(func) def with_logging(*args, **kwargs): print func.__name__ + " was called" return func(*args, **kwargs) return with_logging @logged def f(x): """does some math""" return x + x * x print f.__name__ # prints 'f' print f.__doc__ # prints 'does some math'
Why can't I inherit from dict AND Exception in Python?
I got the following class : class ConstraintFailureSet(dict, Exception) : """ Container for constraint failures. It act as a constraint failure itself but can contain other constraint failures that can be accessed with a dict syntax. """ def __init__(self, **failures) : dict.__init__(self, failures) Exception.__init__(self) print isinstance(ConstraintFailureSet(), Exception) True raise ConstraintFailureSet() TypeError: exceptions must be classes, instances, or strings (deprecated), not ConstraintFailureSet What the heck ? And the worst is that I can't try super() since Exception are old based class... EDIT : And, yes, I've tried to switch the order of inheritance / init. EDIT2 : I am using CPython 2.4 on Ubuntu8.10. You newer know is this kind of infos is usefull ;-). Anyway, this little riddle has shut the mouth of 3 of my collegues. You'd be my best-friend-of-the day...
Both Exception and dict are implemented in C. I think you can test this the follwing way: >>> class C(object): pass ... >>> '__module__' in C.__dict__ True >>> '__module__' in dict.__dict__ False >>> '__module__' in Exception.__dict__ False Since Exception and dict have different ideas of how to store their data internally, they are not compatible and thus you cannot inherit from both at the same time. In later versions of Python you should get an Exception the moment you try to define the class: >>> class foo(dict, Exception): ... pass ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict
How to setup setuptools for python 2.6 on Windows?
Is there any way to install setuptools for python 2.6 in Windows without having an .exe installer? There isn't one built at the moment, and the maintainer of setuptools has stated that it's probable be a while before he'll get to it. Does anyone know of a way to install it anyway?
First Option - Online Installation (i.e. remaining connected to the Internet during the entire installation process): Download setuptools-0.6c9.tar.gz Use 7-zip to extract it to a folder(directory) outside your Windows Python installation folder Go the folder (refer step 2) and run ez_setup.py from the corresponding dos (command) prompt Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory Second Option: Download setuptools-0.6c9.tar.gz Download setuptools-0.6c9-py2.6.egg to a folder(directory) outside your Windows Python installation folder Use 7-zip to extract ez_setup.py in the same folder as setuptools-0.6c9-py2.6.egg Go to the corresponding dos prompt and run python ez_setup.py setuptools-0.6c9-py2.6.egg from the command prompt Ensure that your PATH includes the appropriate C:\Python2X\Scripts directory Third Option (assuming that you have Visual Studio 2005 or MinGW on your machine) Download setuptools-0.6c9.tar.gz Use 7-zip to extract it to a folder(directory) outside your Windows Python installation folder Go the folder (refer step 2) and run python setup.py install from the corresponding dos (command) prompt Please provide feedback.
How to quote a string value explicitly (Python DB API/Psycopg2)
For some reasons, I would like to do an explicit quoting of a string value (becoming a part of constructed SQL query) instead of waiting for implicit quotation performed by cursor.execute method on contents of its second parameter. By "implicit quotation" I mean: value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" cursor.execute( query, (value,) ) # value will be correctly quoted I would prefer something like that: value = "Unsafe string" query = "SELECT * FROM some_table WHERE some_char_field = %s;" % \ READY_TO_USE_QUOTING_FUNCTION(value) cursor.execute( query ) # value will be correctly quoted, too Is such low level READY_TO_USE_QUOTING_FUNCTION expected by Python DB API specification (I couldn't find such functionality in PEP 249 document). If not, maybe Psycopg2 provides such function? If not, maybe Django provides such function? I would prefer not to write such function myself...
Ok, so I was curious and went and looked at the source of psycopg2. Turns out I didn't have to go further than the examples folder :) And yes, this is psycopg2-specific. Basically, if you just want to quote a string you'd do this: from psycopg2.extensions import adapt print adapt("Hello World'; DROP DATABASE World;") But what you probably want to do is to write and register your own adapter; In the examples folder of psycopg2 you find the file 'myfirstrecipe.py' there is an example of how to cast and quote a specific type in a special way. If you have objects for the stuff you want to do, you can just create an adapter that conforms to the 'IPsycopgSQLQuote' protocol (see pydocs for the myfirstrecipe.py-example...actually that's the only reference I can find to that name) that quotes your object and then registering it like so: from psycopg2.extensions import register_adapter register_adapter(mytype, myadapter) Also, the other examples are interesting; esp. 'dialtone.py' and 'simple.py'.
In Django, how does one filter a QuerySet with dynamic field lookups?
Given a class: from django.db import models class Person(models.Model): name = models.CharField(max_length=20) Is it possible, and if so how, to have a QuerySet that filters based on dynamic arguments? For example: # Instead of: Person.objects.filter(name__startswith='B') # ... and: Person.objects.filter(name__endswith='B') # ... is there some way, given: filter_by = '{0}__{1}'.format('name', 'startswith') filter_value = 'B' # ... that you can run the equivalent of this? Person.objects.filter(filter_by=filter_value) # ... which will throw an exception, since `filter_by` is not # an attribute of `Person`. Help is much appreciated & thank you in advance.
Python's argument expansion may be used to solve this problem: kwargs = { '{0}__{1}'.format('name', 'startswith'): 'A', '{0}__{1}'.format('name', 'endswith'): 'Z' } Person.objects.filter(**kwargs) This is a very common and useful Python idiom.
Python library to modify MP3 audio without transcoding
I am looking for some general advice about the mp3 format before I start a small project to make sure I am not on a wild-goose chase. My understanding of the internals of the mp3 format is minimal. Ideally, I am looking for a library that would abstract those details away. I would prefer to use Python (but could be convinced otherwise). I would like to modify a set of mp3 files in a fairly simple way. I am not so much interested in the ID3 tags but in the audio itself. I want to be able to delete sections (e.g. drop 10 seconds from the 3rd minute), and insert sections (e.g. add credits to the end.) My understanding is that the mp3 format is lossy, and so decoding it to (for example) PCM format, making the modifications, and then encoding it again to MP3 will lower the audio quality. (I would love to hear that I am wrong.) I conjecture that if I stay in mp3 format, there will be some sort of minimum frame or packet-size to deal with, so the granularity of the operations may be coarser. I can live with that, as long as I get an accuracy of within a couple of seconds. I have looked at PyMedia, but it requires me to migrate to PCM to process the data. Similarly, LAME wants to help me encode, but not access the data in place. I have seen several other libraries that only deal with the ID3 tags. Can anyone recommend a Python MP3 library? Alternatively, can you disabuse me of my assumption that going to PCM and back is bad and avoidable?
If you want to do things low-level, use pymad. It turns MP3s into a buffer of sample data. If you want something a little higher-level, use the Echo Nest Remix API (disclosure: I wrote part of it for my dayjob). It includes a few examples. If you look at the cowbell example (i.e., MoreCowbell.dj), you'll see a fork of pymad that gives you a NumPy array instead of a buffer. That datatype makes it easier to slice out sections and do math on them.
Modern, high performance bloom filter in Python?
I'm looking for a production quality bloom filter implementation in Python to handle fairly large numbers of items (say 100M to 1B items with 0.01% false positive rate). Pybloom is one option but it seems to be showing its age as it throws DeprecationWarning errors on Python 2.5 on a regular basis. Joe Gregorio also has an implementation. Requirements are fast lookup performance and stability. I'm also open to creating Python interfaces to particularly good c/c++ implementations, or even to Jython if there's a good Java implementation. Lacking that, any recommendations on a bit array / bit vector representation that can handle ~16E9 bits?
I recently went down this path as well; though it sounds like my application was slightly different. I was interested in approximating set operations on a large number of strings. You do make the key observation that a fast bit vector is required. Depending on what you want to put in your bloom filter, you may also need to give some thought to the speed of the hashing algorithm(s) used. You might find this library useful. You may also want to tinker with the random number technique used below that only hashes your key a single time. In terms of non-Java bit array implementations: Boost has dynamic_bitset Java has the built in BitSet I built my bloom filter using BitVector. I spent some time profiling and optimizing the library and contributing back my patches to Avi. Go to that BitVector link and scroll down to acknowledgments in v1.5 to see details. In the end, I realized that performance was not a goal of this project and decided against using it. Here's some code I had lying around. I may put this up on google code at python-bloom. Suggestions welcome. from BitVector import BitVector from random import Random # get hashes from http://www.partow.net/programming/hashfunctions/index.html from hashes import RSHash, JSHash, PJWHash, ELFHash, DJBHash # # ryan.a.cox@gmail.com / www.asciiarmor.com # # copyright (c) 2008, ryan cox # all rights reserved # BSD license: http://www.opensource.org/licenses/bsd-license.php # class BloomFilter(object): def __init__(self, n=None, m=None, k=None, p=None, bits=None ): self.m = m if k > 4 or k < 1: raise Exception('Must specify value of k between 1 and 4') self.k = k if bits: self.bits = bits else: self.bits = BitVector( size=m ) self.rand = Random() self.hashes = [] self.hashes.append(RSHash) self.hashes.append(JSHash) self.hashes.append(PJWHash) self.hashes.append(DJBHash) # switch between hashing techniques self._indexes = self._rand_indexes #self._indexes = self._hash_indexes def __contains__(self, key): for i in self._indexes(key): if not self.bits[i]: return False return True def add(self, key): dupe = True bits = [] for i in self._indexes(key): if dupe and not self.bits[i]: dupe = False self.bits[i] = 1 bits.append(i) return dupe def __and__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise AND') return BloomFilter(m=self.m,k=self.k,bits=(self.bits & filter.bits)) def __or__(self, filter): if (self.k != filter.k) or (self.m != filter.m): raise Exception('Must use bloom filters created with equal k / m paramters for bitwise OR') return BloomFilter(m=self.m,k=self.k,bits=(self.bits | filter.bits)) def _hash_indexes(self,key): ret = [] for i in range(self.k): ret.append(self.hashes[i](key) % self.m) return ret def _rand_indexes(self,key): self.rand.seed(hash(key)) ret = [] for i in range(self.k): ret.append(self.rand.randint(0,self.m-1)) return ret if __name__ == '__main__': e = BloomFilter(m=100, k=4) e.add('one') e.add('two') e.add('three') e.add('four') e.add('five') f = BloomFilter(m=100, k=4) f.add('three') f.add('four') f.add('five') f.add('six') f.add('seven') f.add('eight') f.add('nine') f.add("ten") # test check for dupe on add assert not f.add('eleven') assert f.add('eleven') # test membership operations assert 'ten' in f assert 'one' in e assert 'ten' not in e assert 'one' not in f # test set based operations union = f | e intersection = f & e assert 'ten' in union assert 'one' in union assert 'three' in intersection assert 'ten' not in intersection assert 'one' not in intersection Also, in my case I found it useful to have a faster count_bits function for BitVector. Drop this code into BitVector 1.5 and it should give you a more performant bit counting method: def fast_count_bits( self, v ): bits = ( 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 ) return bits[v & 0xff] + bits[(v >> 8) & 0xff] + bits[(v >> 16) & 0xff] + bits[v >> 24]
How to indent Python list-comprehensions?
List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following? allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
It depends on how long they are. I tend to structure them like so: [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout=20) if x.type == 'post' and x.deleted is not False and ... and ...] That way every expression has its own line. If any line becomes too big I like to extract it out in a lambda or expression: transform = lambda x: x.id results = self.db.query(schema.allPostsUuid).execute(timeout=20) condition = lambda x: x.deleted is not False and ... and ... [transform(x) for x in results if condition(x)] And then if a lambda becomes too long it gets promoted to a function.
How to print date in a regular format in Python?
This is my code: import datetime today = datetime.date.today() print today This prints: 2008-11-22 which is exactly what I want BUT....I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code: import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist This prints the following: [datetime.date(2008, 11, 22)] How on earth can I get just a simple date like "2008-11-22"?
The WHY: dates are objects In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings, not timestamps nor anything. Any object in Python have TWO string representations: The regular representation that is used by "print", can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'. The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'. What happened is that when you have printed the date using "print", it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr(). The How: what do you want to do with that? Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects. When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date). One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list). E.G, you want to print all the date in a list : for date in mylist : print str(date) Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-) Practical case, using your code import datetime mylist = [] today = datetime.date.today() mylist.append(today) print mylist[0] # print the date object, not the container ;-) 2008-11-22 # It's better to always use str() because : print "This is a new day : ", mylist[0] # will work This is a new day : 2008-11-22 print "This is a new day : " + mylist[0] # will crash cannot concatenate 'str' and 'datetime.date' objects print "This is a new day : " + str(mylist[0]) This is a new day : 2008-11-22 Advanced date formatting Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method. strftime() expects a string pattern explaining how you want to format your date. E.G : print today.strftime('We are the %d, %b %Y') 'We are the 22, Nov 2008' All the letter after a "%" represent a format for something : %d is the day number %m is the month number %b is the month abbreviation %y is the year last two digits %Y is the all year etc Have a look at the official documentation, or McCutchen's quick reference you can't know them all. Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this: print "We are the {:%d, %b %Y}".format(today) 'We are the 22, Nov 2008' The advantage of this form is that you can also convert other objects at the same time. Localization Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)
Parsing GPS receiver output via regex in Python
I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus. Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice. At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold: $GPRMC,092204.999,4250.5589,S,14718.5084,E,1,12,24.4,89.6,M,,,0000*1F $GPRMC,093345.679,4234.7899,N,11344.2567,W,3,02,24.5,1000.23,M,,,0000*1F $GPRMC,044584.936,1276.5539,N,88734.1543,E,2,04,33.5,600.323,M,,,*00 $GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00 $GPRMC,066487.954,4572.0089,S,45572.3345,W,3,09,15.0,35000.00,M,,,*1F Here is some further explanation of the data: "I looks like I'll need five things out of every line. And bear in mind that any one of these area's may be empty. Meaning there will be just two commas right next to each other. Such as ',,,' There are two fields that may be full at any time. Some of them only have two or three options that they may be but I don't think I should be counting on that." Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in this pastebin. I am still rather new with regular expressions myself, so I am looking for some assistance.
splitting should do the trick. Here's a good way to extract the data, as well: >>> line = "$GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00" >>> line = line.split(",") >>> neededData = (float(line[2]), line[3], float(line[4]), line[5], float(line[9])) >>> print neededData (3248.7779999999998, 'N', 11355.7832, 'W', 25722.5)
Python - Create a list with initial capacity
Code like this often happens: l = [] while foo: #baz l.append(bar) #qux This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements. In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient. I understand that code like this can often be re-factored into a list comprehension. If the for/while loop is very complicated, though, this is unfeasible. Is there any equivalent for us Python programmers?
def doAppend( size=10000 ): result = [] for i in range(size): message= "some unique object %d" % ( i, ) result.append(message) return result def doAllocate( size=10000 ): result=size*[None] for i in range(size): message= "some unique object %d" % ( i, ) result[i]= message return result Results. (evaluate each function 144 times and average the duration) simple append 0.0102 pre-allocate 0.0098 Conclusion. It barely matters. Premature optimization is the root of all evil.
How do you split a list into evenly sized chunks?
I have a list of arbitrary length, and I need to split it up into equal size chunks and operate on it. There are some obvious ways to do this, like keeping a counter and two lists, and when the second list fills up, add it to the first list and empty the second list for the next round of data, but this is potentially extremely expensive. I was wondering if anyone had a good solution to this for lists of any length, e.g. using generators. This should work: l = range(1, 1000) print chunks(l, 10) -> [ [ 1..10 ], [ 11..20 ], .., [ 991..999 ] ] I was looking for something useful in itertools but I couldn't find anything obviously useful. Might've missed it, though. Related question: What is the most “pythonic” way to iterate over a list in chunks?
Here's a generator that yields the chunks you want: def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] import pprint pprint.pprint(list(chunks(range(10, 75), 10))) [[10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49], [50, 51, 52, 53, 54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65, 66, 67, 68, 69], [70, 71, 72, 73, 74]] If you're using Python 2, you should use xrange() instead of range(): def chunks(l, n): """Yield successive n-sized chunks from l.""" for i in xrange(0, len(l), n): yield l[i:i + n] Also you can simply use list comprehension instead of write a function. Python 3: [l[i:i + n] for i in range(0, len(l), n)] Python 2 version: [l[i:i + n] for i in xrange(0, len(l), n)]
No Module named django.core
I have updated to latest Django version 1.0.2 after uninstalling my old Django version.But now when I run django-admin.py I get the following error. How can I resolve this? Traceback (most recent call last): File "C:\Python25\Lib\site-packages\django\bin\django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core
I have the same problem on Windows and it seems I've found the problem. I have both 2.7 and 3.x installed. It seems it has something to do with the associate program of .py: In commandline type: assoc .py and the result is: .py=Python.File which means .py is associated with Python.File then I tried this: ftype Python.File I got: Python.File="C:\Python32\python.exe" "%1" %* which means in commandline .py is associated with my Python 3.2 installation -- and that's why I can't just type "django-admin.py blah blah" to use django. ALL you need to do is change the association: ftype Python.File="C:\Python27\python.exe" "%1" %* then everythong's okay!
Django authentication and Ajax - URLs that require login
I want to add some Ajax-niceness to my Django-coded website. In my Django code, I use the @login_required decorator from django.contrib.auth.decorators to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass the target page. What I saw on some sites, and really liked, is that when user clicks a link leading to a place restricted to logged-only users, instead of getting redirected to a login page, he/she gets a popup window (via JavaScript) asking him/her to log in or register. There's no redirection part, so no need for a user to use the "back" key if he/she decides he/she really doesn't like the website enough to waste the time registering. So, the qestion is: how would you manage the task of automatically marking some links as "restricted" so JavaScript can handle their onclick event and display a "please log in" popup?
I am facing the same issue, and, like you, I would like a simple decorator to wrap around a Django ajax view in order to handle authentication in the same way that I have other views. One approach that seems promising to me is to use such a decorator in conjunction with JavaScript that looks for a certain value in the response. Here is first revised draft of the decorator: from functools import wraps def ajax_login_required(view_func): @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated(): return view_func(request, *args, **kwargs) json = simplejson.dumps({ 'not_authenticated': True }) return HttpResponse(json, mimetype='application/json') return wrapper Here is the view: @ajax_login_required def ajax_update_module(request, module_slug, action): # Etc ... return HttpResponse(json, mimetype='application/json') And here is the JavaScript (jQuery): $.post('/restricted-url/', data, function(json) { if (json.not_authenticated) { alert('Not authorized.'); // Or something in a message DIV return; } // Etc ... }); EDIT: I've attempted to use functools.wraps, as suggested. I have not actually used this decorator in working code, so beware of possible bugs.
How to debug Web2py applications?
Is it possible? By debug I mean setting breakpoints, inspect values and advance step by step.
You can do remote debugging of python web apps over TCP/IP with winpdb.
Running a function periodically in twisted protocol
I am looking for a way to periodically send some data over all clients connected to a TCP port. I am looking at twisted python and I am aware of reactor.callLater. But how do I use it to send some data to all connected clients periodically ? The data sending logic is in Protocol class and it is instantiated by the reactor as needed. I don't know how to tie it from reactor to all protocol instances...
You would probably want to do this in the Factory for the connections. The Factory is not automatically notified of every time a connection is made and lost, so you can notify it from the Protocol. Here is a complete example of how to use twisted.internet.task.LoopingCall in conjunction with a customised basic Factory and Protocol to announce that '10 seconds has passed' to every connection every 10 seconds. from twisted.internet import reactor, protocol, task class MyProtocol(protocol.Protocol): def connectionMade(self): self.factory.clientConnectionMade(self) def connectionLost(self, reason): self.factory.clientConnectionLost(self) class MyFactory(protocol.Factory): protocol = MyProtocol def __init__(self): self.clients = [] self.lc = task.LoopingCall(self.announce) self.lc.start(10) def announce(self): for client in self.clients: client.transport.write("10 seconds has passed\n") def clientConnectionMade(self, client): self.clients.append(client) def clientConnectionLost(self, client): self.clients.remove(client) myfactory = MyFactory() reactor.listenTCP(9000, myfactory) reactor.run()
Python float to Decimal conversion
Python Decimal doesn't support being constructed from float; it expects that you have to convert float to a string first. This is very inconvenient since standard string formatters for float require that you specify number of decimal places rather than significant places. So if you have a number that could have as many as 15 decimal places you need to format as Decimal(""%.15f"% my_float), which will give you garbage at the 15th decimal place if you also have any significant digits before decimal. Can someone suggest a good way to convert from float to Decimal preserving value as the user has entered, perhaps limiting number of significant digits that can be supported?
Python <2.7 "%.15g" % f Or in Python 3.0: format(f, ".15g") Python 2.7+, 3.2+ Just pass the float to Decimal constructor directly.
Ping a site in Python?
The basic code is: from Tkinter import * import os,sys ana= Tk() def ping1(): os.system('ping') a=Button(pen) ip=("192.168.0.1") a.config(text="PING",bg="white",fg="blue") a=ping1.ip ??? a.pack() ana.mainloop() How could I ping a sites or address?
See this pure Python ping by Matthew Dixon Cowles and Jens Diemer. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux. import ping, socket try: ping.verbose_ping('www.google.com', count=3) delay = ping.Ping('www.wikipedia.org', timeout=2000).do() except socket.error, e: print "Ping Error:", e The source code itself is easy to read, see the implementations of verbose_ping and of Ping.do for inspiration.
Get Element value with minidom with Python
I am creating a GUI frontend for the Eve Online API in Python. I have successfully pulled the XML data from their server. I am trying to grab the value from a node called "name": from xml.dom.minidom import parse dom = parse("C:\\eve.xml") name = dom.getElementsByTagName('name') print name This seems to find the node, but the output is below: [<DOM Element: name at 0x11e6d28>] How could I get it to print the value of the node?
It should just be name[0].firstChild.nodeValue
How do I do a case insensitive string comparison in Python?
What's the best way to do case insensitive string comparison in Python? I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.
Assuming ASCII strings: string1 = 'Hello' string2 = 'hello' if string1.lower() == string2.lower(): print "The strings are the same (case insensitive)" else: print "The strings are not the same (case insensitive)"
How to upload a file with django (python) and s3?
I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: View: def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content_type = copied_data['file'].get('content-type') ffile = copied_data['file']['content'] key = '%s-%s' % (fuser, ''.join(copied_data['file']['filename'].split(' '))) site_s3.save_s3_data(key, ffile, content_type) Template: <form action="/submitpicture/" method="POST"> <input type="file" id="file" name="file" /> <input type="submit" value="submit" /> </form> However, when I actually try to run it i get the following error: "Key 'file' not found in <QueryDict: {}>" #MultiValueDictKeyError I really don't see what I'm doing wrong. Can someone point me in the right direction? Edit: Just in case someone wonders, I am planning on adding some validation after I get the actual upload working.
You will have to provide the enctype attribute to the FORM element (I've been bitten by this before). For example, your FORM tag should look like: <form action="/submitpicture/" method="POST" enctype="multipart/form-data" > Without the enctype, you will find yourself with an empty request.FILES.
Ensuring subprocesses are dead on exiting Python program
Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen(). If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?
You can use atexit for this, and register any clean up tasks to be run when your program exits. atexit.register(func[, *args[, **kargs]]) In your cleanup process, you can also implement your own wait, and kill it when a your desired timeout occurs. >>> import atexit >>> import sys >>> import time >>> >>> >>> >>> def cleanup(): ... timeout_sec = 5 ... for p in all_processes: # list of your processes ... p_sec = 0 ... for second in range(timeout_sec): ... if p.poll() == None: ... time.sleep(1) ... p_sec += 1 ... if p_sec >= timeout_sec: ... p.kill() # supported from python 2.6 ... print 'cleaned up!' ... >>> >>> atexit.register(cleanup) >>> >>> sys.exit() cleaned up! Note -- Registered functions won't be run if this process (parent process) is killed. The following windows method is no longer needed for python >= 2.6 Here's a way to kill a process in windows. Your Popen object has a pid attribute, so you can just call it by success = win_kill(p.pid) (Needs pywin32 installed): def win_kill(pid): '''kill a process by specified PID in windows''' import win32api import win32con hProc = None try: hProc = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid) win32api.TerminateProcess(hProc, 0) except Exception: return False finally: if hProc != None: hProc.Close() return True
Currency formatting in Python
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python. How can I do this?
See the locale module. This does currency (and date) formatting. >>> import locale >>> locale.setlocale( locale.LC_ALL, '' ) 'English_United States.1252' >>> locale.currency( 188518982.18 ) '$188518982.18' >>> locale.currency( 188518982.18, grouping=True ) '$188,518,982.18'
Comparing XML in a unit test in Python
I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).
This is an old question, but the accepted Kozyarchuk's answer doesn't work for me because of attributes order, and the minidom solution doesn't work as-is either (no idea why, I haven't debugged it). This is what I finally came up with: from doctest import Example from lxml.doctestcompare import LXMLOutputChecker class XmlTest(TestCase): def assertXmlEqual(self, got, want): checker = LXMLOutputChecker() if not checker.check_output(want, got, 0): message = checker.output_difference(Example("", want), got, 0) raise AssertionError(message) This also produces a diff that can be helpful in case of large xml files.
Does c# have anything comparable to Python's list comprehensions
I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?
If you are using C# 3.0 (VS2008) then LINQ to Objects can do very similar things: List<Foo> fooList = new List<Foo>(); IEnumerable<Foo> extract = from foo in fooList where foo.Bar > 10 select Foo.Name.ToUpper();
py2exe fails to generate an executable
I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. My setup.py looks like this: from distutils.core import setup import py2exe setup(console=['ServerManager.py']) and the py2exe output looks like this: python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -> wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -> lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -> bz2.pyd) *** finding dlls needed *** py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command: python ServerManager.py Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.
I put this in all my setup.py scripts: distutils.core.setup( options = { "py2exe": { "dll_excludes": ["MSVCP90.dll"] } }, ... ) This keeps py2exe quiet, but you still need to make sure that dll is on the user's machine.
How to get the name of an open file?
I'm trying to store in a variable the name of the current file that I've opened from a folder... How can I do that? I've tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file... Can you please help me? Thanks.
Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('generic.png','r') >>> f.name 'generic.png'
Python list slice syntax used for no obvious reason
I occasionally see the list slice syntax used in Python code like this: newList = oldList[:] Surely this is just the same as: newList = oldList Or am I missing something?
[:] Shallow copies the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists still refer to them, so the updates will show up if the members are accessed through the original. A Deep Copy would make copies of all the list members as well. The code snippet below shows a shallow copy in action. # ================================================================ # === ShallowCopy.py ============================================= # ================================================================ # class Foo: def __init__(self, data): self._data = data aa = Foo ('aaa') bb = Foo ('bbb') # The initial list has two elements containing 'aaa' and 'bbb' OldList = [aa,bb] print OldList[0]._data # The shallow copy makes a new list pointing to the old elements NewList = OldList[:] print NewList[0]._data # Updating one of the elements through the new list sees the # change reflected when you access that element through the # old list. NewList[0]._data = 'xxx' print OldList[0]._data # Updating the new list to point to something new is not reflected # in the old list. NewList[0] = Foo ('ccc') print NewList[0]._data print OldList[0]._data Running it in a python shell gives the following transcript. We can see the list being made with copies of the old objects. One of the objects can have its state updated by reference through the old list, and the updates can be seen when the object is accessed through the old list. Finally, changing a reference in the new list can be seen to not reflect in the old list, as the new list is now referring to a different object. >>> # ================================================================ ... # === ShallowCopy.py ============================================= ... # ================================================================ ... # ... class Foo: ... def __init__(self, data): ... self._data = data ... >>> aa = Foo ('aaa') >>> bb = Foo ('bbb') >>> >>> # The initial list has two elements containing 'aaa' and 'bbb' ... OldList = [aa,bb] >>> print OldList[0]._data aaa >>> >>> # The shallow copy makes a new list pointing to the old elements ... NewList = OldList[:] >>> print NewList[0]._data aaa >>> >>> # Updating one of the elements through the new list sees the ... # change reflected when you access that element through the ... # old list. ... NewList[0]._data = 'xxx' >>> print OldList[0]._data xxx >>> >>> # Updating the new list to point to something new is not reflected ... # in the old list. ... NewList[0] = Foo ('ccc') >>> print NewList[0]._data ccc >>> print OldList[0]._data xxx
How to access previous/next element while for looping?
Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop? l=[1,2,3] for item in l: if item==2: get_previous(l,item)
Expressed as a generator function: def neighborhood(iterable): iterator = iter(iterable) prev = None item = iterator.next() # throws StopIteration if empty. for next in iterator: yield (prev,item,next) prev = item item = next yield (prev,item,None) Usage: for prev,item,next in neighborhood(l): print prev, item, next Edit: I thought it would reduce the readability, but this way seem to look better.
Foreign key from one app into another in Django
I'm wondering if it's possible to define a foreign key in a models.py file in Django that is a reference to a table in another app? In other words, I have two apps, called cf and profiles, and in cf/models.py I have (amongst other things): class Movie(models.Model): title = models.CharField(max_length=255) and in profiles/models.py I want to have: class MovieProperty(models.Model): movie = models.ForeignKey(Movie) But I can't get it to work. I've tried: movie = models.ForeignKey(cf.Movie) and I've tried importing cf.Movie at the beginning of models.py, but I always get errors, such as: NameError: name 'User' is not defined Am I breaking the rules by trying to tie two apps together in this way, or have I just got the syntax wrong?
According to the docs, your second attempt should work: To refer to models defined in another application, you must instead explicitly specify the application label. For example, if the Manufacturer model above is defined in another application called production, you'd need to use: class Car(models.Model): manufacturer = models.ForeignKey('production.Manufacturer') Have you tried putting it into quotes?
Is there any way to kill a Thread in Python?
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?
It is generally a bad pattern to kill a thread abruptly, in Python and in any language. Think of the following cases: the thread is holding a critical resource that must be closed properly the thread has created several other threads that must be killed as well. The nice way of handling this if you can afford it (if you are managing your own threads) is to have an exit_request flag that each threads checks on regular interval to see if it is time for him to exit. For example: import threading class StoppableThread(threading.Thread): """Thread class with a stop() method. The thread itself has to check regularly for the stopped() condition.""" def __init__(self): super(StoppableThread, self).__init__() self._stop = threading.Event() def stop(self): self._stop.set() def stopped(self): return self._stop.isSet() In this code, you should call stop() on the thread when you want it to exit, and wait for the thread to exit properly using join(). The thread should check the stop flag at regular intervals. There are cases however when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls and you want to interrupt it. The following code allows (with some restrictions) to raise an Exception in a Python thread: def _async_raise(tid, exctype): '''Raises an exception in the threads with id tid''' if not inspect.isclass(exctype): raise TypeError("Only types can be raised (not instances)") res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype)) if res == 0: raise ValueError("invalid thread id") elif res != 1: # "if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect" ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed") class ThreadWithExc(threading.Thread): '''A thread class that supports raising exception in the thread from another thread. ''' def _get_my_tid(self): """determines this (self's) thread id CAREFUL : this function is executed in the context of the caller thread, to get the identity of the thread represented by this instance. """ if not self.isAlive(): raise threading.ThreadError("the thread is not active") # do we have it cached? if hasattr(self, "_thread_id"): return self._thread_id # no, look for it in the _active dict for tid, tobj in threading._active.items(): if tobj is self: self._thread_id = tid return tid # TODO: in python 2.6, there's a simpler way to do : self.ident raise AssertionError("could not determine the thread's id") def raiseExc(self, exctype): """Raises the given exception type in the context of this thread. If the thread is busy in a system call (time.sleep(), socket.accept(), ...), the exception is simply ignored. If you are sure that your exception should terminate the thread, one way to ensure that it works is: t = ThreadWithExc( ... ) ... t.raiseExc( SomeException ) while t.isAlive(): time.sleep( 0.1 ) t.raiseExc( SomeException ) If the exception is to be caught by the thread, you need a way to check that your thread has caught it. CAREFUL : this function is executed in the context of the caller thread, to raise an excpetion in the context of the thread represented by this instance. """ _async_raise( self._get_my_tid(), exctype ) As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption. A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.
What is the fastest way to parse large XML docs in Python?
I am currently the following code based on Chapter 12.5 of the Python Cookbook: from xml.parsers import expat class Element(object): def __init__(self, name, attributes): self.name = name self.attributes = attributes self.cdata = '' self.children = [] def addChild(self, element): self.children.append(element) def getAttribute(self,key): return self.attributes.get(key) def getData(self): return self.cdata def getElements(self, name=''): if name: return [c for c in self.children if c.name == name] else: return list(self.children) class Xml2Obj(object): def __init__(self): self.root = None self.nodeStack = [] def StartElement(self, name, attributes): element = Element(name.encode(), attributes) if self.nodeStack: parent = self.nodeStack[-1] parent.addChild(element) else: self.root = element self.nodeStack.append(element) def EndElement(self, name): self.nodeStack.pop() def CharacterData(self,data): if data.strip(): data = data.encode() element = self.nodeStack[-1] element.cdata += data def Parse(self, filename): Parser = expat.ParserCreate() Parser.StartElementHandler = self.StartElement Parser.EndElementHandler = self.EndElement Parser.CharacterDataHandler = self.CharacterData ParserStatus = Parser.Parse(open(filename).read(),1) return self.root I am working with XML docs about 1 GB in size. Does anyone know a faster way to parse these?
I looks to me as if you do not need any DOM capabilities from your program. I would second the use of the (c)ElementTree library. If you use the iterparse function of the cElementTree module, you can work your way through the xml and deal with the events as they occur. Note however, Fredriks advice on using cElementTree iterparse function: to parse large files, you can get rid of elements as soon as you’ve processed them: for event, elem in iterparse(source): if elem.tag == "record": ... process record elements ... elem.clear() The above pattern has one drawback; it does not clear the root element, so you will end up with a single element with lots of empty child elements. If your files are huge, rather than just large, this might be a problem. To work around this, you need to get your hands on the root element. The easiest way to do this is to enable start events, and save a reference to the first element in a variable: # get an iterable context = iterparse(source, events=("start", "end")) # turn it into an iterator context = iter(context) # get the root element event, root = context.next() for event, elem in context: if event == "end" and elem.tag == "record": ... process record elements ... root.clear() The lxml.iterparse() does not allow this.
Launch a shell command with in a python script, wait for the termination and return to the script
I've a python script that has to launch a shell command for every file in a dir: import os files = os.listdir(".") for f in files: os.execlp("myscript", "myscript", f) This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script. How can I do? Do I have to fork() before calling os.execlp()?
subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. http://docs.python.org/library/subprocess.html Usage: import subprocess process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE) process.wait() print process.returncode
Which is faster in Python: x**.5 or math.sqrt(x)?
I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? UPDATE This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido van Rossum an email cause I really wanted to know the differences in these methods. My email: There are at least 3 ways to do a square root in Python: math.sqrt, the '**' operator and pow(x,.5). I'm just curious as to the differences in the implementation of each of these. When it comes to efficiency which is better? His response: pow and ** are equivalent; math.sqrt doesn't work for complex numbers, and links to the C sqrt() function. As to which one is faster, I have no idea...
As per comments, I've updated the code: import time import math def timeit1(): s = time.time() for i in xrange(750000): z=i**.5 print "Took %f seconds" % (time.time() - s) def timeit2(arg=math.sqrt): s = time.time() for i in xrange(750000): z=arg(i) print "Took %f seconds" % (time.time() - s) timeit1() timeit2() Now the math.sqrt function is directly in a local argument, meaning it has the fastest lookup possible. UPDATE: The python version seems to matter here. I used to think that timeit1 would be faster, since when python parses "i**.5" it knows, syntactically, which method to call (__pow__ or some variant), so it doesn't have to go through the overhead of lookup that the math.sqrt variant does. But I might be wrong: Python 2.5: 0.191000 vs. 0.224000 Python 2.6: 0.195000 vs. 0.139000 Also psyco seems to deal with math.sqrt better: Python 2.5 + Psyco 2.0: 0.109000 vs. 0.043000 Python 2.6 + Psyco 2.0: 0.128000 vs. 0.067000 | Interpreter | x**.5, | sqrt, | sqrt faster, % | | | seconds | seconds | | |----------------+---------+---------+----------------| | Python 3.2rc1+ | 0.32 | 0.27 | 19 | | Python 3.1.2 | 0.136 | 0.088 | 55 | | Python 3.0.1 | 0.155 | 0.102 | 52 | | Python 2.7 | 0.132 | 0.079 | 67 | | Python 2.6.6 | 0.121 | 0.075 | 61 | | PyPy 1.4.1 | 0.083 | 0.0159 | 422 | | Jython 2.5.1 | 0.132 | 0.22 | -40 | | Python 2.5.5 | 0.129 | 0.125 | 3 | | Python 2.4.6 | 0.131 | 0.123 | 7 | #+TBLFM: $4=100*($2-$3)/$3;%.0f Table results produced on machine: $ uname -vms Linux #42-Ubuntu SMP Thu Dec 2 02:41:37 UTC 2010 x86_64 $ cat /proc/cpuinfo | grep 'model name' | head -1 model name : Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz To reproduce results: get source: git clone git://gist.github.com/783011.git gist-783011 install tox: pip install tox run tox from the directory with tox.ini file.
Memory Efficient Alternatives to Python Dictionaries
In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2] returns a dictionary with all the words that appeared following words 1 and 2, etc. This functions correctly, but it is very memory intensive. In my initial tests it used something like 20 times the memory of just storing the triplets in a text file, which seems like an overly large amount of memory overhead. My suspicion is that many of these dictionaries are being created with many more slots than are actually being used, so I want to replace the dictionaries with something else that is more memory efficient when used in this manner. I would strongly prefer a solution that allows key lookups along the lines of the dictionaries. From what I know of data structures, a balanced binary search tree using something like red-black or AVL would probably be ideal, but I would really prefer not to implement them myself. If possible, I'd prefer to stick with standard python libraries, but I'm definitely open to other alternatives if they would work best. So, does anyone have any suggestions for me? Edited to add: Thanks for the responses so far. A few of the answers so far have suggested using tuples, which didn't really do much for me when I condensed the first two words into a tuple. I am hesitant to use all three as a key since I want it to be easy to look up all third words given the first two. (ie I want something like the result of topDict[word1,word2].keys() ). The current dataset I am playing around with is the most recent version of Wikipedia For Schools. The results of parsing the first thousand pages, for example, is something like 11MB for a text file where each line is the three words and the count all tab separated. Storing the text in the dictionary format I am now using takes around 185MB. I know that there will be some additional overhead for pointers and whatnot, but the difference seems excessive. Once again, thank you all for the responses so far.
Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record: 295760 S. Lott's answer 237984 S. Lott's with keys interned before passing in 203172 [*] d[(a,b,c)] = int(freq) 203156 d[a][b][c] = int(freq) 189132 keys.append((a,b,c)); freqs.append(int(freq)) 146132 d[intern(a),intern(b)][intern(c)] = int(freq) 145408 d[intern(a)][intern(b)][intern(c)] = int(freq) 83888 [*] d[a+' '+b+' '+c] = int(freq) 82776 [*] d[(intern(a),intern(b),intern(c))] = int(freq) 68756 keys.append((intern(a),intern(b),intern(c))); freqs.append(int(freq)) 60320 keys.append(a+' '+b+' '+c); freqs.append(int(freq)) 50556 pair array 48320 squeezed pair array 33024 squeezed single array The entries marked [*] have no efficient way to look up a pair (a,b); they're listed only because others have suggested them (or variants of them). (I was sort of irked into making this because the top-voted answers were not helpful, as the table shows.) 'Pair array' is the scheme below in my original answer ("I'd start with the array with keys being the first two words..."), where the value table for each pair is represented as a single string. 'Squeezed pair array' is the same, leaving out the frequency values that are equal to 1 (the most common case). 'Squeezed single array' is like squeezed pair array, but gloms key and value together as one string (with a separator character). The squeezed single array code: import collections def build(file): pairs = collections.defaultdict(list) for line in file: # N.B. file assumed to be already sorted a, b, c, freq = line.split() key = ' '.join((a, b)) pairs[key].append(c + ':' + freq if freq != '1' else c) out = open('squeezedsinglearrayfile', 'w') for key in sorted(pairs.keys()): out.write('%s|%s\n' % (key, ' '.join(pairs[key]))) def load(): return open('squeezedsinglearrayfile').readlines() if __name__ == '__main__': build(open('freqs')) I haven't written the code to look up values from this structure (use bisect, as mentioned below), or implemented the fancier compressed structures also described below. Original answer: A simple sorted array of strings, each string being a space-separated concatenation of words, searched using the bisect module, should be worth trying for a start. This saves space on pointers, etc. It still wastes space due to the repetition of words; there's a standard trick to strip out common prefixes, with another level of index to get them back, but that's rather more complex and slower. (The idea is to store successive chunks of the array in a compressed form that must be scanned sequentially, along with a random-access index to each chunk. Chunks are big enough to compress, but small enough for reasonable access time. The particular compression scheme applicable here: if successive entries are 'hello george' and 'hello world', make the second entry be '6world' instead. (6 being the length of the prefix in common.) Or maybe you could get away with using zlib? Anyway, you can find out more in this vein by looking up dictionary structures used in full-text search.) So specifically, I'd start with the array with keys being the first two words, with a parallel array whose entries list the possible third words and their frequencies. It might still suck, though -- I think you may be out of luck as far as batteries-included memory-efficient options. Also, binary tree structures are not recommended for memory efficiency here. E.g., this paper tests a variety of data structures on a similar problem (unigrams instead of trigrams though) and finds a hashtable to beat all of the tree structures by that measure. I should have mentioned, as someone else did, that the sorted array could be used just for the wordlist, not bigrams or trigrams; then for your 'real' data structure, whatever it is, you use integer keys instead of strings -- indices into the wordlist. (But this keeps you from exploiting common prefixes except in the wordlist itself. Maybe I shouldn't suggest this after all.)
How are Python's Built In Dictionaries Implemented
Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive). Python dictionaries are implemented as hash tables. Hash tables must allow for hash collisions i.e. even if two distinct keys have the same hash value, the table's implementation must have a strategy to insert and retrieve the key and value pairs unambiguously. Python dict uses open addressing to resolve hash collisions (explained below) (see dictobject.c:296-297). Python hash table is just a contiguous block of memory (sort of like an array, so you can do an O(1) lookup by index). Each slot in the table can store one and only one entry. This is important. Each entry in the table actually a combination of the three values: < hash, key, value >. This is implemented as a C struct (see dictobject.h:51-56). The figure below is a logical representation of a Python hash table. In the figure below, 0, 1, ..., i, ... on the left are indices of the slots in the hash table (they are just for illustrative purposes and are not stored along with the table obviously!). # Logical model of Python Hash table -+-----------------+ 0| <hash|key|value>| -+-----------------+ 1| ... | -+-----------------+ .| ... | -+-----------------+ i| ... | -+-----------------+ .| ... | -+-----------------+ n| ... | -+-----------------+ When a new dict is initialized it starts with 8 slots. (see dictobject.h:49) When adding entries to the table, we start with some slot, i, that is based on the hash of the key. CPython initially uses i = hash(key) & mask (where mask = PyDictMINSIZE - 1, but that's not really important). Just note that the initial slot, i, that is checked depends on the hash of the key. If that slot is empty, the entry is added to the slot (by entry, I mean, <hash|key|value>). But what if that slot is occupied!? Most likely because another entry has the same hash (hash collision!) If the slot is occupied, CPython (and even PyPy) compares the the hash AND the key (by compare I mean == comparison not the is comparison) of the entry in the slot against the key of the current entry to be inserted (dictobject.c:337,344-345). If both match, then it thinks the entry already exists, gives up and moves on to the next entry to be inserted. If either hash or the key don't match, it starts probing. Probing just means it searches the slots by slot to find an empty slot. Technically we could just go one by one, i+1, i+2, ... and use the first available one (that's linear probing). But for reasons explained beautifully in the comments (see dictobject.c:33-126), CPython uses random probing. In random probing, the next slot is picked in a pseudo random order. The entry is added to the first empty slot. For this discussion, the actual algorithm used to pick the next slot is not really important (see dictobject.c:33-126 for the algorithm for probing). What is important is that the slots are probed until first empty slot is found. The same thing happens for lookups, just starts with the initial slot i (where i depends on the hash of the key). If the hash and the key both don't match the entry in the slot, it starts probing, until it finds a slot with a match. If all slots are exhausted, it reports a fail. BTW, the dict will be resized if it is two-thirds full. This avoids slowing down lookups. (see dictobject.h:64-65) NOTE: I did the research on Python Dict implementation in response to my own question about how multiple entries in a dict can have same hash values. I posted a slightly edited version of the response here because all the research is very relevant for this question as well.
storing unbound python functions in a class object
I'm trying to do the following in python: In a file called foo.py: # simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction And then in a file called bar.py: import foo d = foo.data d.fn(1,2,3) However, I get the following error: TypeError: unbound method f() must be called with data instance as first argument (got int instance instead) This is fair enough I suppose - python is treating d.myFunction as a class method. However, I want it to treat it as a normal function - so I can call it without having to add an unused 'self' parameter to the myFunction definition. So the question is: How can I store a function in a class object without the function becoming bound to that class?
data.fn = staticmethod(myFunction) should do the trick.
Storing and updating lists in Python dictionaries: why does this happen?
I have a list of data that looks like the following: // timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 ... and I want to make this look like: 0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like: # where t = 0, c = (4,7), d = {} # code 1 d[t].append(c) Now this causes IDLE to fail. However, if I do: # code 2 d[t] = [] d[t].append(c) ... this works. So the question is: why does code 2 work, but code 1 doesn't? PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through.
Let's look at d[t].append(c) What is the value of d[t]? Try it. d = {} t = 0 d[t] What do you get? Oh. There's nothing in d that has a key of t. Now try this. d[t] = [] d[t] Ahh. Now there's something in d with a key of t. There are several things you can do. Use example 2. Use setdefault. d.setdefault(t,[]).append(c). Use collections.defaultdict. You'd use a defaultdict(list) instead of a simple dictionary, {}. Edit 1. Optimization Given input lines from a file in the above form: ts, x, y, the grouping process is needless. There's no reason to go from a simple list of ( ts, x, y ) to a more complex list of ( ts, (x,y), (x,y), (x,y), ... ). The original list can be processed exactly as it arrived. d= collections.defaultdict(list) for ts, x, y in someFileOrListOrQueryOrWhatever: d[ts].append( (x,y) ) Edit 2. Answer Question "when initialising a dictionary, you need to tell the dictionary what the key-value data structure will look like?" I'm not sure what the question means. Since, all dictionaries are key-value structures, the question's not very clear. So, I'll review the three alternatives, which may answer the question. Example 2. Initialization d= {} Use if t not in d: d[t] = list() d[t].append( c ) Each dictionary value must be initialized to some useful structure. In this case, we check to see if the key is present; when the key is missing, we create the key and assign an empty list. Setdefault Initialization d= {} Use d.setdefault(t,list()).append( c ) In this case, we exploit the setdefault method to either fetch a value associated with a key or create a new value associated with a missing key. default dict Initialization import collections d = collections.defaultdict(list) Use d[t].append( c ) The defaultdict uses an initializer function for missing keys. In this case, we provide the list function so that a new, empty list is created for a missing key.
Django equivalent for count and group by
I have a model that looks like this: class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) I want select count (just the count) of items for each category, so in SQL it would be as simple as this: select category_id, count(id) from item group by category_id Is there an equivalent of doing this "the Django way"? Or is plain SQL the only option? I am familiar with the count( ) method in Django, however I don't see how group by would fit there.
Here, as I just discovered, is how to do this with the Django 1.1 aggregation API: from django.db.models import Count theanswer = Item.objects.values('category').annotate(Count('category'))
Create a List that contain each Line of a File
I'm trying to open a file and create a list with each line read from the file. i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List But this sample code gives me an error because of the i+=1 saying that index is out of range. What's my problem here? How can I write the code in order to increment my list with every new Line in the InFile?
It's a lot easier than that: List = open("filename.txt").readlines() This returns a list of each line in the file.
How to make a surface with a transparent background in pygame
Can someone give me some example code that creates a surface with a transparent background in pygame?
This should do it: image = pygame.Surface([640,480], pygame.SRCALPHA, 32) image = image.convert_alpha() Make sure that the color depth (32) stays explicitly set else this will not work.
How can you determine a point is between two other points on a line segment?
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point. How can you determine if another point c is on the line segment defined by a and b? I use python most, but examples in any language would be helpful.
Check if the cross product of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned. But, as you want to know if c is between a and b, you also have to check that the dot product of (b-a) and (c-a) is positive and is less than the square of the distance between a and b. In non-optimized pseudocode: def isBetween(a, b, c): crossproduct = (c.y - a.y) * (b.x - a.x) - (c.x - a.x) * (b.y - a.y) if abs(crossproduct) > epsilon : return False # (or != 0 if using integers) dotproduct = (c.x - a.x) * (b.x - a.x) + (c.y - a.y)*(b.y - a.y) if dotproduct < 0 : return False squaredlengthba = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y) if dotproduct > squaredlengthba: return False return True
Extracting text from HTML file using Python
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, but I've had a few problems using it. For one, it picked up unwanted text, such as JavaScript source. Also, it did not interpret HTML entities. For example, I would expect &#39; in HTML source to be converted to an apostrophe in text, just as if I'd pasted the browser content into notepad. Update html2text looks promising. It handles HTML entities correctly and ignores JavaScript. However, it does not exactly produce plain text; it produces markdown that would then have to be turned into plain text. It comes with no examples or documentation, but the code looks clean. Related questions: Filter out HTML tags and resolve entities in python Convert XML/HTML Entities into Unicode String in Python
NOTE: NTLK no longer supports clean_html function Original answer below. Use NLTK I wasted my 4-5 hours fixing the issues with html2text. Luckily i could encounter NLTK. It works magically. import nltk from urllib import urlopen url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" html = urlopen(url).read() raw = nltk.clean_html(html) print(raw)
Printing all instances of a class
With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?
I see two options in this case: Garbage collector import gc for obj in gc.get_objects(): if isinstance(obj, some_class): dome_something(obj) This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control. Use a mixin and weakrefs from collections import defaultdict import weakref class KeepRefs(object): __refs__ = defaultdict(list) def __init__(self): self.__refs__[self.__class__].append(weakref.ref(self)) @classmethod def get_instances(cls): for inst_ref in cls.__refs__[cls]: inst = inst_ref() if inst is not None: yield inst class X(KeepRefs): def __init__(self, name): super(X, self).__init__() self.name = name x = X("x") y = X("y") for r in X.get_instances(): print r.name del y for r in X.get_instances(): print r.name In this case, all the references get stored as a weak reference in a list. If you create and delete a lot of instances frequently, you should clean up the list of weakrefs after iteration, otherwise there's going to be a lot of cruft. Another problem in this case is that you have to make sure to call the base class constructor. You could also override __new__, but only the __new__ method of the first base class is used on instantiation. This also works only on types that are under your control. Edit: The method for printing all instances according to a specific format is left as an exercise, but it's basically just a variation on the for-loops.
Replace textarea with rich text editor in Django Admin?
I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?
There's an add-on Django application to provide TinyMCE support for Django admin forms without having to muck around with admin templates or Django newform internals.
How to quickly parse a list of strings
If I want to split a list of words separated by a delimiter character, I can use >>> 'abc,foo,bar'.split(',') ['abc', 'foo', 'bar'] But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ? In: 'abc,"a string, with a comma","another, one"' Out: ['abc', 'a string, with a comma', 'another, one'] Related question: How can i parse a comma delimited string into a list (caveat)?
import csv input = ['abc,"a string, with a comma","another, one"'] parser = csv.reader(input) for fields in parser: for i,f in enumerate(fields): print i,f # in Python 3 and up, print is a function; use: print(i,f) Result: 0 abc 1 a string, with a comma 2 another, one
Converting a PDF to a series of images with Python
I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images. PIL does not work, as it can't read PDFs. The two options I've found are using either GhostScript or ImageMagick through the shell. This is not a viable option for me, since this program needs to be cross-platform, and I can't be sure either of those programs will be available on the machines it will be installed and used on. Are there any Python libraries out there that can do this?
ImageMagick has Python bindings.
Difference between class foo and class foo(object) in Python
I know class foo(object) is an old school way of defining a class. But I would like to understand in more detail the difference between these two.
Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes). This led to problems when you wanted to mix python-types and builtin types. The most common reason for this is subclassing. If you wanted to subclass the list type in python code, you were out of luck, and so various workarounds were used instead, such as subclassing the pure python implementation of lists (in the UserList module) instead. This was a fairly ugly, so in 2.2 there was a move to unify python and builtin types, including the ability to inherit from them. The result is "new style classes". These do have some incompatible differences to old-style classes however, so for backward compatability the bare class syntax creates an old-style class, while the new behaviour is obtained by inheriting from object. The most visible behaviour differences are: The method resolution order (MRO). There is a difference in behaviour in diamond-shaped inheritance hierarchies (where A inherits from both B and C, which both inherit from a common base class D. Previously, methods were looked up left-to right, depth first (ie A B D C D) However if C overloads a member of D, it won't be used by A (as it finds D's implementation first) This is bad for various styles of programming (eg. using mixin classes). New style classes will treat this situation as A B C D, (look at the __mro__ attribute of a class to see the order it will search) The __new__ constructor is added, which allows the class to act as a factory method, rather than return a new instance of the class. Useful for returning particular subclasses, or reusing immutable objects rather than creating new ones without having to change the creation interface. Descriptors. These are the feature behind such things as properties, classmethods, staticmethods etc. Essentially, they provide a way to control what happens when you access or set a particular attribute on a (new style) class.
How do you change the size of figures drawn with matplotlib?
How do you change the size of figure drawn with matplotlib?
figure tells you the call signature: figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') So figure(figsize=(1,1)) creates an inch-by-inch image, which will be 80-by-80 pixels unless you also give a different dpi argument.
How to detect that Python code is being executed through the debugger?
Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger? I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.
Python debuggers (as well as profilers and coverage tools) use the sys.settrace function (in the sys module) to register a callback that gets called when interesting events happen. If you're using Python 2.6, you can call sys.gettrace() to get the current trace callback function. If it's not None then you can assume you should be passing debug parameters to the JVM. It's not clear how you could do this pre 2.6.
Passing a dictionary to a function in python as keyword parameters
I'd like to call a function in python using a dictionary. Here is some code: d = dict(param='test') def f(param): print param f(d) This prints {'param': 'test'} but I'd like it to just print test. I'd like it to work similarly for more parameters: d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(d) Is this possible?
Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary So my example becomes: d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(**d)
Lists in ConfigParser
The typical ConfigParser generated file looks like: [Section] bar=foo [Section 2] bar2= baz Now, is there a way to index lists like, for instance: [Section 3] barList={ item1, item2 } Related question: Python’s ConfigParser unique keys per section ? Thanks in advance
Also a bit late, but maybe helpful for some. I am using a combination of ConfigParser and JSON: [Foo] fibs: [1,1,2,3,5,8,13] just read it with: >>> json.loads(config.get("Foo","fibs")) [1, 1, 2, 3, 5, 8, 13] You can even break lines if your list is long (thanks @peter-smit): [Bar] files_to_check = [ "/path/to/file1", "/path/to/file2", "/path/to/another file with space in the name" ] Of course i could just use JSON, but i find config files much more readable, and the [DEFAULT] Section very handy.
Python: Invalid Token
Some of you may recognize this as Project Euler's problem number 11. The one with the grid. I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ], ... And I get this error: File "D:\development\Python\ProjectEuler\p11.py", line 3 [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ], ^ SyntaxError: invalid token Why is it throwing an error before the comma?
I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.
How to implement a minimal server for AJAX in Python?
I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python SimpleHTTPServer.SimpleHTTPRequestHandler? A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple. I already found some nice examples for such a server (e.g. here), but so far I could not come up with a truly minimal one. In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction - so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).
O.K., I think I can now answer my own question. Here is an example implementation for calculating the square of a number on the server. Please let me know if there are any improvements or misconceptions. the python server file: import threading import webbrowser import BaseHTTPServer import SimpleHTTPServer FILE = 'frontend.html' PORT = 8080 class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """The test example handler.""" def do_POST(self): """Handle a post request by returning the square of the number.""" length = int(self.headers.getheader('content-length')) data_string = self.rfile.read(length) try: result = int(data_string) ** 2 except: result = 'error' self.wfile.write(result) def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" server_address = ("", PORT) server = BaseHTTPServer.HTTPServer(server_address, TestHandler) server.serve_forever() if __name__ == "__main__": open_browser() start_server() ...and the HTML file (I call it 'frontend.html', unfortunately the name has to appear in the JavaScript code as well): <html> <head> <title>AJAX test</title> </head> <body> <script type="text/javascript"> function xml_http_post(url, data, callback) { var req = false; try { // Firefox, Opera 8.0+, Safari req = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } req.open("POST", url, true); req.onreadystatechange = function() { if (req.readyState == 4) { callback(req); } } req.send(data); } function test_button() { var data = document.test_form.test_text.value; xml_http_post("frontend.html", data, test_handle) } function test_handle(req) { var elem = document.getElementById('test_result') elem.innerHTML = req.responseText } </script> <form name=test_form> sqr( <input type="text" name="test_text" value="0" size="4"> ) = <span id="test_result">0</span> <input type=button onClick="test_button();" value="start" title="start"> </form> </body> </html> Of course it would be much more convenient to use jQuery for the XML request, but in the interest of simplicity I'll leave it like that. Finally an alternative implementation using WSGI (unfortunately I didn't see a way to fall back on the standard file-serving handler if the request is not a POST): import threading import webbrowser from wsgiref.simple_server import make_server FILE = 'frontend.html' PORT = 8080 def test_app(environ, start_response): if environ['REQUEST_METHOD'] == 'POST': try: request_body_size = int(environ['CONTENT_LENGTH']) request_body = environ['wsgi.input'].read(request_body_size) except (TypeError, ValueError): request_body = "0" try: response_body = str(int(request_body) ** 2) except: response_body = "error" status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response_body] else: response_body = open(FILE).read() status = '200 OK' headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body] def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" httpd = make_server("", PORT, test_app) httpd.serve_forever() if __name__ == "__main__": open_browser() start_server()