instruction
stringlengths
12
148
input
stringlengths
16
30.2k
output
stringlengths
11
27.3k
ODFPy documentation
I need to manipulate the ODF file format (open document format, the open office's internal format), and I need to do it in Python. It seem's ODFPy is a wonderful library for this purpose. Unfortunately the official documentation is very poor, almost unuseful. I can't find almost anything online - maybe it is not so popular? Is there anyone who can point me at some some information or better documentation?
The documentation is unfortunately horrible, and the generated Python wrapper is lousily documented in code, providing lots of functions whose argument lists look like func(*args). The reference manual is actually useful, but not when you're starting out - it doesn't provide any context of how to use these functions. I would suggest starting with the tutorial and all the examples. Even though they may have nothing to do with your use case, they will help you get the feel of how the package works. After you've gotten used to the way the package is structured, you can often make sense of the documentation by combining the API doc with the information in the OpenDocument Essentials book. (The relationship is somewhat tenuous at best, but you can often intuit method and attribute values from it. When working with the spreadsheet, for example, the handy list of office:value-type data in the book provided the necessary constants for building proper TableCell(valuetype=...) instances) Also, making small documents in OpenOffice and then inspecting the xml and comparing it to the XML generated from ODFPy greatly helps you debug where you might have gone wrong.
Dynamic loading of python modules
In python how do you dynamically add modules to a package while your programming is running. I want to be able to add modules to the package directory from an outside process, and be able to use those new modules in my program: import package def doSomething(name): pkg = __import__("package." + name) mod = getattr(pkg, name) mod.doSomething() How do I do this?
Your code is almost correct. See __import__ function. def doSomething(name): name = "package." + name mod = __import__(name, fromlist=['']) mod.doSomething()
Making a flat list out of list of lists in Python
I wonder whether there is a shortcut to make a simple list out of list of lists in Python. I can do that in a for loop, but maybe there is some cool "one-liner"? I tried it with reduce, but I get an error. Code l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]] reduce(lambda x, y: x.extend(y), l) Error message Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> AttributeError: 'NoneType' object has no attribute 'extend'
[item for sublist in l for item in sublist] is faster than the shortcuts posted so far. (l is the list to flatten.) For evidence, as always, you can use the timeit module in the standard library: $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]' 10000 loops, best of 3: 143 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])' 1000 loops, best of 3: 969 usec per loop $ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)' 1000 loops, best of 3: 1.1 msec per loop Explanation: the shortcuts based on + (including the implied use in sum) are, of necessity, O(L**2) when there are L sublists -- as the intermediate result list keeps getting longer, at each step a new intermediate result list object gets allocated, and all the items in the previous intermediate result must be copied over (as well as a few new ones added at the end). So (for simplicity and without actual loss of generality) say you have L sublists of I items each: the first I items are copied back and forth L-1 times, the second I items L-2 times, and so on; total number of copies is I times the sum of x for x from 1 to L excluded, i.e., I * (L**2)/2. The list comprehension just generates one list, once, and copies each item over (from its original place of residence to the result list) also exactly once.
Check unread count of Gmail messages with Python
How can I check the number of unread Gmail message in my inbox with a short Python script? Bonus points for retrieving the password from a file.
import imaplib obj = imaplib.IMAP4_SSL('imap.gmail.com','993') obj.login('username','password') obj.select() obj.search(None,'UnSeen')
How to get files in a directory, including all subdirectories
I'm trying to get a list of all log files (.log) in directory, including all subdirectories.
import os import os.path for dirpath, dirnames, filenames in os.walk("."): for filename in [f for f in filenames if f.endswith(".log")]: print os.path.join(dirpath, filename)
How do I use raw_input in Python 3
import sys print (sys.platform) print (2 ** 100) raw_input( ) I am using Python 3.1 and can't get the raw_input to "freeze" the dos pop-up. The book I'm reading is for 2.5 and I'm using 3.1 What should I do to fix this?
raw_input() was renamed to input() From http://docs.python.org/dev/py3k/whatsnew/3.0.html
How to identify whether a file is normal file or directory using python
How do you check whether a file is a normal file or a directory using python?
os.path.isdir() and os.path.isfile() should give you what you want. See: http://docs.python.org/library/os.path.html
What is the correct way to set Python's locale on Windows?
I'm attempting to sort a list of strings in a locale-aware manner. I've used the Babel library for other i18n-related tasks, but it doesn't support sorting. Python's locale module provides a strcoll function, but requires the locale of the process to be set to the one I want to work with. Kind of a pain, but I can live with it. The problem is that I can't seem to actually set the locale. The documentation for the locale module gives this example: import locale locale.setlocale(locale.LC_ALL, 'de_DE') When I run that, I get this: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\Lib\locale.py", line 494, in setlocale locale.Error: unsupported locale setting What am I doing wrong?
It seems you're using Windows. The locale strings are different there. Take a more precise look at the doc: locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform On Windows, I think it would be something like: locale.setlocale(locale.LC_ALL, 'deu_deu') MSDN has a list of language strings and of country/region strings
How to get string objects instead of Unicode ones from JSON in Python?
I'm using Python 2 to parse JSON from (ASCII encoded) text files. When loading these files with either json or simplejson, all my string values are cast to Unicode objects instead of string objects. The problem is, I have to use the data with some libraries that only accept string objects. I can't change the libraries nor update them. Is it possible to get string objects instead of Unicode ones from json or simplejson? Here's a small example: >>> import json >>> original_list = ['a', 'b'] >>> json_list = json.dumps(original_list) >>> json_list '["a", "b"]' >>> new_list = json.loads(js) >>> new_list [u'a', u'b'] # I want these to be of type `str`, not `unicode`
While there are some good answers here, I ended up using PyYAML to parse my JSON files, since it gives the keys and values as str type strings instead of unicode type. Because JSON is a subset of YAML it works nicely: >>> import json >>> import yaml >>> list_org = ['a', 'b'] >>> list_dump = json.dumps(list_org) >>> list_dump '["a", "b"]' >>> json.loads(list_dump) [u'a', u'b'] >>> yaml.safe_load(list_dump) ['a', 'b'] Some things to note though: I get string objects because all my entries are ASCII encoded. If I would use unicode encoded entries, I would get them back as unicode objects — there is no conversion! You should (probably always) use PyYAML's safe_load function; if you use it to load JSON files, you don't need the "additional power" of the load function anyway. If you want a YAML parser that has more support for the 1.2 version of the spec (and correctly parses very low numbers) try Ruamel YAML: pip install ruamel.yaml and import ruamel.yaml as yaml was all I needed in my tests. As stated, there is no conversion! If you can't be sure to only deal with ASCII values (and you can't be sure most of the time), better use a conversion function: I used the one from Mark Amery a couple of times now, it works great and is very easy to use. You can also use a similar function as an object_hook instead, as it might gain you a performance boost on big files. See the slightly more involved answer from Mirec Miskuf for that.
Clean Python Regular Expressions
Is there a cleaner way to write long regex patterns in python? I saw this approach somewhere but regex in python doesn't allow lists. patterns = [ re.compile(r'<!--([^->]|(-+[^->])|(-?>))*-{2,}>'), re.compile(r'\n+|\s{2}') ]
You can use verbose mode to write more readable regular expressions. In this mode: Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash. When a line contains a '#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such '#' through the end of the line are ignored. The following two statements are equivalent: a = re.compile(r"""\d + # the integral part \. # the decimal point \d * # some fractional digits""", re.X) b = re.compile(r"\d+\.\d*") (Taken from the documentation of verbose mode)
Removing starting spaces in Python?
I have a text string that starts with a number of spaces, varying between 2 & 4. What's the easiest & simplest way to remove them ie. remove everything before a certain character?
The lstrip() method will remove leading whitespaces, newline and tab characters on a string beginning: >>> ' hello world!'.lstrip() 'hello world!' Edit As balpha pointed out in the comments, in order to remove only spaces from the beginning of the string, lstrip(' ') should be used: >>> ' hello world with 2 spaces and a tab!'.lstrip(' ') '\thello world with 2 spaces and a tab!' Related question: Trimming a string in Python
Python creating a dictionary of lists
I want to create a dictionary whose values are lists. For example: { 1: ['1'], 2: ['1','2'], 3: ['2'] } If I do: d = dict() a = ['1', '2'] for i in a: for j in range(int(i), int(i) + 2): d[j].append(i) I get a KeyError, because d[...] isn't a list. In this case, I can add the following code after the assignment of a to initialize the dictionary. for x in range(1, 4): d[x] = list() Is there a better way to do this? Lets say I don't know the keys I am going to need until I am in the second for loop. For example: class relation: scope_list = list() ... d = dict() for relation in relation_list: for scope_item in relation.scope_list: d[scope_item].append(relation) An alternative would then be replacing d[scope_item].append(relation) with if d.has_key(scope_item): d[scope_item].append(relation) else: d[scope_item] = [relation,] What is the best way to handle this? Ideally, appending would "just work". Is there some way to express that I want a dictionary of empty lists, even if I don't know every key when I first create the list?
You can use defaultdict: >>> from collections import defaultdict >>> d = defaultdict(list) >>> for i in a: ... for j in range(int(i), int(i) + 2): ... d[j].append(i) ... >>> d defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']}) >>> d.items() [(1, ['1']), (2, ['1', '2']), (3, ['2'])]
PEP 302 Example: New Import Hooks
Where can I find an example implementation of the "New Import Hooks" described in PEP 302? I would like to implement a custom finder and loader in the most forward compatible way possible. In other words, the implementation should work in python 2.x and 3.x.
You can find thousands of open-source examples e.g. with a google code search, here it is: http://www.google.com/codesearch?hl=en&lr=&q="imp.find_module"+"imp.load_module"&sbtn=Search Edit: as the questioner clarified he's looking for example of implementation, not use, a better URL for the search is: http://www.google.com/codesearch?hl=en&sa=N&q="path_hooks"++lang:python&ct=rr&cs_r=lang:python One readable example (though NOT suitable for production use, as the reddit discussion points out!) is urlimport. As for supporting Python 2 and Python 3 at the same time, that sounds ambitious -- I don't know of any existing import hook which claims to. In your shoes, I'd start with offering full support for Python 2.6, then once that's working (and has a good battery of tests and makes nary a peep with the -3 switch), I'd 2to3 the sources and see if anything breaks (if so, find out why, fix the 2.6 sources, iterate).
Trie (Prefix Tree) in Python
I don't know if this is the place to ask about algorithms. But let's see if I get any answers ... :) If anything is unclear I'm very happy to clarify things. I just implemented a Trie in python. However, one bit seemed to be more complicated than it ought to (as someone who loves simplicity). Perhaps someone has had a similar problem? My aim was to minimize the number of nodes by storing the largest common prefix of a sub-trie in its root. For example, if we had the words stackoverflow, stackbase and stackbased, then the tree would look something like this: [s]tack [o]verflow ______/ \_______ [b]ase \___ [d] Note that one can still think of the edges having one character (the first one of the child node). Find-query is simple to implement. Insertion is not hard, but somewhat more complex than I want.. :( My idea was to insert the keys one after the other (starting from an empty trie), by first searching for the to-be-inserted key k (Find(k)), and then rearranging/splitting the nodes locally at the place where the find-procedure stops. There turn out to be 4 cases: (Let k be the key we want to insert, and k' be the key of the node, where the search ended) k is identical to k' k is a "proper" prefix of k' k' is a "proper" prefix of k k and k' share some common prefix, but none of the cases (1), (2) or (3) occur. It seems that each of the cases are unique and thus imply different modifications of the Trie. BUT: is it really that complex? Am I missing something? Is there a better approach? Thanks :)
At a glance, it sounds like you've implemented a Patricia Trie. This approach also is called path compression in some of the literature. There should be copies of that paper that aren't behind the ACM paywall, which will include an insertion algorithm. There's also another compression method you may want to look at: level compression. The idea behind path compression is to replace strings of single child nodes with a single super node that has a "skip" count. The idea behind level compression is to replace full or nearly full subtrees with a super node with a "degree" count that says how many digits of the key the node decodes. There's also a 3rd approach called width compression, but I'm afraid my memory fails me and I couldn't find a description of it with quick googling. Level compression can shorten the average path considerably, but insertion and removal algorithms get quite complicated as they need to manage the trie nodes as similarly to dynamic arrays. For the right data sets, level compressed trees can be fast. From what I remember, they're the 2nd fastest approach for storing IP routing tables, the fastest is some sort of hash trie.
Python Comet Server
I am building a web application that has a real-time feed (similar to Facebook's newsfeed) that I want to update via a long-polling mechanism. I understand that with Python, my choices are pretty much to either use Stackless (building from their Comet wsgi example) or Cometd + Twisted. Unfortunately there is very little documentation regarding these options and I cannot find good information online about production scale users of comet on Python. Has anyone successfully implemented comet on Python in a production system? How did you go about doing it and where can I find resources to implement my own?
Orbited seems as a nice solution. Haven't tried it though. Update: things have changed in the last 2.5 years. We now have websockets in all major browsers, except IE (naturally) and a couple of very good abstractions over it, that provide many methods of emulating real-time communication. socket.io along with tornadio (socket.io 0.6) and tornadio2 (socket.io 0.7+) sock.js along with SockJS-tornado
Get class that defined method
How can I get the class that defined a method in Python? I'd want the following example to print "__main__.FooClass": class FooClass: def foo_method(self): print "foo" class BarClass(FooClass): pass bar = BarClass() print get_class_that_defined_method(bar.foo_method)
import inspect def get_class_that_defined_method(meth): for cls in inspect.getmro(meth.im_class): if meth.__name__ in cls.__dict__: return cls return None
Reloading module giving NameError: name 'reload' is not defined
I'm trying to reload a module I have already imported in Python 3. I know that you only need to import once and executing the import command again won't do anything. Executing reload(foo) is giving this error: Traceback (most recent call last): File "(stdin)", line 1, in (module) ... NameError: name 'reload' is not defined What does the error mean?
reload is a builtin in Python 2, but not in Python 3, so the error you're seeing is expected. If you truly must reload a module in Python 3, you should use either: importlib.reload for Python 3.4 and above imp.reload for Python 3.0 to 3.3 (deprecated since Python 3.4 in favour of importlib)
Two values from one input in python?
This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python? For instance, in C I can do something like this: scanf("%d %d", &var1, &var2). However, I can't figure out what the Python equivalent of that is. I figured it would just be something like var1, var2 = input("Enter two numbers here: "), but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did. Does anyone out there know a good way to do this elegantly and concisely?
The Python way to map printf("Enter two numbers here: "); scanf("%d %d", &var1, &var2) would be var1, var2 = raw_input("Enter two numbers here: ").split() Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces., Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line var1, var2 = [int(var1), int(var2)] Or you could use list comprehension var1, var2 = [int(x) for x in [var1, var2]] To sum it up, you could have done the whole thing with this one-liner: var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]
What does the percentage sign mean in Python 3.1
In the tutorial there is an example for finding prime numbers. >>> for n in range(2, 10): ... for x in range(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... I understand that the double == is a test for equality, but I don't understand the "if n % x" part. Like I can verbally walk through each part and say what the statement does for the example. But I don't understand how the percentage sign falls in. What does "if n % x" actually say?
The % does two things, depending on its arguments. In this case, it acts as the modulo operator, meaning when its arguments are numbers, it divides the first by the second and returns the remainder. 34 % 10 == 4 since 34 divided by 10 is three, with a remainder of four. If the first argument is a string, it formats it using the second argument. This is a bit involved, so I will refer to the documentation, but just as an example: >>> "foo %d bar"%5 'foo 5 bar' However, the string formatting behavior is supplemented as of Python 3.1 in favor of the string.format() mechanism: The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text. And thankfully, almost all of the new features are also available from python 2.6 onwards.
Converting integer to string in Python?
I want to convert an integer to a string in Python. I am typecasting it in vain: t=raw_input() c=[] for j in range(0,int(t)): n=raw_input() a=[] a,b= (int(i) for i in n.split(' ')) d=pow(a,b) d.str() c.append(d[0]) for j in c: print j When I try to convert it to string, it's showing an error like int doesn't have any attribute called str.
>>> str(10) '10' >>> int('10') 10 [Edit] Links to the documentation: int() str() [Edit] The problem seems to come from this line: d.str() Conversion to string is done with the builtin str() function, which basically calls the __str__() method of its parameter. Also, it shouldn't be necessary to call pow(). Try using the ** operator.
How to use numpy with 'None' value in Python?
I'd like to calculate the mean of an array in Python in this form: Matrice = [1, 2, None] I'd just like to have my None value ignored by the numpy.mean calculation but I can't figure out how to do it.
You are looking for masked arrays. Here's an example. import MA a = MA.array([1, 2, None], mask = [0, 0, 1]) print "average =", MA.average(a) Unfortunately, masked arrays aren't thoroughly supported in numpy, so you've got to look around to see what can and can't be done with them.
How can I speed up update/replace operations in PostgreSQL?
We have a rather specific application that uses PostgreSQL 8.3 as a storage backend (using Python and psycopg2). The operations we perform to the important tables are in the majority of cases inserts or updates (rarely deletes or selects). For sanity reasons we have created our own Data Mapper-like layer that works reasonably well, but it has one big bottleneck, the update performance. Of course, I'm not expecting the update/replace scenario to be as speedy as the 'insert to an empty table' one, but it would be nice to get a bit closer. Note that this system is free from concurrent updates We always set all the fields of each rows on an update, which can be seen in the terminology where I use the word 'replace' in my tests. I've so far tried two approaches to our update problem: Create a replace() procedure that takes an array of rows to update: CREATE OR REPLACE FUNCTION replace_item(data item[]) RETURNS VOID AS $$ BEGIN FOR i IN COALESCE(array_lower(data,1),0) .. COALESCE(array_upper(data,1),-1) LOOP UPDATE item SET a0=data[i].a0,a1=data[i].a1,a2=data[i].a2 WHERE key=data[i].key; END LOOP; END; $$ LANGUAGE plpgsql Create an insert_or_replace rule so that everything but the occasional delete becomes multi-row inserts CREATE RULE "insert_or_replace" AS ON INSERT TO "item" WHERE EXISTS(SELECT 1 FROM item WHERE key=NEW.key) DO INSTEAD (UPDATE item SET a0=NEW.a0,a1=NEW.a1,a2=NEW.a2 WHERE key=NEW.key); These both speeds up the updates a fair bit, although the latter slows down inserts a bit: Multi-row insert : 50000 items inserted in 1.32 seconds averaging 37807.84 items/s executemany() update : 50000 items updated in 26.67 seconds averaging 1874.57 items/s update_andres : 50000 items updated in 3.84 seconds averaging 13028.51 items/s update_merlin83 (i/d/i) : 50000 items updated in 1.29 seconds averaging 38780.46 items/s update_merlin83 (i/u) : 50000 items updated in 1.24 seconds averaging 40313.28 items/s replace_item() procedure : 50000 items replaced in 3.10 seconds averaging 16151.42 items/s Multi-row insert_or_replace: 50000 items inserted in 2.73 seconds averaging 18296.30 items/s Multi-row insert_or_replace: 50000 items replaced in 2.02 seconds averaging 24729.94 items/s Random notes about the test run: All tests are run on the same computer as the database resides; connecting to localhost. Inserts and updates are applied to the database in batches of of 500 items, each sent in its own transaction (UPDATED). All update/replace tests used the same values as were already in the database. All data was escaped using the psycopg2 adapt() function. All tables are truncated and vacuumed before use (ADDED, in previous runs only truncation happened) The table looks like this: CREATE TABLE item ( key MACADDR PRIMARY KEY, a0 VARCHAR, a1 VARCHAR, a2 VARCHAR ) So, the real question is: How can I speed up update/replace operations a bit more? (I think these findings might be 'good enough', but I don't want to give up without tapping the SO crowd :) Also anyones hints towards a more elegant replace_item(), or evidence that my tests are completely broken would be most welcome. The test script is available here if you'd like to attempt to reproduce. Remember to check it first though...it WorksForMe, but... You will need to edit the db.connect() line to suit your setup. EDIT Thanks to andres in #postgresql @ freenode I have another test with a single-query update; much like a multi-row insert (listed as update_andres above). UPDATE item SET a0=i.a0, a1=i.a1, a2=i.a2 FROM (VALUES ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ... ) AS i(key, a0, a1, a2) WHERE item.key=i.key::macaddr EDIT Thanks to merlin83 in #postgresql @ freenode and jug/jwp below I have another test with an insert-to-temp/delete/insert approach (listed as "update_merlin83 (i/d/i)" above). INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); DELETE FROM item USING temp_item WHERE item.key=temp_item.key; INSERT INTO item (key, a0, a1, a2) SELECT key, a0, a1, a2 FROM temp_item; My gut feeling is that these tests are not very representative to the performance in the real-world scenario, but I think the differences are great enough to give an indication of the most promising approaches for further investigation. The perftest.py script contains all updates as well for those of you who want to check it out. It's fairly ugly though, so don't forget your goggles :) EDIT andres in #postgresql @ freenode pointed out that I should test with an insert-to-temp/update variant (listed as "update_merlin83 (i/u)" above). INSERT INTO temp_item (key, a0, a1, a2) VALUES ( ('00:00:00:00:00:01', 'v0', 'v1', 'v2'), ('00:00:00:00:00:02', 'v3', 'v4', 'v5'), ...); UPDATE item SET a0=temp_item.a0, a1=temp_item.a1, a2=temp_item.a2 FROM temp_item WHERE item.key=temp_item.key EDIT Probably final edit: I changed my script to match our load scenario better, and it seems the numbers hold even when scaling things up a bit and adding some randomness. If anyone gets very different numbers from some other scenario I'd be interested in knowing about it.
The usual way I do these things in pg is: load raw data matching target table into temp table (no constraints) using copy, merge(the fun part), profit. I wrote a merge_by_key function specifically for these situations: http://mbk.projects.postgresql.org/ The docs aren't terribly friendly, but I'd suggest giving it a good look.
How to pull a random record using Django's ORM?
I have a model that represents paintings I present on my site. On the main webpage I'd like to show some of them: newest, one that was not visited for most time, most popular one and a random one. I'm using Django 1.0.2. While first 3 of them are easy to pull using django models, last one (random) causes me some trouble. I can ofc code it in my view, to something like this: number_of_records = models.Painting.objects.count() random_index = int(random.random()*number_of_records)+1 random_paint = models.Painting.get(pk = random_index) It doesn't look like something I'd like to have in my view tho - this is entirely part of database abstraction and should be in the model. Also, here I need to take care of removed records (then number of all records won't cover me all the possible key values) and probably lots of other things. Any other options how I can do it, preferably somehow inside the model abstraction?
Simply use: MyModel.objects.order_by('?').first() It is documented in QuerySet API.
Python: changing methods and attributes at runtime
I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that? Oh, and please don't ask why.
This example shows the differences between adding a method to a class and to an instance. >>> class Dog(): ... def __init__(self, name): ... self.name = name ... >>> skip = Dog('Skip') >>> spot = Dog('Spot') >>> def talk(self): ... print 'Hi, my name is ' + self.name ... >>> Dog.talk = talk # add method to class >>> skip.talk() Hi, my name is Skip >>> spot.talk() Hi, my name is Spot >>> del Dog.talk # remove method from class >>> skip.talk() # won't work anymore Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Dog instance has no attribute 'talk' >>> import types >>> f = types.MethodType(talk, skip, Dog) >>> skip.talk = f # add method to specific instance >>> skip.talk() Hi, my name is Skip >>> spot.talk() # won't work, since we only modified skip Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: Dog instance has no attribute 'talk'
Python display string multiple times
I want to print a character or string like '-' n number of times. Can I do it without using a loop?.. Is there a function like print('-',3) ..which would mean printing the - 3 times, like this: ---
Python 2.x: print '-' * 3 Python 3.x: print('-' * 3)
How to write Strategy Pattern in Python differently than example in Wikipedia?
In the 2009 Wikipedia entry for the Strategy Pattern, there's a example written in PHP. Most other code samples do something like: a = Context.new(StrategyA.new) a.execute #=> Doing the task the normal way b = Context.new(StrategyB.new) b.execute #=> Doing the task alternatively c = Context.new(StrategyC.new) c.execute #=> Doing the task even more alternative In the Python code a different technique is used with a Submit button. I wonder what the Python code will look like if it also did it the way the other code samples do. Update: Can it be shorter using first-class functions in Python?
The example in Python is not so different of the others. To mock the PHP script: class StrategyExample: def __init__(self, func=None): if func: self.execute = func def execute(self): print("Original execution") def executeReplacement1(): print("Strategy 1") def executeReplacement2(): print("Strategy 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat2 = StrategyExample(executeReplacement2) strat0.execute() strat1.execute() strat2.execute() Output: Original execution Strategy 1 Strategy 2 The main differences are: You don't need to write any other class or implement any interface. Instead you can pass a function reference that will be bound to the method you want. The functions can still be used separately, and the original object can have a default behavior if you want to (the if func == None pattern can be used for that). Indeed, it's clean short and elegant as usual with Python. But you lose information; with no explicit interface, the programmer is assumed as an adult to know what they are doing. Note that there are 3 ways to dynamically add a method in Python: The way I've shown you. But the method will be static, it won't get the "self" argument passed. Using the class name: StrategyExample.execute = func Here, all the instance will get func as the execute method, and will get self passed as an argument. Binding to an instance only (using the types module): strat0.execute = types.MethodType(executeReplacement1, strat0) or with Python 2, the class of the instance being changed is also required: strat0.execute = types.MethodType(executeReplacement1, strat0, StrategyExample) This will bind the new method to strat0, and only strat0, like with the first example. But start0.execute() will get self passed as an argument. If you need to use a reference to the current instance in the function, then you would combine the first and the last method. If you do not: class StrategyExample: def __init__(self, func=None): self.name = "Strategy Example 0" if func: self.execute = func def execute(self): print(self.name) def executeReplacement1(): print(self.name + " from execute 1") def executeReplacement2(): print(self.name + " from execute 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat1.name = "Strategy Example 1" strat2 = StrategyExample(executeReplacement2) strat2.name = "Strategy Example 2" strat0.execute() strat1.execute() strat2.execute() You will get: Traceback (most recent call last): File "test.py", line 28, in <module> strat1.execute() File "test.py", line 13, in executeReplacement1 print self.name + " from execute 1" NameError: global name 'self' is not defined So the proper code would be: import sys import types if sys.version_info[0] > 2: # Python 3+ create_bound_method = types.MethodType else: def create_bound_method(func, obj): return types.MethodType(func, obj, obj.__class__) class StrategyExample: def __init__(self, func=None): self.name = "Strategy Example 0" if func: self.execute = create_bound_method(func, self) def execute(self): print(self.name) def executeReplacement1(self): print(self.name + " from execute 1") def executeReplacement2(self): print(self.name + " from execute 2") if __name__ == "__main__": strat0 = StrategyExample() strat1 = StrategyExample(executeReplacement1) strat1.name = "Strategy Example 1" strat2 = StrategyExample(executeReplacement2) strat2.name = "Strategy Example 2" strat0.execute() strat1.execute() strat2.execute() This will output the expected result: Strategy Example 0 Strategy Example 1 from execute 1 Strategy Example 2 from execute 2 Of course, in the case the functions cannot be used stand alone anymore, but can still be bound to any other instance of any object, without any interface limitation.
Python - simple reading lines from a pipe
I'm trying to read lines from a pipe and process them, but I'm doing something silly and I can't figure out what. The producer is going to keep producing lines indefinitely, like this: producer.py import time while True: print 'Data' time.sleep(1) The consumer just needs to check for lines periodically: consumer.py import sys, time while True: line = sys.stdin.readline() if line: print 'Got data:', line else: time.sleep(1) When I run this in the Windows shell as python producer.py | python consumer.py, it just sleeps forever (never seems to get data?) It seems that maybe the problem is that the producer never terminates, since if I send a finite amount of data then it works fine. How can I get the data to be received and show up for the consumer? In the real application, the producer is a C++ program I have no control over.
Some old versions of Windows simulated pipes through files (so they were prone to such problems), but that hasn't been a problem in 10+ years. Try adding a sys.stdout.flush() to the producer after the print, and also try to make the producer's stdout unbuffered (by using python -u). Of course this doesn't help if you have no control over the producer -- if it buffers too much of its output you're still going to wait a long time. Unfortunately - while there are many approaches to solve that problem on Unix-like operating systems, such as pyexpect, pexpect, exscript, and paramiko, I doubt any of them works on Windows; if that's indeed the case, I'd try Cygwin, which puts enough of a Linux-like veneer on Windows as to often enable the use of Linux-like approaches on a Windows box.
What's the official way of storing settings for python programs?
Django uses real Python files for settings, Trac uses a .ini file, and some other pieces of software uses XML files to hold this information. Are one of these approaches blessed by Guido and/or the Python community more than another?
As many have said, there is no "offical" way. There are, however, many choices. There was a talk at PyCon this year about many of the available options.
Can I automatically change my PYTHONPATH when activating/deactivating a virtualenv?
I would like to have a different PYTHONPATH from my usual in a particular virtualenv. How do I set this up automatically? I realize that it's possible to hack the bin/activate file, is there a better/more standard way?
This django-users post is probably going to help you a lot. It suggests using virtualenvwrapper to wrap virtualenv, to use the add2virtualenv command. Using this, when the environment is active, you can just call: add2virtualenv directory1 directory2 ... to add the directories to your pythonpath for the current environment. It handles autonomously the PATH changes on environment switches. No black magic required. Et voila!
Joining a set of ordered-integer yielding Python iterators
Here is a seemingly simple problem: given a list of iterators that yield sequences of integers in ascending order, write a concise generator that yields only the integers that appear in every sequence. After reading a few papers last night, I decided to hack up a completely minimal full text indexer in Python, as seen here (though that version is quite old now). My problem is with the search() function, which must iterate over each posting list and yield only the document IDs that appear on every list. As you can see from the link above, my current non-recursive 'working' attempt is terrible. Example: postings = [[1, 100, 142, 322, 12312], [2, 100, 101, 322, 1221], [100, 142, 322, 956, 1222]] Should yield: [100, 322] There is at least one elegant recursive function solution to this, but I'd like to avoid that if possible. However, a solution involving nested generator expressions, itertools abuse, or any other kind of code golf is more than welcome. :-) It should be possible to arrange for the function to only require as many steps as there are items in the smallest list, and without sucking the entire set of integers into memory. In future, these lists may be read from disk, and larger than available RAM. For the past 30 minutes I've had an idea on the tip of my tongue, but I can't quite get it into code. Remember, this is just for fun!
import heapq, itertools def intersect(*its): for key, values in itertools.groupby(heapq.merge(*its)): if len(list(values)) == len(its): yield key >>> list(intersect(*postings)) [100, 322]
Iterating through a multidimensional array in Python
I have created a multidimensional array in Python like this: self.cells = np.empty((r,c),dtype=np.object) Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?
It's clear you're using numpy. With numpy you can just do: for cell in self.cells.flat: do_somethin(cell)
spawning process from python
im spawning a script that runs for a long time from a web app like this: os.spawnle(os.P_NOWAIT, "../bin/producenotify.py", "producenotify.py", "xx",os.environ) the script is spawned successfully and it runs, but till it gets over i am not able to free the port that is used by the web app, or in other words i am not able to restart the web app. how do i spawn off a process and make it completely independent of the web app? this is on linux os.
As @mark clarified it's a Linux system, the script could easily make itself fully independent, i.e., a daemon, by following this recipe. (You could also do it in the parent after an os.fork and only then os.exec... the child process). Edit: to clarify some details wrt @mark's comment on my answer: super-user privileges are not needed to "daemonize" a process as per the cookbook recipes, nor is there any need to change the current working directory (though the code in the recipe does do that and more, that's not the crucial part -- rather it's the proper logic sequence of fork, _exit and setsid calls). The various os.exec... variants that do not end in e use the parent process's environment, so that part is easy too -- see Python online docs. To address suggestions made in others' comments and answers: I believe subprocess and multiprocessing per se don't daemonize the child process, which seems to be what @mark needs; the script could do it for itself, but since some code has to be doing forks and setsid, it seems neater to me to keep all of the spawning on that low-level plane rather than mix some high-level and some low-level code in the course of the operation. Here's a vastly reduced and simplified version of the recipe at the above URL, tailored to be called in the parent to spawn a daemon child -- this way, the code can be used to execute non-Python executables just as well. As given, the code should meet the needs @mark explained, of course it can be tailored in many ways -- I strongly recommend reading the original recipe and its comments and discussions, as well as the books it recommends, for more information. import os import sys def spawnDaemon(path_to_executable, *args) """Spawn a completely detached subprocess (i.e., a daemon). E.g. for mark: spawnDaemon("../bin/producenotify.py", "producenotify.py", "xx") """ # fork the first time (to make a non-session-leader child process) try: pid = os.fork() except OSError, e: raise RuntimeError("1st fork failed: %s [%d]" % (e.strerror, e.errno)) if pid != 0: # parent (calling) process is all done return # detach from controlling terminal (to make child a session-leader) os.setsid() try: pid = os.fork() except OSError, e: raise RuntimeError("2nd fork failed: %s [%d]" % (e.strerror, e.errno)) raise Exception, "%s [%d]" % (e.strerror, e.errno) if pid != 0: # child process is all done os._exit(0) # grandchild process now non-session-leader, detached from parent # grandchild process must now close all open files try: maxfd = os.sysconf("SC_OPEN_MAX") except (AttributeError, ValueError): maxfd = 1024 for fd in range(maxfd): try: os.close(fd) except OSError: # ERROR, fd wasn't open to begin with (ignored) pass # redirect stdin, stdout and stderr to /dev/null os.open(os.devnull, os.O_RDWR) # standard input (0) os.dup2(0, 1) os.dup2(0, 2) # and finally let's execute the executable for the daemon! try: os.execv(path_to_executable, args) except Exception, e: # oops, we're cut off from the world, let's just give up os._exit(255)
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom. The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example: # mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() This is useful for simple, ad-hoc testing. One would normally use this module by writing from mymodule import MyClass, in which case _runTests() is never called, but with the snippet at the end, one can also run it by typing python mymodule.py directly from the command line. Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.
It's not idiomatic to run Clojure scripts over and over from the command line. The REPL is a better command line. Clojure being a Lisp, it's common to fire up Clojure and leave the same instance running forever, and interact with it rather than restart it. You can change functions in the running instance one at a time, run them and poke them as needed. Escaping the tedious and slow traditional edit/compile/debug cycle is a great feature of Lisps. You can easily write functions to do things like run unit tests, and just call those functions from the REPL whenever you want to run them and ignore them otherwise. It's common in Clojure to use clojure.contrib.test-is, add your test functions to your namespace, then use clojure.contrib.test-is/run-tests to run them all. Another good reason not to run Clojure from the commandline is that the startup time of the JVM can be prohibitive. If you really want to run a Clojure script from the command line, there are a bunch of ways you can do it. See the Clojure mailing list for some discussion. One way is to test for the presence of command line arguments. Given this foo.clj in the current directory: (ns foo) (defn hello [x] (println "Hello," x)) (if *command-line-args* (hello "command line") (hello "REPL")) You'll get different behavior depending how you start Clojure. $ java -cp ~/path/to/clojure.jar:. clojure.main foo.clj -- Hello, command line $ java -cp ~/path/to/clojure.jar:. clojure.main Clojure 1.1.0-alpha-SNAPSHOT user=> (use 'foo) Hello, REPL nil user=> See src/clj/clojure/main.clj in the Clojure source if you want to see how this is working. Another way is to compile your code into .class files and invoke them from the Java command line. Given a source file foo.clj: (ns foo (:gen-class)) (defn hello [x] (println "Hello," x)) (defn -main [] (hello "command line")) Make a directory to store the compiled .class files; this defaults to ./classes. You must make this folder yourself, Clojure won't create it. Also make sure you set $CLASSPATH to include ./classes and the directory with your source code; I'll assume foo.clj is in the current directory. So from the command line: $ mkdir classes $ java -cp ~/path/to/clojure.jar:./classes:. clojure.main Clojure 1.1.0-alpha-SNAPSHOT user=> (compile 'foo) foo In the classes directory you will now have a bunch of .class files. To invoke your code from the command line (running the -main function by default): $ java -cp ~/path/to/clojure.jar:./classes foo Hello, command line. There's a lot of information about compiling Clojure code on clojure.org.
Getting a list of all subdirectories in the current directory
Is there a way to return a list of all the subdirectories in the current directory in Python? I know you can do this with files, but I need to get the list of directories instead.
Do you mean immediate subdirectories, or every directory right down the tree? Either way, you could use os.walk to do this: os.walk(directory) will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so [x[0] for x in os.walk(directory)] should give you all of the directories. Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much. However, you could use it just to give you the immediate child directories: next(os.walk('.'))[1] Or see the other solutions already posted, using os.listdir and os.path.isdir, including those at "get all of the immediate subdirectories in python".
Python library for playing fixed-frequency sound
I have a mosquito problem in my house. This wouldn't usually concern a programmers' community; However, I've seen some devices that claim to deter these nasty creatures by playing a 17Khz tone. I would like to do this using my laptop. One method would be creating an MP3 with a a single, fixed-frequency tone (This can easily done by audacity), opening it with a python library and playing it repeatedly. The second would be playing a sound using the computer built-in speaker. I'm looking for something similar to QBasic Sound: SOUND 17000, 100 Is there a python library for that?
PyAudiere is a simple cross-platform solution for the problem: >>> import audiere >>> d = audiere.open_device() >>> t = d.create_tone(17000) # 17 KHz >>> t.play() # non-blocking call >>> import time >>> time.sleep(5) >>> t.stop() pyaudiere.org is gone. The site and binary installers for Python 2 (debian, windows) are available via the wayback machine e.g., here's source code pyaudiere-0.2.tar.gz. To support both Python 2 and 3 on Linux, Windows, OSX, pyaudio module could be used instead: #!/usr/bin/env python """Play a fixed frequency sound.""" from __future__ import division import math from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio try: from itertools import izip except ImportError: # Python 3 izip = zip xrange = range def sine_tone(frequency, duration, volume=1, sample_rate=22050): n_samples = int(sample_rate * duration) restframes = n_samples % sample_rate p = PyAudio() stream = p.open(format=p.get_format_from_width(1), # 8bit channels=1, # mono rate=sample_rate, output=True) s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate) samples = (int(s(t) * 0x7f + 0x80) for t in xrange(n_samples)) for buf in izip(*[samples]*sample_rate): # write several samples at a time stream.write(bytes(bytearray(buf))) # fill remainder of frameset with silence stream.write(b'\x80' * restframes) stream.stop_stream() stream.close() p.terminate() Example: sine_tone( # see http://www.phy.mtu.edu/~suits/notefreqs.html frequency=440.00, # Hz, waves per second A4 duration=3.21, # seconds to play sound volume=.01, # 0..1 how loud it is # see http://en.wikipedia.org/wiki/Bit_rate#Audio sample_rate=22050 # number of samples per second ) It is a modified (to support Python 3) version of this AskUbuntu answer.
Multiply operator applied to list(data structure)
I'm reading How to think like a computer scientist which is an introductory text for "Python Programming". I want to clarify the behaviour of multiply operator (*) when applied to lists. Consider the function make_matrix def make_matrix(rows, columns): """ >>> make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] >>> m = make_matrix(4, 2) >>> m[1][1] = 7 >>> m [[0, 0], [0, 7], [0, 0], [0, 0]] """ return [[0] * columns] * rows The actual output is [[0, 7], [0, 7], [0, 7], [0, 7]] The correct version of make_matrix is : def make_matrix(rows, columns): """ >>> make_matrix(3, 5) [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]] >>> make_matrix(4, 2) [[0, 0], [0, 0], [0, 0], [0, 0]] >>> m = make_matrix(4, 2) >>> m[1][1] = 7 >>> m [[0, 0], [0, 7], [0, 0], [0, 0]] """ matrix = [] for row in range(rows): matrix += [[0] * columns] return matrix The reason why first version of make_matrix fails ( as explained in the book at 9.8 ) is that ...each row is an alias of the other rows... I wonder why [[0] * columns] * rows causes ...each row is an alias of the other rows... but not [[0] * columns] i.e. why each [0] in a row is not an alias of other row element.
EVERYTHING in python are objects, and python never makes copies unless explicity asked to do so. When you do innerList = [0] * 10 you create a list with 10 elements, all of them refering to the same int object 0. Since integer objects are immutable, when you do innerList[1] = 15 You are changing the second element of the list so that it refers to another integer 15. That always works because of int objects immutability. That's why outerList = innerList * 5 Will create a list object with 5 elements, each one is a reference to the same innerList just as above. But since list objects are mutable: outerList[2].append('something') Is the same as: innerList.append('something') Because they are two references to the same list object. So the element ends up in that single list. It appears to be duplicated, but the fact is that there is only one list object, and many references to it. By contrast if you do outerList[1] = outerList[1] + ['something'] Here you are creating another list object (using + with lists is an explicit copy), and assigning a reference to it into the second position of outerList. If you "append" the element this way (not really appending, but creating another list), innerList will be unaffected.
Split an integer into digits to compute an ISBN checksum
I'm writing a program which calculates the check digit of an ISBN number. I have to read the user's input (nine digits of an ISBN) into an integer variable, and then multiply the last digit by 2, the second last digit by 3 and so on. How can I "split" the integer into its constituent digits to do this? As this is a basic homework exercise I am not supposed to use a list.
Just create a string out of it. myinteger = 212345 number_string = str(myinteger) That's enough. Now you can iterate over it: for ch in number_string: print ch # will print each digit in order Or you can slice it: print number_string[:2] # first two digits print number_string[-3:] # last three digits print number_string[3] # forth digit Or better, don't convert the user's input to an integer (the user types a string) isbn = raw_input() for pos, ch in enumerate(reversed(isbn)): print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2) For more information read a tutorial.
redirecting sys.stdout to python logging
So right now we have a lot of python scripts and we are trying to consolidate them and fix and redundancies. One of the things we are trying to do, is to ensure that all sys.stdout/sys.stderr goes into the python logging module. Now the main thing is, we want the following printed out: [<ERROR LEVEL>] | <TIME> | <WHERE> | <MSG> Now all sys.stdout / sys.stderr msgs pretty much in all of the python error messages are in the format of [LEVEL] - MSG, which are all written using sys.stdout/sys.stderr. I can parse the fine, in my sys.stdout wrapper and in the sys.stderr wrapper. Then call the corresponding logging level, depending on the parsed input. So basically we have a package called foo, and a subpackage called log. In __init__.py we define the following: def initLogging(default_level = logging.INFO, stdout_wrapper = None, \ stderr_wrapper = None): """ Initialize the default logging sub system """ root_logger = logging.getLogger('') strm_out = logging.StreamHandler(sys.__stdout__) strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_TIME_FORMAT, \ DEFAULT_LOG_TIME_FORMAT)) root_logger.setLevel(default_level) root_logger.addHandler(strm_out) console_logger = logging.getLogger(LOGGER_CONSOLE) strm_out = logging.StreamHandler(sys.__stdout__) #strm_out.setFormatter(logging.Formatter(DEFAULT_LOG_MSG_FORMAT, \ # DEFAULT_LOG_TIME_FORMAT)) console_logger.setLevel(logging.INFO) console_logger.addHandler(strm_out) if stdout_wrapper: sys.stdout = stdout_wrapper if stderr_wrapper: sys.stderr = stderr_wrapper def cleanMsg(msg, is_stderr = False): logy = logging.getLogger('MSG') msg = msg.rstrip('\n').lstrip('\n') p_level = r'^(\s+)?\[(?P<LEVEL>\w+)\](\s+)?(?P<MSG>.*)$' m = re.match(p_level, msg) if m: msg = m.group('MSG') if m.group('LEVEL') in ('WARNING'): logy.warning(msg) return elif m.group('LEVEL') in ('ERROR'): logy.error(msg) return if is_stderr: logy.error(msg) else: logy.info(msg) class StdOutWrapper: """ Call wrapper for stdout """ def write(self, s): cleanMsg(s, False) class StdErrWrapper: """ Call wrapper for stderr """ def write(self, s): cleanMsg(s, True) Now we would call this in one of our scripts for example: import foo.log foo.log.initLogging(20, foo.log.StdOutWrapper(), foo.log.StdErrWrapper()) sys.stdout.write('[ERROR] Foobar blew') Which would be converted into an error log message. Like: [ERROR] | 20090610 083215 | __init__.py | Foobar Blew Now the problem is when we do that, The module where the error message was logged is now the __init__ (corresponding to foo.log.__init__.py file) which defeats the whole purpose. I tried doing a deepCopy/shallowCopy of the stderr/stdout objects, but that does nothing, it still says the module the message occured in __init__.py. How can i make it so this doesn't happen?
The problem is that the logging module is looking a single layer up the call stack to find who called it, but now your function is an intermediate layer at that point (Though I'd have expected it to report cleanMsg, not __init__, as that's where you're calling into log()). Instead, you need it to go up two levels, or else pass who your caller is into the logged message. You can do this by inspecting up the stack frame yourself and grabbing the calling function, inserting it into the message. To find your calling frame, you can use the inspect module: import inspect f = inspect.currentframe(N) will look up N frames, and return you the frame pointer. ie your immediate caller is currentframe(1), but you may have to go another frame up if this is the stdout.write method. Once you have the calling frame, you can get the executing code object, and look at the file and function name associated with it. eg: code = f.f_code caller = '%s:%s' % (code.co_filename, code.co_name) You may also need to put some code to handle non-python code calling into you (ie. C functions or builtins), as these may lack f_code objects. Alternatively, following up mikej's answer, you could use the same approach in a custom Logger class inheriting from logging.Logger that overrides findCaller to navigate several frames up, rather than one.
Random hash in Python
What is the easiest way to generate a random hash (MD5) in Python?
A md5-hash is just a 128-bit value, so if you want a random one: import random hash = random.getrandbits(128) print "hash value: %032x" % hash I don't really see the point, though. Maybe you should elaborate why you need this...
Shuffling a list of objects in python
I have a list of objects in Python and I want to shuffle them. I thought I could use the random.shuffle method, but this seems to fail when the list is of objects. Is there a method for shuffling object or another way around this? import random class a: foo = "bar" a1 = a() a2 = a() b = [a1,a2] print random.shuffle(b) This will fail.
random.shuffle should work. Here's an example, where the objects are lists: from random import shuffle x = [[i] for i in range(10)] shuffle(x) # print x gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]] # of course your results will vary Note that shuffle works in place, and returns None.
Comparing 2 .txt files using difflib in Python
I am trying to compare 2 text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module. When I try something like: result = difflib.SequenceMatcher(None, testFile, comparisonFile) I get an error saying object of type 'file' has no len.
For starters, you need to pass strings to difflib.SequenceMatcher, not files: # Like so difflib.SequenceMatcher(None, str1, str2) # Or just read the files in difflib.SequenceMatcher(None, file1.read(), file2.read()) That'll fix your error anyway. To get the first non-matching string, I'll direct you to the wonderful world of difflib documentation.
Vim, Python, and Django autocompletion (pysmell?)
Does anyone know how to set up auto completion to work nicely with python, django, and vim? I've been trying to use pysmell, but I can't seem to get it set up correctly (or maybe I don't know how it works). Right now, I run pysmell in the django directory (I'm using the trunk) and move the resulting tags to my project directory, then I also run pysmell in the project directory. Vim doesn't pick up the django tags, though, and they don't get auto completed. Does anyone know how to set up auto completion in vim so that it will complete the long django functions (like get_object_or_404) as well as classes/functions in my own code? I have poked around on google but haven't found any good resources. Thanks.
First off, thank you for asking this question, as it forced me to figure this out myself and it's great! Here is the page I used as a reference: PySmell v0.6 released : orestis.gr Install PySmell using the setup.py install command. Generate the PYSMELLTAGS file for django by going to your site-packages/django directory and running: pysmell . -o ~/PYSMELLTAGS.django Copy that file to your project directory, and then ran pysmell . to generate the project PYSMELLTAGS file Make sure pysmell is in your PYTHONPATH (export PYTHONPATH=${PYTHONPATH}:/path/to/pysmell/) Run vim (vim .) Source pysmell.vim (:source /path/to/pysmell/pysmell.vim) Set the autocomplete command (:set omnifunc=pysmell#Complete) Type ^x^o to autocomplete and it should work I realize this is not a sustainable solution, but you should be able to use this as a start to getting it setup to always work (e.g., add the export to your .bashrc, add the :source to your .vimrc, setup autocmd FileType python set omnifunc=pysmell#Complete, etc.) Let me know if this is enough to get you started. It worked for me! Edit I simply added this to my .vimrc and as long as the PYSMELLTAGS & PYSMELLTAGS.django files are in my project root, it works fine without any other work: python << EOF import os import sys import vim sys.path.append("/usr/local/python/lib/python2.5/site-packages") EOF exe ":source ~/src/pysmell/pysmell.vim" autocmd FileType python set omnifunc=pysmell#Complete
Getting all items less than a month old
Is there a way to get all objects with a date less than a month ago in django. Something like: items = Item.objects.filter(less than a month old).order_by(...)
What is your definition of a "month"? 30 days? 31 days? Past that, this should do it: from datetime import datetime, timedelta last_month = datetime.today() - timedelta(days=30) items = Item.objects.filter(my_date__gte=last_month).order_by(...) Takes advantange of the gte field lookup.
Difference between dir(…) and vars(…).keys() in Python?
Is there a difference between dir(…) and vars(…).keys() in Python? (I hope there is a difference, because otherwise this would break the "one way to do it" principle... :)
Python objects store their instance variables in a dictionary that belongs to the object. vars(x) returns this dictionary (as does x.__dict__). dir(x), on the other hand, returns a dictionary of x's "attributes, its class's attributes, and recursively the attributes of its class's base classes." When you access an object's attribute using the dot operator, python does a lot more than just looking up the attribute in that objects dictionary. A common case is when x is an object of class C and you call a method m on it. class C(object): def m(self): print "m" x = C() x.m() The method m is not stored in x.__dict__. It is an attribute of the class C. When you call x.m(), python will begin by looking for m in x.__dict__, but it won't find it. However, it knows that x is an instance of C, so it will next look in C.__dict__, find it there, and call m with x as the first argument. So the difference between vars(x) and dir(x) is that dir(x) does the extra work of looking in x's class (and its bases) for attributes that are accessible from it, not just those attributes that are stored in x's own symbol table. In the above example, vars(x) returns an empty dictionary, because x has no instance variables. However, dir(x) returns ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'm']
Using a Django custom model method property in order_by()
I'm currently learning Django and some of my models have custom methods to get values formatted in a specific way. Is it possible to use the value of one of these custom methods that I've defined as a property in a model with order_by()? Here is an example that demonstrates how the property is implemented. class Author(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=40) email = models.EmailField(blank=True, verbose_name='e-mail') def _get_full_name(self): return u'%s %s' % (self.first_name, self.last_name) full_name = property(_get_full_name) def __unicode__(self): return self.full_name With this model I can do: >>> Author.objects.all() [<Author: John Doh>, <Author: Jane Doh>, <Author: Andre Miller>] >>> Author.objects.order_by('first_name') [<Author: Andre Miller>, <Author: Jane Doh>, <Author: John Doh>] But I cannot do: >>> Author.objects.order_by('full_name') FieldError: Cannot resolve keyword 'full_name' into field. Choices are: book, email, first_name, id, last_name What would be the correct way to use order_by on a custom property like this?
No, you can't do that. order_by is applied at the database level, but the database can't know anything about your custom Python methods. You can either use the separate fields to order: Author.objects.order_by('first_name', 'last_name') or do the ordering in Python: sorted(Author.objects.all(), key=lambda a: a.full_name)
Mark data as sensitive in python
I need to store a user's password for a short period of time in memory. How can I do so yet not have such information accidentally disclosed in coredumps or tracebacks? Is there a way to mark a value as "sensitive", so it's not saved anywhere by a debugger?
Edit I have made a solution that uses ctypes (which in turn uses C) to zero memory. import sys import ctypes def zerome(string): location = id(string) + 20 size = sys.getsizeof(string) - 20 memset = ctypes.cdll.msvcrt.memset # For Linux, use the following. Change the 6 to whatever it is on your computer. # memset = ctypes.CDLL("libc.so.6").memset print "Clearing 0x%08x size %i bytes" % (location, size) memset(location, 0, size) I make no guarantees of the safety of this code. It is tested to work on x86 and CPython 2.6.2. A longer writeup is here. Decrypting and encrypting in Python will not work. Strings and Integers are interned and persistent, which means you are leaving a mess of password information all over the place. Hashing is the standard answer, though of course the plaintext eventually needs to be processed somewhere. The correct solution is to do the sensitive processes as a C module. But if your memory is constantly being compromised, I would rethink your security setup.
python and sys.argv
if len(sys.argv) < 2: sys.stderr.write('Usage: sys.argv[0] ') sys.exit(1) if not os.path.exists(sys.argv[1]): sys.stderr.write('ERROR: Database sys.argv[1] was not found!') sys.exit(1) This is a portion of code I'm working on. The first part I'm trying to say if the user doesn't type python programname something then it will exit. The second part I'm trying to see if the database exists. On both places I'm unsure if I have the correct way to write out the sys.argv's by stderr or not.
BTW you can pass the error message directly to sys.exit: if len(sys.argv) < 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
How do I make python to wait for a pressed key
I want my script to wait until the user presses any key. How do I do that?
One way to do this in Python 2, is to use raw_input(): raw_input("Press Enter to continue...") In python3 it's just input()
Python JSON encoding
I'm trying to encode data to JSON in Python and I been having a quite a bit of trouble. I believe the problem is simply a misunderstanding. I'm relatively new to Python and never really got familiar with the various Python data types, so that's most likely what's messing me up. Currently I am declaring a list, looping through and another list, and appending one list within another: import simplejson, json data = [['apple', 'cat'], ['banana', 'dog'], ['pear', 'fish']] x = simplejson.loads(data) # >>> typeError: expected string or buffer.. x = simplejson.dumps(stream) # >>> [["apple", "cat"], ["banana", "dog"], ["pear", "fish"]] # - shouldn't JSON encoded strings be like: {{"apple":{"cat"},{"banana":"dog"}} So I either: I don't understand JSON Syntax I don't understand the Pythons JSON module(s) I'm using an inappropriate data type.
Python lists translate to JSON arrays. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict: >>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'}) '{"pear": "fish", "apple": "cat", "banana": "dog"}'
Facebook, Django, and Google App Engine
I'm experimenting with app-engine-patch (Django for GAE) on Google App Engine. And I would like to write a Facebook application. Is it possible to use PyFacebook and its middleware? Or is there some other solution?
I run a system on for social networks and facebook on GAE with back-end in Python, front end in Javascript and Flash. I use mostly client side js libraries to pass data back to the server side datastore. This library for facebook to be exact: http://code.google.com/p/facebookjsapi/ There is a reason for this. Most of what we are doing will be running on its own site, in iframes in different social networks and in widgets etc. But for the most part this has worked very well. It is good because we can swap out our backend at any time or even run it on multiple platforms as it is also using a python rest GAE library but any backend would do with this setup.
Correct way of handling exceptions in Python?
I have searched for other posts, as I felt this is a rather common problem, but all other Python exception questions I have found didn't reflect my problem. I will try to be as specific here as I can, so I will give a direct example. And pleeeeease do not post any workarounds for this specific problem. I am not specifically interested how you can send an email much nicer with xyz. I want to know how you generally deal with dependent, error prone statements. My question is, how to handle exceptions nicely, ones that depend on one another, meaning: Only if the first step was successful, try the next, and so on. One more criterion is: All exceptions have to be caught, this code has to be robust. For your consideration, an example: try: server = smtplib.SMTP(host) #can throw an exception except smtplib.socket.gaierror: #actually it can throw a lot more, this is just an example pass else: #only if no exception was thrown we may continue try: server.login(username, password) except SMTPAuthenticationError: pass # do some stuff here finally: #we can only run this when the first try...except was successful #else this throws an exception itself! server.quit() else: try: # this is already the 3rd nested try...except # for such a simple procedure! horrible server.sendmail(addr, [to], msg.as_string()) return True except Exception: return False finally: server.quit() return False This looks extremely unpythonic to me, and the error handling code is triple the real business code, but on the other hand how can I handle several statements that are dependent on one another, meaning statement1 is prerequisite for statement2 and so on? I am also interested in proper resource cleanup, even Python can manage that for itself. Thanks, Tom
Instead of using the try/except's else block, you could simply return when it errors: def send_message(addr, to, msg): ## Connect to host try: server = smtplib.SMTP(host) #can throw an exception except smtplib.socket.gaierror: return False ## Login try: server.login(username, password) except SMTPAuthenticationError: server.quit() return False ## Send message try: server.sendmail(addr, [to], msg.as_string()) return True except Exception: # try to avoid catching Exception unless you have too return False finally: server.quit() That's perfectly readable and Pythonic.. Another way of doing this is, rather than worry about the specific implementation, decide how you want your code to look, for example.. sender = MyMailer("username", "password") # the except SocketError/AuthError could go here try: sender.message("addr..", ["to.."], "message...") except SocketError: print "Couldn't connect to server" except AuthError: print "Invalid username and/or password!" else: print "Message sent!" Then write the code for the message() method, catching any errors you expect, and raising your own custom one, and handle that where it's relevant. Your class may look something like.. class ConnectionError(Exception): pass class AuthError(Exception): pass class SendError(Exception): pass class MyMailer: def __init__(self, host, username, password): self.host = host self.username = username self.password = password def connect(self): try: self.server = smtp.SMTP(self.host) except smtplib.socket.gaierror: raise ConnectionError("Error connecting to %s" % (self.host)) def auth(self): try: self.server.login(self.username, self.password) except SMTPAuthenticationError: raise AuthError("Invalid username (%s) and/or password" % (self.username)) def message(self, addr, to, msg): try: server.sendmail(addr, [to], msg.as_string()) except smtplib.something.senderror, errormsg: raise SendError("Couldn't send message: %s" % (errormsg)) except smtp.socket.timeout: raise ConnectionError("Socket error while sending message")
Python Subprocess.Popen from a thread
I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Another thing I've noticed is that when I set shell=False I get nothing back from the communicate when running in a thread.
You didn't supply any code for us to look at, but here's a sample that does something similar to what you describe: import threading import subprocess class MyClass(threading.Thread): def __init__(self): self.stdout = None self.stderr = None threading.Thread.__init__(self) def run(self): p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(), shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.stdout, self.stderr = p.communicate() myclass = MyClass() myclass.start() myclass.join() print myclass.stdout
Locale date formatting in Python
How do I get datetime.datetime.now() printed out in the native language? >>> session.deathDate.strftime("%a, %d %b %Y") 'Fri, 12 Jun 2009' I'd like to get the same result but in local language.
You can just set the locale like in this example: >>> import time >>> print time.strftime("%a, %d %b %Y %H:%M:%S") Sun, 23 Oct 2005 20:38:56 >>> import locale >>> locale.setlocale(locale.LC_TIME, "sv_SE") # swedish 'sv_SE' >>> print time.strftime("%a, %d %b %Y %H:%M:%S") sön, 23 okt 2005 20:39:15
How do I pass a variable by reference?
The Python documentation seems unclear about whether parameters are passed by reference or value, and the following code produces the unchanged value 'Original' class PassByReference: def __init__(self): self.variable = 'Original' self.Change(self.variable) print self.variable def Change(self, var): var = 'Changed' Is there something I can do to pass the variable by actual reference?
Arguments are passed by assignment. The rationale behind this is twofold: the parameter passed in is actually a reference to an object (but the reference is passed by value) some data types are mutable, but others aren't So: If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object. If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object. To make it even more clear, let's have some examples. List - a mutable type Let's try to modify the list that was passed to a method: def try_to_change_list_contents(the_list): print 'got', the_list the_list.append('four') print 'changed to', the_list outer_list = ['one', 'two', 'three'] print 'before, outer_list =', outer_list try_to_change_list_contents(outer_list) print 'after, outer_list =', outer_list Output: before, outer_list = ['one', 'two', 'three'] got ['one', 'two', 'three'] changed to ['one', 'two', 'three', 'four'] after, outer_list = ['one', 'two', 'three', 'four'] Since the parameter passed in is a reference to outer_list, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope. Now let's see what happens when we try to change the reference that was passed in as a parameter: def try_to_change_list_reference(the_list): print 'got', the_list the_list = ['and', 'we', 'can', 'not', 'lie'] print 'set to', the_list outer_list = ['we', 'like', 'proper', 'English'] print 'before, outer_list =', outer_list try_to_change_list_reference(outer_list) print 'after, outer_list =', outer_list Output: before, outer_list = ['we', 'like', 'proper', 'English'] got ['we', 'like', 'proper', 'English'] set to ['and', 'we', 'can', 'not', 'lie'] after, outer_list = ['we', 'like', 'proper', 'English'] Since the the_list parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list was a copy of the outer_list reference, and we had the_list point to a new list, but there was no way to change where outer_list pointed. String - an immutable type It's immutable, so there's nothing we can do to change the contents of the string Now, let's try to change the reference def try_to_change_string_reference(the_string): print 'got', the_string the_string = 'In a kingdom by the sea' print 'set to', the_string outer_string = 'It was many and many a year ago' print 'before, outer_string =', outer_string try_to_change_string_reference(outer_string) print 'after, outer_string =', outer_string Output: before, outer_string = It was many and many a year ago got It was many and many a year ago set to In a kingdom by the sea after, outer_string = It was many and many a year ago Again, since the the_string parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string was a copy of the outer_string reference, and we had the_string point to a new string, but there was no way to change where outer_string pointed. I hope this clears things up a little. EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that. How do we get around this? As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out: def return_a_whole_new_string(the_string): new_string = something_to_do_with_the_old_string(the_string) return new_string # then you could call it like my_string = return_a_whole_new_string(my_string) If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list: def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change): new_string = something_to_do_with_the_old_string(stuff_to_change[0]) stuff_to_change[0] = new_string # then you could call it like wrapper = [my_string] use_a_wrapper_to_simulate_pass_by_reference(wrapper) do_something_with(wrapper[0]) Although this seems a little cumbersome.
Experiences of creating Social Network site in Django
I plan to sneak in some Python/Django to my workdays and a possible social network site project seems like a good possibility. Django itself seems excellent, but I am skeptical about the quality of large amount of Django apps that seem to be available. I would like to hear what kind of experiences you may have had with Django in creating social network type sites. Any experiences in using any of the Django powered social network "frameworks" would also be welcome.
If you're interested in creating a social-network site in Django, you should definitely investigate Pinax. This is a project that integrates a number of apps that are useful for creating this sort of site - friends, messaging, invitations, registration, etc. They're mostly very high quality.
How to know if urllib.urlretrieve succeeds?
urllib.urlretrieve returns silently even if the file doesn't exist on the remote http server, it just saves a html page to the named file. For example: urllib.urlretrieve('http://google.com/abc.jpg', 'abc.jpg') just returns silently, even if abc.jpg doesn't exist on google.com server, the generated abc.jpg is not a valid jpg file, it's actually a html page . I guess the returned headers (a httplib.HTTPMessage instance) can be used to actually tell whether the retrieval successes or not, but I can't find any doc for httplib.HTTPMessage. Can anybody provide some information about this problem?
Consider using urllib2 if it possible in your case. It is more advanced and easy to use than urllib. You can detect any HTTP errors easily: >>> import urllib2 >>> resp = urllib2.urlopen("http://google.com/abc.jpg") Traceback (most recent call last): <<MANY LINES SKIPPED>> urllib2.HTTPError: HTTP Error 404: Not Found resp is actually HTTPResponse object that you can do a lot of useful things with: >>> resp = urllib2.urlopen("http://google.com/") >>> resp.code 200 >>> resp.headers["content-type"] 'text/html; charset=windows-1251' >>> resp.read() "<<ACTUAL HTML>>"
Converting a String to Dictionary?
How can I convert the str representation of a dict, such as the following string, into a dict? s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" I prefer not to use eval. What else can I use? The main reason for this, is one of my coworkers classes he wrote, converts all input into strings. I'm not in the mood to go and modify his classes, to deal with this issue.
Starting in Python 2.6 you can use the built-in ast.literal_eval: >>> import ast >>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}") {'muffin': 'lolz', 'foo': 'kitty'} This is safer than using eval. As its own docs say: >>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None. For example: >>> eval("shutil.rmtree('mongo')") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree onerror(os.listdir, path, sys.exc_info()) File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree names = os.listdir(path) OSError: [Errno 2] No such file or directory: 'mongo' >>> ast.literal_eval("shutil.rmtree('mongo')") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval return _convert(node_or_string) File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert raise ValueError('malformed string') ValueError: malformed string
How to find out the arity of a method in Python
I'd like to find out the arity of a method in Python (the number of parameters that it receives). Right now I'm doing this: def arity(obj, method): return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self class Foo: def bar(self, bla): pass arity(Foo(), "bar") # => 1 I'd like to be able to achieve this: Foo().bar.arity() # => 1 Update: Right now the above function fails with built-in types, any help on this would also be appreciated: # Traceback (most recent call last): # File "bla.py", line 10, in <module> # print arity('foo', 'split') # => # File "bla.py", line 3, in arity # return getattr(obj.__class__, method).func_code.co_argcount - 1 # remove self # AttributeError: 'method_descriptor' object has no attribute 'func_co
Module inspect from Python's standard library is your friend -- see the online docs! inspect.getargspec(func) returns a tuple with four items, args, varargs, varkw, defaults: len(args) is the "primary arity", but arity can be anything from that to infinity if you have varargs and/or varkw not None, and some arguments may be omitted (and defaulted) if defaults is not None. How you turn that into a single number, beats me, but presumably you have your ideas in the matter!-) This applies to Python-coded functions, but not to C-coded ones. Nothing in the Python C API lets C-coded functions (including built-ins) expose their signature for introspection, except via their docstring (or optionally via annotations in Python 3); so, you will need to fall back to docstring parsing as a last ditch if other approaches fail (of course, the docstring might be missing too, in which case the function will remain a mystery).
Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?
So I just finished watching this talk on the Python Global Interpreter Lock (GIL) http://blip.tv/file/2232410. The gist of it is that the GIL is a pretty good design for single core systems (Python essentially leaves the thread handling/scheduling up to the operating system). But that this can seriously backfire on multi-core systems and you end up with IO intensive threads being heavily blocked by CPU intensive threads, the expense of context switching, the ctrl-C problem[*] and so on. So since the GIL limits us to basically executing a Python program on one CPU my thought is why not accept this and simply use taskset on Linux to set the affinity of the program to a certain core/cpu on the system (especially in a situation with multiple Python apps running on a multi-core system)? So ultimately my question is this: has anyone tried using taskset on Linux with Python applications (especially when running multiple applications on a Linux system so that multiple cores can be used with one or two Python applications bound to a specific core) and if so what were the results? is it worth doing? Does it make things worse for certain workloads? I plan to do this and test it out (basically see if the program takes more or less time to run) but would love to hear from others as to your experiences. Addition: David Beazley (the guy giving the talk in the linked video) pointed out that some C/C++ extensions manually release the GIL lock and if these extensions are optimized for multi-core (i.e. scientific or numeric data analysis/etc.) then rather than getting the benefits of multi-core for number crunching the extension would be effectively crippled in that it is limited to a single core (thus potentially slowing your program down significantly). On the other hand if you aren't using extensions such as this The reason I am not using the multiprocessing module is that (in this case) part of the program is heavily network I/O bound (HTTP requests) so having a pool of worker threads is a GREAT way to squeeze performance out of a box since a thread fires off an HTTP request and then since it's waiting on I/O gives up the GIL and another thread can do it's thing, so that part of the program can easily run 100+ threads without hurting the CPU much and let me actually use the network bandwidth that is available. As for stackless Python/etc I'm not overly interested in rewriting the program or replacing my Python stack (availability would also be a concern). [*] Only the main thread can receive signals so if you send a ctrl-C the Python interpreter basically tries to get the main thread to run so it can handle the signal, but since it doesn't directly control which thread is run (this is left to the operating system) it basically tells the OS to keep switching threads until it eventually hits the main thread (which if you are unlucky may take a while).
Another solution is: http://docs.python.org/library/multiprocessing.html Note 1: This is not a limitation of the Python language, but of CPython implementation. Note 2: With regard to affinity, your OS shouldn't have a problem doing that itself.
How do convert unicode escape sequences to unicode characters in a python string
When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python?
Assuming Python sees the name as a normal string, you'll first have to decode it to unicode: >>> name 'Christensen Sk\xf6ld' >>> unicode(name, 'latin-1') u'Christensen Sk\xf6ld' Another way of achieving this: >>> name.decode('latin-1') u'Christensen Sk\xf6ld' Note the "u" in front of the string, signalling it is uncode. If you print this, the accented letter is shown properly: >>> print name.decode('latin-1') Christensen Sköld BTW: when necessary, you can use de "encode" method to turn the unicode into e.g. a UTF-8 string: >>> name.decode('latin-1').encode('utf-8') 'Christensen Sk\xc3\xb6ld'
How to get a reference to current module's attributes in Python
What I'm trying to do would look like this in the command line: >>> import mymodule >>> names = dir(mymodule) How can I get a reference to all the names defined in mymodule from within mymodule itself? Something like this: # mymodule.py names = dir(__thismodule__)
As previously mentioned, globals gives you a dictionary as opposed to dir() which gives you a list of the names defined in the module. The way I typically see this done is like this: import sys dir(sys.modules[__name__])
How to leave/exit/deactivate a python virtualenv?
I'm using virtualenv and the virtualenvwrapper. I can switch between virtualenv's just fine using the workon command. me@mymachine:~$ workon env1 (env1)me@mymachine:~$ workon env2 (env2)me@mymachine:~$ workon env1 (env1)me@mymachine:~$ However, how do I exit all virtual machines and workon my real machine again? Right now, the only way I have of getting back to me@mymachine:~$ is to exit the shell and start a new one. That's kind of annoying. Is there a command to workon "nothing", and if so, what is it? If such a command does not exist, how would I go about creating it?
Usually, activating a virtualenv gives you a shell function named: $ deactivate which puts things back to normal. Edit: I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports "deactivate" as the way to escape from all virtualenvs. Edit: If you are trying to leave an Anaconda environment, the procedure is a bit different: run the two-word command source deactivate since they implement deactivation using a stand-alone script. bash-4.3$ deactivate pyenv-virtualenv: deactivate must be sourced. Run 'source deactivate' instead of 'deactivate' bash-4.3$ source deactivate pyenv-virtualenv: no virtualenv has been activated.
Reclassing an instance in Python
I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class. I now want to turn this instance into an instance of my subclass without changing any properties that the instance already has (except for those that my subclass overrides anyway). The following solution seems to work. # This class comes from an external library. I don't (want) to control # it, and I want to be open to changes that get made to the class # by the library provider. class Programmer(object): def __init__(self,name): self._name = name def greet(self): print "Hi, my name is %s." % self._name def hard_work(self): print "The garbage collector will take care of everything." # This is my subclass. class C_Programmer(Programmer): def __init__(self, *args, **kwargs): super(C_Programmer,self).__init__(*args, **kwargs) self.learn_C() def learn_C(self): self._knowledge = ["malloc","free","pointer arithmetic","curly braces"] def hard_work(self): print "I'll have to remember " + " and ".join(self._knowledge) + "." # The questionable thing: Reclassing a programmer. @classmethod def teach_C(cls, programmer): programmer.__class__ = cls # <-- do I really want to do this? programmer.learn_C() joel = C_Programmer("Joel") joel.greet() joel.hard_work() #>Hi, my name is Joel. #>I'll have to remember malloc and free and pointer arithmetic and curly braces. jeff = Programmer("Jeff") # We (or someone else) makes changes to the instance. The reclassing shouldn't # overwrite these. jeff._name = "Jeff A" jeff.greet() jeff.hard_work() #>Hi, my name is Jeff A. #>The garbage collector will take care of everything. # Let magic happen. C_Programmer.teach_C(jeff) jeff.greet() jeff.hard_work() #>Hi, my name is Jeff A. #>I'll have to remember malloc and free and pointer arithmetic and curly braces. However, I'm not convinced that this solution doesn't contain any caveats I haven't thought of (sorry for the triple negation), especially because reassigning the magical __class__ just doesn't feel right. Even if this works, I can't help the feeling there should be a more pythonic way of doing this. Is there? Edit: Thanks everyone for your answers. Here is what I get from them: Although the idea of reclassing an instance by assigning to __class__ is not a widely used idiom, most answers (4 out of 6 at the time of writing) consider it a valid approach. One anwswer (by ojrac) says that it's "pretty weird at first glance," with which I agree (it was the reason for asking the question). Only one answer (by Jason Baker; with two positive comments & votes) actively discouraged me from doing this, however doing so based on the example use case moreso than on the technique in general. None of the answers, whether positive or not, finds an actual technical problem in this method. A small exception is jls who mentions to beware of old-style classes, which is likely true, and C extensions. I suppose that new-style-class-aware C extensions should be as fine with this method as Python itself (presuming the latter is true), although if you disagree, keep the answers coming. As to the question of how pythonic this is, there were a few positive answers, but no real reasons given. Looking at the Zen (import this), I guess the most important rule in this case is "Explicit is better than implicit." I'm not sure, though, whether that rule speaks for or against reclassing this way. Using {has,get,set}attr seems more explicit, as we are explicitly making our changes to the object instead of using magic. Using __class__ = newclass seems more explicit because we explicitly say "This is now an object of class 'newclass,' expect a different behaviour" instead of silently changing attributes but leaving users of the object believing they are dealing with a regular object of the old class. Summing up: From a technical standpoint, the method seems okay; the pythonicity question remains unanswered with a bias towards "yes." I have accepted Martin Geisler's answer, because the Mercurial plugin example is a quite strong one (and also because it answered a question I even hadn't asked myself yet). However, if there are any arguments on the pythonicity question, I'd still like to hear them. Thanks all so far. P.S. The actual use case is a UI data control object that needs to grow additional functionality at runtime. However, the question is meant to be very general.
Reclassing instances like this is done in Mercurial (a distributed revision control system) when extensions (plugins) want to change the object that represent the local repository. The object is called repo and is initially a localrepo instance. It is passed to each extension in turn and, when needed, extensions will define a new class which is a subclass of repo.__class__ and change the class of repo to this new subclass! It looks like this in code: def reposetup(ui, repo): # ... class bookmark_repo(repo.__class__): def rollback(self): if os.path.exists(self.join('undo.bookmarks')): util.rename(self.join('undo.bookmarks'), self.join('bookmarks')) return super(bookmark_repo, self).rollback() # ... repo.__class__ = bookmark_repo The extension (I took the code from the bookmarks extension) defines a module level function called reposetup. Mercurial will call this when initializing the extension and pass a ui (user interface) and repo (repository) argument. The function then defines a subclass of whatever class repo happens to be. It would not suffice to simply subclass localrepo since extensions need to be able to extend each other. So if the first extension changes repo.__class__ to foo_repo, the next extension should change repo.__class__ to a subclass of foo_repo and not just a subclass of localrepo. Finally the function changes the instanceø's class, just like you did in your code. I hope this code can show a legitimate use of this language feature. I think it's the only place where I've seen it used in the wild.
How to calculate a mod b in python?
Is there a modulo function in the python math library? Isn't 15 % 4, 3? But 15 mod 4 is 1, right?
There's the % sign. It's not just for the remainder, it is the modulo operation.
Counting repeated characters in a string in Python
I want to count the number of times each character is repeated in a string. Is there any particular way to do it apart from comparing each character of the string from A-Z and incrementing a counter? Update (in reference to Anthony's answer): Whatever you have suggested till now I have to write 26 times. Is there an easier way?
import collections d = collections.defaultdict(int) for c in thestring: d[c] += 1 A collections.defaultdict is like a dict (subclasses it, actually), but when an entry is sought and not found, instead of reporting it doesn't have it, it makes it and inserts it by calling the supplied 0-argument callable. Most popular are defaultdict(int), for counting (or, equivalently, to make a multiset AKA bag data structure), and defaultdict(list), which does away forever with the need to use .setdefault(akey, []).append(avalue) and similar awkward idioms. So once you've done this d is a dict-like container mapping every character to the number of times it appears, and you can emit it any way you like, of course. For example, most-popular character first: for c in sorted(d, key=d.get, reverse=True): print '%s %6d' % (c, d[c])
Why is there no GIL in the Java Virtual Machine? Why does Python need one so bad?
I'm hoping someone can provide some insight as to what's fundamentally different about the Java Virtual Machine that allows it to implement threads nicely without the need for a Global Interpreter Lock (GIL), while Python necessitates such an evil.
Python (the language) doesn't need a GIL (which is why it can perfectly be implemented on JVM [Jython] and .NET [IronPython], and those implementations multithread freely). CPython (the popular implementation) has always used a GIL for ease of coding (esp. the coding of the garbage collection mechanisms) and of integration of non-thread-safe C-coded libraries (there used to be a ton of those around;-). The Unladen Swallow project, among other ambitious goals, does plan a GIL-free virtual machine for Python -- to quote that site, "In addition, we intend to remove the GIL and fix the state of multithreading in Python. We believe this is possible through the implementation of a more sophisticated GC system, something like IBM's Recycler (Bacon et al, 2001)."
Custom Filter in Django Admin on Django 1.3 or below
How can I add a custom filter to django admin (the filters that appear on the right side of a model dashboard)? I know its easy to include a filter based on a field of that model, but what about a "calculated" field like this: class NewsItem(models.Model): headline = models.CharField(max_length=4096, blank=False) byline_1 = models.CharField(max_length=4096, blank=True) dateline = models.DateTimeField(help_text=_("date/time that appears on article")) body_copy = models.TextField(blank=False) when_to_publish = models.DateTimeField(verbose_name="When to publish", blank=True, null=True) # HOW CAN I HAVE "is_live" as part of the admin filter? It's a calculated state!! def is_live(self): if self.when_to_publish is not None: if ( self.when_to_publish < datetime.now() ): return """ <img alt="True" src="/media/img/admin/icon-yes.gif"/> """ else: return """ <img alt="False" src="/media/img/admin/icon-no.gif"/> """ is_live.allow_tags = True class NewsItemAdmin(admin.ModelAdmin): form = NewsItemAdminForm list_display = ('headline', 'id', 'is_live') list_filter = ('is_live') # how can i make this work??
Thanks to gpilotino for giving me the push into the right direction for implementing this. I noticed the question's code is using a datetime to figure out when its live . So I used the DateFieldFilterSpec and subclassed it. from django.db import models from django.contrib.admin.filterspecs import FilterSpec, ChoicesFilterSpec,DateFieldFilterSpec from django.utils.encoding import smart_unicode from django.utils.translation import ugettext as _ from datetime import datetime class IsLiveFilterSpec(DateFieldFilterSpec): """ Adds filtering by future and previous values in the admin filter sidebar. Set the is_live_filter filter in the model field attribute 'is_live_filter'. my_model_field.is_live_filter = True """ def __init__(self, f, request, params, model, model_admin): super(IsLiveFilterSpec, self).__init__(f, request, params, model, model_admin) today = datetime.now() self.links = ( (_('Any'), {}), (_('Yes'), {'%s__lte' % self.field.name: str(today), }), (_('No'), {'%s__gte' % self.field.name: str(today), }), ) def title(self): return "Is Live" # registering the filter FilterSpec.filter_specs.insert(0, (lambda f: getattr(f, 'is_live_filter', False), IsLiveFilterSpec)) To use you can put the above code into a filters.py, and import it in the model you want to add the filter to
Why are 008 and 009 invalid keys for Python dicts?
Why is it that I can't have 008 or 009 be keys for a Python dict, but 001-007 are fine? Example: some_dict = { 001: "spam", 002: "eggs", 003: "foo", 004: "bar", 008: "anything", # Throws a SyntaxError 009: "nothing" # Throws a SyntaxError } Update: Problem solved. I wasn't aware that starting a literal with a zero made it octal. That seems really odd. Why zero?
In python and some other languages, if you start a number with a 0, the number is interpreted as being in octal (base 8), where only 0-7 are valid digits. You'll have to change your code to this: some_dict = { 1: "spam", 2: "eggs", 3: "foo", 4: "bar", 8: "anything", 9: "nothing" } Or if the leading zeros are really important, use strings for the keys.
django for loop counter break
This is hopefully a quick/easy one. I know a way to work around this via a custom template tag, but I was curious if there were other methods I was over looking. I've created a gallery function of sorts for my blog, and I have a gallery list page that paginates all my galleries. Now, I don't want to show all the photos of each gallery in that list, since if each gallery even has 20 images, then that's 100 images on a page if I paginate at 5 posts. That'd be wasteful, and the wrong way to go about things. The question I have is, is there a way to just display 3 photos from the photo set? What I'd like to do, but I don't think is possible is something like (pseudocode): {% for photos in gallery.photo_set %} {% if forloop.counter lt 3 %} <img src="{{ photos.url }}"> {% endif %} {% endfor %} Judging from the documentation, unless I'm completely missing it, that's not possible via the templating system. Hence, I can just write my own template tag of sorts to work around it. I could probably do something from the view aspect, but I haven't looked to far into that idea. The other option I have is giving the model a preview field, and allow the user to select the photos they want in the preview field. Anyways, a few different options, so I thought I'd poll the audience to see how you'd do it. Any opinion is appreciated. Personally, enjoying that there's numerous ways to skin this cat.
Use: {% for photos in gallery.photo_set|slice:":3" %}
Creating a range of dates in Python
I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this? import datetime a = datetime.datetime.today() numdays = 100 dateList = [] for x in range (0, numdays): dateList.append(a - datetime.timedelta(days = x)) print dateList
Marginally better... base = datetime.datetime.today() date_list = [base - datetime.timedelta(days=x) for x in range(0, numdays)]
What does %s mean in Python?
What does %s mean in Python? And what does the following bit of code do? For instance... if len(sys.argv) < 2: sys.exit('Usage: %s database-name' % sys.argv[0]) if not os.path.exists(sys.argv[1]): sys.exit('ERROR: Database %s was not found!' % sys.argv[1])
It is a string formatting syntax (which it borrows from C). Please see "Formatting Strings": Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the %s placeholder. Edit: Here is a really simple example: name = raw_input("who are you?") print "hello %s" % (name,) The %s token allows me to insert (and potentially format) a string. Notice that the %s token is replaced by whatever I pass to the string after the % symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
Handle either a list or single integer as an argument
A function should select rows in a table based on the row name (column 2 in this case). It should be able to take either a single name or a list of names as arguments and handle them correctly. This is what I have now, but ideally there wouldn't be this duplicated code and something like exceptions would be used intelligently to choose the right way to handle the input argument: def select_rows(to_select): # For a list for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) # For a single integer for row in range(0, table.numRows()): if _table.item(row, 1).text() == to_select: table.selectRow(row)
Actually I agree with Andrew Hare above, just pass a list with a single element. But if you really must accept a non-list, how about just turning it into a list in that case? def select_rows(to_select): if type(to_select) is not list: to_select = [ to_select ] for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) The performance penalty for doing 'in' on a single-item list isn't likely to be high :-) But that does point out one other thing you might want to consider doing if your 'to_select' list may be long: consider casting it to a set so that lookups are more efficient. def select_rows(to_select): if type(to_select) is list: to_select = set( to_select ) elif type(to_select) is not set: to_select = set( [to_select] ) for row in range(0, table.numRows()): if _table.item(row, 1).text() in to_select: table.selectRow(row) -----N
run django with xampp on windows
can i run django (Python framework) site with xampp on windows? Please guide me.
XAMPP for windows contains: Apache, MySQL, PHP + PEAR, Perl, mod_php, mod_perl, mod_ssl, OpenSSL, phpMyAdmin, Webalizer, Mercury Mail Transport System for Win32 and NetWare Systems v3.32, Ming, JpGraph, FileZilla FTP Server, mcrypt, eAccelerator, SQLite, and WEB-DAV + mod_auth_mysql. There are two requirements to run django missing: Python mod_wsgi So, NO, you can't run django with XAMPP alone. You need to install additional software. However running django is very easy. If you just want to develop an application, you only need python and django. Django itself includes an internal web server that can be used for development. If you want to use django on windows for a production server, you don't even need the apache web server. You could install just: Python cherrypy That's enough to have a good django production server up and running, since cherrypy's web server is written in python and is pretty good to serve django (or any other wsgi-compatible) applications. If you're not using apache for anything else I think this setup is actually better and easier. There are other webservers you could use instead of cherrypy. But if you really want to use apache, you also need mod_wsgi.
How to keep a Python script output window open?
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open?
You have a few options: Run the program from an already-open terminal. Open a command prompt and type: python myscript.py For that to work you need the python executable in your path. Just check on how to edit environment variables on Windows, and add C:\PYTHON26 (or whatever directory you installed python to). When the program ends, it'll drop you back to the cmd prompt instead of closing the window. Add code to wait at the end of your script. Adding ... raw_input() ... at the end of the script makes it wait for the Enter key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "python -i myscript.py" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods.
How do I concatenate files in Python?
I have multiple (between 40 and 50) MP3 files that I'd like to concatenate into one file. What's the best way to do this in Python? Use fileinput module to loop through each line of each file and write it to an output file? Outsource to windows copy command?
Putting the bytes in those files together is easy... however I am not sure if that will cause a continuous play - I think it might if the files are using the same bitrate, but I'm not sure. from glob import iglob import shutil import os PATH = r'C:\music' destination = open('everything.mp3', 'wb') for filename in iglob(os.path.join(PATH, '*.mp3')): shutil.copyfileobj(open(filename, 'rb'), destination) destination.close() That will create a single "everything.mp3" file with all bytes of all mp3 files in C:\music concatenated together. If you want to pass the names of the files in command line, you can use sys.argv[1:] instead of iglob(...), etc.
Can bin() be overloaded like oct() and hex() in Python 2.6?
In Python 2.6 (and earlier) the hex() and oct() built-in functions can be overloaded in a class by defining __hex__ and __oct__ special functions. However there is not a __bin__ special function for overloading the behaviour of Python 2.6's new bin() built-in function. I want to know if there is any way of flexibly overloading bin(), and if not I was wondering why the inconsistent interface? I do know that the __index__ special function can be used, but this isn't flexible as it can only return an integer. My particular use case is from the bitstring module, where leading zero bits are considered significant: >>> a = BitString(length=12) # Twelve zero bits >>> hex(a) '0x000' >>> oct(a) '0o0000' >>> bin(a) '0b0' <------ I want it to output '0b000000000000' I suspect that there's no way of achieving this, but I thought it wouldn't hurt to ask!
As you've already discovered, you can't override bin(), but it doesn't sound like you need to do that. You just want a 0-padded binary value. Unfortunately in python 2.5 and previous, you couldn't use "%b" to indicate binary, so you can't use the "%" string formatting operator to achieve the result you want. Luckily python 2.6 does offer what you want, in the form of the new str.format() method. I believe that this particular bit of line-noise is what you're looking for: >>> '{0:010b}'.format(19) '0000010011' The syntax for this mini-language is under "format specification mini-language" in the docs. To save you some time, I'll explain the string that I'm using: parameter zero (i.e. 19) should be formatted, using a magic "0" to indicate that I want 0-padded, right-aligned number, with 10 digits of precision, in binary format. You can use this syntax to achieve a variety of creative versions of alignment and padding.
Know any creative ways to interface Python with Tcl?
Here's the situation. The company I work for has quite a bit of existing Tcl code, but some of them want to start using python. It would nice to be able to reuse some of the existing Tcl code, because that's money already spent. Besides, some of the test equipment only has Tcl API's. So, one of the ways I thought of was using the subprocess module to call into some Tcl scripts. Is subprocess my best bet? Has anyone used this fairly new piece of code: Plumage? If so what is your experience (not just for Tk)? Any other possible ways that I have not considered?
I hope you're ready for this. Standard Python import Tkinter tclsh = Tkinter.Tcl() tclsh.eval(""" proc unknown args {puts "Hello World!"} }"!dlroW olleH" stup{ sgra nwonknu corp """) Edit in Re to comment: Python's tcl interpreter is not aware of other installed tcl components. You can deal with that by adding extensions in the usual way to the tcl python actually uses. Here's a link with some detail How Tkinter can exploit Tcl/Tk extensions
What is the runtime complexity of python list functions?
I was writing a python function that looked something like this def foo(some_list): for i in range(0, len(some_list)): bar(some_list[i], i) so that it was called with x = [0, 1, 2, 3, ... ] foo(x) I had assumed that index access of lists was O(1), but was surprised to find that for large lists this was significantly slower than I expected. My question, then, is how are python lists are implemented, and what is the runtime complexity of the following Indexing: list[x] Popping from the end: list.pop() Popping from the beginning: list.pop(0) Extending the list: list.append(x) For extra credit, splicing or arbitrary pops.
there is a very detailed table on python wiki which answers your question. However, in your particular example you should use enumerate to get an index of an iterable within a loop. like so: for i, item in enumerate(some_seq): bar(item, i)
How do I look inside a Python object?
I'm starting to code in various projects using Python (including Django web development and Panda3D game development). To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properties. So say I have a Python object, what would I need to print out its contents? Is that even possible?
Python has a strong set of introspection features. Take a look at the following built-in functions: type() dir() id() getattr() hasattr() globals() locals() callable() type() and dir() are particularly useful for inspecting the type of an object and its set of attributes, respectively.
How to find out the number of CPUs using python
I want to know the number of CPUs on the local machine using Python. The result should be user/real as output by time(1) when called with an optimally scaling userspace-only program.
If you have python with a version >= 2.6 you can simply use import multiprocessing multiprocessing.cpu_count() http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count
How do I replace whitespaces with underscore and vice versa?
I want to replace whitespace with underscore in a string to create nice URLs. So that for example: "This should be connected" becomes "This_should_be_connected" I am using Python with Django. Can this be solved using regular expressions?
You don't need regular expressions, Python has a string method that does what you need: mystring.replace (" ", "_")
Command Line Arguments In Python
I am originally a C programmer. I have seen numerous tricks and "hacks" to read many different arguments. What are some of the ways Python programmers can do this? Related What’s the best way to grab/parse command line arguments passed to a Python script? Implementing a “[command] [action] [parameter]” style command-line interfaces? How can I process command line arguments in Python? How do I format positional argument help using Python’s optparse?
import sys print "\n".join(sys.argv) sys.argv is a list that contains all the arguments passed to the script on the command line. Basically, import sys print sys.argv[1:]
Python factorization
I'd just like to know the best way of listing all integer factors of a number, given a dictionary of its prime factors and their exponents. For example if we have {2:3, 3:2, 5:1} (2^3 * 3^2 * 5 = 360) Then I could write: for i in range(4): for j in range(3): for k in range(1): print 2**i * 3**j * 5**k But here I've got 3 horrible for loops. Is it possible to abstract this into a function given any factorization as a dictionary object argument?
I have blogged about this, and the fastest pure python (without itertools) comes from a post by Tim Peters to the python list, and uses nested recursive generators: def divisors(factors) : """ Generates all divisors, unordered, from the prime factorization. """ ps = sorted(set(factors)) omega = len(ps) def rec_gen(n = 0) : if n == omega : yield 1 else : pows = [1] for j in xrange(factors.count(ps[n])) : pows += [pows[-1] * ps[n]] for q in rec_gen(n + 1) : for p in pows : yield p * q for p in rec_gen() : yield p Note that the way it is written, it takes a list of prime factors, not a dictionary, i.e. [2, 2, 2, 3, 3, 5] instead of {2 : 3, 3 : 2, 5 : 1}.
Configuring Django to use SQLAlchemy
how we configure django with SQLAlchemy??
Check this: Replacing django orm
Python - Previous and next values inside a loop
How can I do thing like this in python? foo = somevalue previous = next = 0 for (i=1; i<objects.length(); i++) { if (objects[i]==foo){ previous = objects[i-1] next = objects[i+1] } }
Solutions until now only deal with lists, and most are copying the list. In my experience a lot of times that isn't possible. Also, they don't deal with the fact that you can have repeated elements in the list. The title of your question says "Previous and next values inside a loop", but if you run most answers here inside a loop, you'll end up iterating over the entire list again on each element to find it. So I've just created a function that. using the itertools module, splits and slices the iterable, and generates tuples with the previous and next elements together. Not exactly what your code does, but it is worth taking a look, because it can probably solve your problem. from itertools import tee, islice, chain, izip def previous_and_next(some_iterable): prevs, items, nexts = tee(some_iterable, 3) prevs = chain([None], prevs) nexts = chain(islice(nexts, 1, None), [None]) return izip(prevs, items, nexts) Then use it in a loop, and you'll have previous and next items in it: mylist = ['banana', 'orange', 'apple', 'kiwi', 'tomato'] for previous, item, nxt in previous_and_next(mylist): print "Item is now", item, "next is", nxt, "previous is", previous The results: Item is now banana next is orange previous is None Item is now orange next is apple previous is banana Item is now apple next is kiwi previous is orange Item is now kiwi next is tomato previous is apple Item is now tomato next is None previous is kiwi It'll work with any size list (because it doesn't copy the list), and with any iterable (files, sets, etc). This way you can just iterate over the sequence, and have the previous and next items available inside the loop. No need to search again for the item in the sequence. A short explanation of the code: tee is used to efficiently create 3 independent iterators over the input sequence chain links two sequences into one; it's used here to append a single-element sequence [None] to prevs islice is used to make a sequence of all elements except the first, then chain is used to append a None to its end There are now 3 independent sequences based on some_iterable that look like: prevs: None, A, B, C, D, E items: A, B, C, D, E nexts: B, C, D, E, None finally izip is used to change 3 sequences into one sequence of triplets. Note that izip stops when any input sequence gets exhausted, so the last element of prevs will be ignored, which is correct - there's no such element that the last element would be its prev. We could try to strip off the last elements from prevs but izip's behaviour makes that redundant Also note that tee, izip, islice and chain come from the itertools module; they operate on their input sequences on-the-fly (lazily), which makes them efficient and doesn't introduce the need of having the whole sequence in memory at once at any time.
In Python, how do I index a list with another list?
I would like to index a list with another list like this L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] and T should end up being a list containing ['a', 'd', 'h']. Is there a better way than T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h']
T = [L[i] for i in Idx]
What is the purpose of the two colons in this Python string-slicing statement?
For example, str = "hello" str[1::3] And where can I find this in Python documentation?
in sequences' description: s[i:j:k] slice of s from i to j with step k The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i)/k. In other words, the indices are i, i+k, i+2*k, i+3*k and so on, stopping when j is reached (but never including j). If i or j is greater than len(s), use len(s). If i or j are omitted or None, they become “end” values (which end depends on the sign of k). Note, k cannot be zero. If k is None, it is treated like 1.
After writing to a file, why does os.path.getsize still return the previous size?
I am trying to split up a large xml file into smaller chunks. I write to the output file and then check its size to see if its passed a threshold, but I dont think the getsize() method is working as expected. What would be a good way to get the filesize of a file that is changing in size. Ive done something like this... import string import os f1 = open('VSERVICE.xml', 'r') f2 = open('split.xml', 'w') for line in f1: if str(line) == '</Service>\n': break else: f2.write(line) size = os.path.getsize('split.xml') print('size = ' + str(size)) running this prints 0 as the filesize for about 80 iterations and then 4176. Does Python store the output in a buffer before actually outputting it?
File size is different from file position. For example, os.path.getsize('sample.txt') It exactly returns file size in bytes. But f = open('sample.txt') print f.readline() f.tell() Here f.tell() returns the current position of the file handler - i.e. where the next write will put its data. Since it is aware of the buffering, it should be accurate as long as you are simply appending to the output file.
Simple syntax for bringing a list element to the front in python?
I have an array with a set of elements. I'd like to bring a given element to the front but otherwise leave the order unchanged. Do folks have suggestions as to the cleanest syntax for this? This is the best I've been able to come up with, but it seems like bad form to have an N log N operation when an N operation could do. mylist = sorted(mylist, key=lambda x: x == targetvalue, reverse=True) Cheers, /YGA
I would go with: mylist.insert(0, mylist.pop(mylist.index(targetvalue)))
Traversing foreign key related tables in django templates
View categories = Category.objects.all() t = loader.get_template('index.html') v = Context({ 'categories': categories }) return HttpResponse(t.render(v)) Template {% for category in categories %} <h1>{{ category.name }}</h1> {% endfor %} this works great. now im trying to print each company in that category. the company table has a foreign key to the category table ive tried {% for company in category.company_set.all() %} seems django doesn't like () in templates There's a maze of information on the django site i keep getting lost between the .96, 1.0 and dev version. im running django version 1.0.2
Just get rid of the parentheses: {% for company in category.company_set.all %} Here's the appropriate documentation. You can call methods that take 0 parameters this way.
Logging All Exceptions in a pyqt4 app
What's the best way to log all of the exceptions in a pyqt4 application using the standard python logging api? I've tried wrapping exec_() in a try, except block, and logging the exceptions from that, but it only logs exceptions from the initialization of the app. As a temporary solution, I wrapped the most important methods in try, except blocks, but that can't be the only way to do it.
You need to override sys.excepthook def my_excepthook(type, value, tback): # log the exception here # then call the default handler sys.__excepthook__(type, value, tback) sys.excepthook = my_excepthook
Python: Bind an Unbound Method?
In Python, is there a way to bind an unbound method without calling it? I am writing a wxPython program, and for a certain class I decided it'd be nice to group the data of all of my buttons together as a class-level list of tuples, like so: class MyWidget(wx.Window): buttons = [("OK", OnOK), ("Cancel", OnCancel)] # ... def Setup(self): for text, handler in MyWidget.buttons: # This following line is the problem line. b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler) The problem is, since all of the values of handler are unbound methods, my program explodes in a spectacular blaze and I weep. I was looking around online for a solution to what seems like should be a relatively straightforward, solvable problem. Unfortunately I couldn't find anything. Right now, I'm using functools.partial to work around this, but does anyone know if there's a clean-feeling, healthy, Pythonic way to bind an unbound method to an instance and continue passing it around without calling it?
All functions are also descriptors, so you can bind them by calling their __get__ method: bound_handler = handler.__get__(self, MyWidget) Here's R. Hettinger's excellent guide to descriptors.
Continuous unit testing with Pydev (Python and Eclipse)
Is there a way to integrate background unit tests with the Pydev Eclipse environment? My unit tests run well, but I would like to integrate them to run in the background based on source file changes (e.g. with nose) and to integrate the result back to Eclipse (I'm thinking big red X when tests fail with a console and trace log view). No, a command prompt running nose on the side does not count. I have had this Eclipse integration when developing RoR stuff. Thanks, Tal. EDIT: Check out the new Pydev (1.6.4) http://pydev.org/manual_adv_pyunit.html
This feature has been added to PyDev 2.0.1 with an option to relaunch the tests in the last test run whenever a python file change, with an additional option to rerun only the errors -- although it'll run the full test suite if no errors were found, as the idea is that you work through your errors and when all pass a final launch for the whole suite is done (then you can move on to another task). The current nightly build has this feature incorporated.
Why is `self` in Python objects immutable?
Why can't I perform an action like the following: class Test(object): def __init__(self): self = 5 t = Test() print t I would expect it to print 5 since we're overwriting the instance with it, but instead it doesn't do anything at all. Doesn't even throw an error. Just ignores the assignment. I understand that there would be hardly any situations where one would want to do that, but it still seems odd that you can't. Update: I now understand why it doesn't work, but I'd still like to know if there is any way of replacing an instance from within the instance.
Any simple assignment to any argument of any function behaves exactly the same way in Python: binds that name to a different value, and does nothing else whatsoever. "No special case is special enough to break the rules", as the Zen of Python says!-) So, far from it being odd (that simply=assigning to a specific argument in a specific function has no externally visible effect whatsoever), it would be utterly astonishing if this specific case worked in any other way, just because of the names of the function and argument in question. Should you ever want to make a class that constructs an object of a different type than itself, such behavior is of course quite possible -- but it's obtained by overriding the special method __new__, not __init__: class Test(object): def __new__(cls): return 5 t = Test() print t This does emit 5. The __new__ / __init__ behavior in Python is an example of the "two-step construction" design pattern: the "constructor" proper is __new__ (it builds and returns a (normally uninitialized) object (normally a new one of the type/class in question); __init__ is the "initializer" which properly initializes the new object. This allows, for example, the construction of objects that are immutable once constructed: in this case everything must be done in __new__, before the immutable object is constructed, since, given that the object is immutable, __init__ cannot mutate it in order to initialize it.
Cross-platform subprocess with hidden window
I want to open a process in the background and interact with it, but this process should be invisible in both Linux and Windows. In Windows you have to do some stuff with STARTUPINFO, while this isn't valid in Linux: ValueError: startupinfo is only supported on Windows platforms Is there a simpler way than creating a separate Popen command for each OS? if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW proc = subprocess.Popen(command, startupinfo=startupinfo) if os.name == 'posix': proc = subprocess.Popen(command)
You can reduce one line :) startupinfo = None if os.name == 'nt': startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW proc = subprocess.Popen(command, startupinfo=startupinfo)
What to do with "Unexpected indent" in python?
How do I rectify the error "unexpected indent" in python?
Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are: Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines of code in a block must start with exactly the same string of whitespace. For instance: >>> def a(): ... print "foo" ... print "bar" IndentationError: unexpected indent This one is especially common when running python interactively: make sure you don't put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!) >>> print "hello" IndentationError: unexpected indent Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not? >>> if user == "Joey": ... print "Super secret powers enabled!" ... print "Revealing super secrets" IndendationError: unindent does not match any outer indentation level Expected an indented block. This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition). >>> def foo(): ... print "Bar" IndentationError: expected an indented block If you want a function that doesn't do anything, use the "no-op" command pass: >>> def foo(): ... pass Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces. The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.
Is there any Ruby or Python interpreter for Lego Mindstorm?
I want to start coding in Python or Ruby. Since I own a Lego Midstorms kit I thought it would be nice to program against it. Are there any good translators / interpeters for the Mindstorms brick?
The nxt-python and ruby-nxt projects are remote control interfaces to the NXT. They both run on a PC and remotely control the NXT via Bluetooth or USB. If you are looking for running alternative firmware on the NXT, there are several different alternatives. Steve Hassenplug has a webpage with a comprehensive list of all of the known alternative firmware and remote control options. NXT Software
PostgreSQL - how to run VACUUM from code outside transaction block?
I am using Python with psycopg2 and I'm trying to run a full VACUUM after a daily operation which inserts several thousand rows. The problem is that when I try to run the VACUUM command within my code I get the following error: psycopg2.InternalError: VACUUM cannot run inside a transaction block How do I run this from the code outside a transaction block? If it makes a difference, I have a simple DB abstraction class, a subset of which is displayed below for context (not runnable, exception-handling and docstrings omitted and line spanning adjustments made): class db(object): def __init__(dbname, host, port, user, password): self.conn = psycopg2.connect("dbname=%s host=%s port=%s \ user=%s password=%s" \ % (dbname, host, port, user, password)) self.cursor = self.conn.cursor() def _doQuery(self, query): self.cursor.execute(query) self.conn.commit() def vacuum(self): query = "VACUUM FULL" self._doQuery(query)
After more searching I have discovered the isolation_level property of the psycopg2 connection object. It turns out that changing this to 0 will move you out of a transaction block. Changing the vacuum method of the above class to the following solves it. Note that I also set the isolation level back to what it previously was just in case (seems to be 1 by default). def vacuum(self): old_isolation_level = self.conn.isolation_level self.conn.set_isolation_level(0) query = "VACUUM FULL" self._doQuery(query) self.conn.set_isolation_level(old_isolation_level) This article (near the end on that page) provides a brief explanation of isolation levels in this context.
Why isn't Python very good for functional programming?
I have always thought that functional programming can be done in Python. Thus, I was surprised that Python didn't get much of a mention in this question, and when it was mentioned, it normally wasn't very positive. However, not many reasons were given for this (lack of pattern matching and algebraic data types were mentioned). So my question is: why isn't Python very good for functional programming? Are there more reasons than its lack of pattern matching and algebraic data types? Or are these concepts so important to functional programming that a language that doesn't support them can only be classed as a second rate functional programming language? (Keep in mind that my experience with functional programming is quite limited.)
The question you reference asks which languages promote both OO and functional programming. Python does not promote functional programming even though it works fairly well. The best argument against functional programming in Python is that imperative/OO use cases are carefully considered by Guido, while functional programming use cases are not. When I write imperative Python, it's one of the prettiest languages I know. When I write functional Python, it becomes as ugly and unpleasant as your average language that doesn't have a BDFL. Which is not to say that it's bad, just that you have to work harder than you would if you switched to a language that promotes functional programming or switched to writing OO Python. Here are the functional things I miss in Python: Pattern matching Tail recursion Large library of list functions Functional dictionary class Automatic currying Concise way to compose functions Lazy lists Simple, powerful expression syntax (Python's simple block syntax prevents Guido from adding it) No pattern matching and no tail recursion mean your basic algorithms have to be written imperatively. Recursion is ugly and slow in Python. A small list library and no functional dictionaries mean that you have to write a lot of stuff yourself. No syntax for currying or composition means that point-free style is about as full of punctuation as explicitly passing arguments. Iterators instead of lazy lists means that you have to know whether you want efficiency or persistence, and to scatter calls to list around if you want persistence. (Iterators are use-once) Python's simple imperative syntax, along with its simple LL1 parser, mean that a better syntax for if-expressions and lambda-expressions is basically impossible. Guido likes it this way, and I think he's right.
Help me understand the difference between CLOBs and BLOBs in Oracle
This is mainly just a "check my understanding" type of question. Here's my understanding of CLOBs and BLOBs as they work in Oracle: CLOBs are for text like XML, JSON, etc. You should not assume what encoding the database will store it as (at least in an application) as it will be converted to whatever encoding the database was configured to use. BLOBs are for binary data. You can be reasonably assured that they will be stored how you send them and that you will get them back with exactly the same data as they were sent as. So in other words, say I have some binary data (in this case a pickled python object). I need to be assured that when I send it, it will be stored exactly how I sent it and that when I get it back it will be exactly the same. A BLOB is what I want, correct? Is it really feasible to use a CLOB for this? Or will character encoding cause enough problems that it's not worth it?
CLOB is encoding and collation sensitive, BLOB is not. When you write into a CLOB using, say, CL8WIN1251, you write a 0xC0 (which is Cyrillic letter А). When you read data back using AL16UTF16, you get back 0x0410, which is a UTF16 represenation of this letter. If you were reading from a BLOB, you would get same 0xC0 back.