instruction
stringlengths 12
148
| input
stringlengths 16
30.2k
| output
stringlengths 11
27.3k
|
|---|---|---|
Merge some list items in a Python List
|
Say I have a list like this:
[a, b, c, d, e, f, g]
How do modify that list so that it looks like this?
[a, b, c, def, g]
I would much prefer that it modified the existing list directly, not created a new list.
|
On what basis should the merging take place? Your question is rather vague. Also, I assume a, b, ..., f are supposed to be strings, that is, 'a', 'b', ..., 'f'.
>>> x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> x[3:6] = [''.join(x[3:6])]
>>> x
['a', 'b', 'c', 'def', 'g']
Check out the documentation on sequence types, specifically on mutable sequence types. And perhaps also on string methods.
|
Python sorting list of dictionaries by multiple keys
|
I have a list of dicts:
b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}]
and I need to use a multi key sort reversed by Total_Points, then not reversed by TOT_PTS_Misc.
This can be done at the command prompt like so:
a = sorted(b, key=lambda d: (-d['Total_Points'], d['TOT_PTS_Misc']))
But I have to run this through a function, where I pass in the list and the sort keys. For example, def multikeysort(dict_list, sortkeys):.
How can the lambda line be used which will sort the list, for an arbitrary number of keys that are passed in to the multikeysort function, and take into consideration that the sortkeys may have any number of keys and those that need reversed sorts will be identified with a '-' before it?
|
This answer works for any kind of column in the dictionary -- the negated column need not be a number.
def multikeysort(items, columns):
from operator import itemgetter
comparers = [((itemgetter(col[1:].strip()), -1) if col.startswith('-') else
(itemgetter(col.strip()), 1)) for col in columns]
def comparer(left, right):
for fn, mult in comparers:
result = cmp(fn(left), fn(right))
if result:
return mult * result
else:
return 0
return sorted(items, cmp=comparer)
You can call it like this:
b = [{u'TOT_PTS_Misc': u'Utley, Alex', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Russo, Brandon', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Chappell, Justin', u'Total_Points': 96.0},
{u'TOT_PTS_Misc': u'Foster, Toney', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lawson, Roman', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Lempke, Sam', u'Total_Points': 80.0},
{u'TOT_PTS_Misc': u'Gnezda, Alex', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Kirks, Damien', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Worden, Tom', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Korecz, Mike', u'Total_Points': 78.0},
{u'TOT_PTS_Misc': u'Swartz, Brian', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Burgess, Randy', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Smugala, Ryan', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Harmon, Gary', u'Total_Points': 66.0},
{u'TOT_PTS_Misc': u'Blasinsky, Scott', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Carter III, Laymon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Coleman, Johnathan', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Venditti, Nick', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Blackwell, Devon', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Kovach, Alex', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Bolden, Antonio', u'Total_Points': 60.0},
{u'TOT_PTS_Misc': u'Smith, Ryan', u'Total_Points': 60.0}]
a = multikeysort(b, ['-Total_Points', 'TOT_PTS_Misc'])
for item in a:
print item
Try it with either column negated. You will see the sort order reverse.
Next: change it so it does not use extra class....
2016-01-17
Taking my inspiration from this answer What is the best way to get the first item from an iterable matching a condition?, I shortened the code:
from operator import itemgetter as i
def multikeysort(items, columns):
comparers = [
((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
for col in columns
]
def comparer(left, right):
comparer_iter = (
cmp(fn(left), fn(right)) * mult
for fn, mult in comparers
)
return next((result for result in comparer_iter if result), 0)
return sorted(items, cmp=comparer)
In case you like your code terse.
Later 2016-01-17
This works with python3 (which eliminated the cmp argument to sort):
from operator import itemgetter as i
from functools import cmp_to_key
def multikeysort(items, columns):
comparers = [
((i(col[1:].strip()), -1) if col.startswith('-') else (i(col.strip()), 1))
for col in columns
]
def comparer(left, right):
comparer_iter = (
cmp(fn(left), fn(right)) * mult
for fn, mult in comparers
)
return next((result for result in comparer_iter if result), 0)
return sorted(items, key=cmp_to_key(comparer))
Inspired by this answer How should I do custom sort in Python 3?
|
How do I convert (or scale) axis values and redefine the tick frequency in matplotlib?
|
I am displaying a jpg image (I rotate this by 90 degrees, if this is relevant) and of course
the axes display the pixel coordinates. I would like to convert the axis so that instead of displaying the pixel number, it will display my unit of choice - be it radians, degrees, or in my case an astronomical coordinate. I know the conversion from pixel to (eg) degree. Here is a snippet of what my code looks like currently:
import matplotlib.pyplot as plt
import Image
import matplotlib
thumb = Image.open(self.image)
thumb = thumb.rotate(90)
dpi = plt.rcParams['figure.dpi']
figsize = thumb.size[0]/dpi, thumb.size[1]/dpi
fig = plt.figure(figsize=figsize)
plt.imshow(thumb, origin='lower',aspect='equal')
plt.show()
...so following on from this, can I take each value that matplotlib would print on the axis, and change/replace it with a string to output instead? I would want to do this for a specific coordinate format - eg, rather than an angle of 10.44 (degrees), I would like it to read 10 26' 24'' (ie, degrees, arcmins, arcsecs)
Finally on this theme, I'd want control over the tick frequency, on the plot. Matplotlib might print the axis value every 50 pixels, but I'd really want it every (for example) degree.
It sounds like I would like to define some kind of array with the pixel values and their converted values (degrees etc) that I want to be displayed, having control over the sampling frequency over the range xmin/xmax range.
Are there any matplotlib experts on Stack Overflow? If so, thanks very much in advance for your help! To make this a more learning experience, I'd really appreciate being prodded in the direction of tutorials etc on this kind of matplotlib problem. I've found myself getting very confused with axes, axis, figures, artists etc!
Cheers,
Dave
|
It looks like you're dealing with the matplotlib.pyplot interface, which means that you'll be able to bypass most of the dealing with artists, axes, and the like. You can control the values and labels of the tick marks by using the matplotlib.pyplot.xticks command, as follows:
tick_locs = [list of locations where you want your tick marks placed]
tick_lbls = [list of corresponding labels for each of the tick marks]
plt.xticks(tick_locs, tick_lbls)
For your particular example, you'll have to compute what the tick marks are relative to the units (i.e. pixels) of your original plot (since you're using imshow) - you said you know how to do this, though.
I haven't dealt with images much, but you may be able to use a different plotting method (e.g. pcolor) that allows you to supply x and y information. That may give you a few more options for specifying the units of your image.
For tutorials, you would do well to look through the matplotlib gallery - find something you like, and read the code that produced it. One of the guys in our office recently bought a book on Python visualization - that may be worthwhile looking at.
The way that I generally think of all the various pieces is as follows:
A Figure is a container for all the Axes
An Axes is the space where what you draw (i.e. your plot) actually shows up
An Axis is the actual x and y axes
Artists? That's too deep in the interface for me: I've never had to worry about those yet, even though I rarely use the pyplot module in production plots.
|
Simulating Pointers in Python
|
I'm trying to cross compile an in house language(ihl) to Python.
One of the ihl features is pointers and references that behave like you would expect from C or C++.
For instance you can do this:
a = [1,2]; // a has an array
b = &a; // b points to a
*b = 2; // derefernce b to store 2 in a
print(a); // outputs 2
print(*b); // outputs 2
Is there a way to duplicate this functionality in Python.
I should point out that I think I've confused a few people. I don't want pointers in Python. I just wanted to get a sense from the Python experts out there, what Python I should generate to simulate the case I've shown above
My Python isn't the greatest but so far my exploration hasn't yielded anything promising:(
I should point out that we are looking to move from our ihl to a more common language so we aren't really tied to Python if someone can suggest another language that may be more suitable.
|
This can be done explicitly.
class ref:
def __init__(self, obj): self.obj = obj
def get(self): return self.obj
def set(self, obj): self.obj = obj
a = ref([1, 2])
b = a
print a.get() # => [1, 2]
print b.get() # => [1, 2]
b.set(2)
print a.get() # => 2
print b.get() # => 2
|
SQLAlchemy: Scan huge tables using ORM?
|
I am currently playing around with SQLAlchemy a bit, which is really quite neat.
For testing I created a huge table containing my pictures archive, indexed by SHA1 hashes (to remove duplicates :-)). Which was impressingly fast...
For fun I did the equivalent of a select * over the resulting SQLite database:
session = Session()
for p in session.query(Picture):
print(p)
I expected to see hashes scrolling by, but instead it just kept scanning the disk. At the same time, memory usage was skyrocketing, reaching 1GB after a few seconds. This seems to come from the identity map feature of SQLAlchemy, which I thought was only keeping weak references.
Can somebody explain this to me? I thought that each Picture p would be collected after the hash is written out!?
|
Okay, I just found a way to do this myself. Changing the code to
session = Session()
for p in session.query(Picture).yield_per(5):
print(p)
loads only 5 pictures at a time. It seems like the query will load all rows at a time by default. However, I don't yet understand the disclaimer on that method. Quote from SQLAlchemy docs
WARNING: use this method with caution; if the same instance is present in more than one batch of rows, end-user changes to attributes will be overwritten.
In particular, itâs usually impossible to use this setting with eagerly loaded collections (i.e. any lazy=False) since those collections will be cleared for a new load when encountered in a subsequent result batch.
So if using yield_per is actually the right way (tm) to scan over copious amounts of SQL data while using the ORM, when is it safe to use it?
|
How can I use Sphinx' Autodoc-extension for private methods?
|
I am using Sphinx for documenting my python project. I have the autodoc extension enabled and have the following in my docs.
.. autoclass:: ClassName
:members:
The problem is, it only documents the non-private methods in the class. How do I include the private methods too?
|
if you are using sphinx 1.1 or above, from the sphinx documentation site at http://sphinx.pocoo.org/ext/autodoc.html,
:special-members:
:private-members:
|
Exploring and decompiling python bytecode
|
Lets say I have:
>>> def test(a):
>>> print a
Now, I want to explore see how test looks like in its compiled form.
>>> test.func_code.co_code
'|\x00\x00GHd\x00\x00S'
I can get the disassembled form using the dis module:
>>> import dis
>>> dis.dis(test)
2 0 LOAD_FAST 0 (a)
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
Is there an opensource and maintained decompiler I could use to turn the bytecode back into readable python code?
update: thanks for suggesting decompile, but it's outdated (python2.3) and no one maintains it anymore. Is there anything for python2.5 or later?
|
UnPyc
http://sourceforge.net/projects/unpyc/
It is a maintained fork of the old decompyle updated to work with 2.5 and 2.6.
|
Pythonic Swap?
|
I found that i have to perform a swap in python and i write something like this.
arr[first], arr[second] = arr[second], arr[first]
I suppose this is not so pythonic. Does somebody know how to do a swap in python more elegent?
EDIT:
I think another example will show my doubts
self.memberlist[someindexA], self.memberlist[someindexB] = self.memberlist[someindexB], self.memberlist[someindexA]
is this the only available solution for swap in python?
I did searched a lot but didn't find a nice answer...
|
a, b = b, a
Is a perfectly Pythonic idiom. It is short and readable, as long as your variable names are short enough.
|
Can I create a Python extension module in D (instead of C)
|
I hear D is link-compatible with C. I'd like to use D to create an extension module for Python. Am I overlooking some reason why it's never going to work?
|
Wait? Something like this http://pyd.dsource.org/
|
Source interface with Python and urllib2
|
How do i set the source IP/interface with Python and urllib2?
|
Unfortunately the stack of standard library modules in use (urllib2, httplib, socket) is somewhat badly designed for the purpose -- at the key point in the operation, HTTPConnection.connect (in httplib) delegates to socket.create_connection, which in turn gives you no "hook" whatsoever between the creation of the socket instance sock and the sock.connect call, for you to insert the sock.bind just before sock.connect that is what you need to set the source IP (I'm evangelizing widely for NOT designing abstractions in such an airtight, excessively-encapsulated way -- I'll be speaking about that at OSCON this Thursday under the title "Zen and the Art of Abstraction Maintenance" -- but here your problem is how to deal with a stack of abstractions that WERE designed this way, sigh).
When you're facing such problems you only have two not-so-good solutions: either copy, paste and edit the misdesigned code into which you need to place a "hook" that the original designer didn't cater for; or, "monkey-patch" that code. Neither is GOOD, but both can work, so at least let's be thankful that we have such options (by using an open-source and dynamic language). In this case, I think I'd go for monkey-patching (which is bad, but copy and paste coding is even worse) -- a code fragment such as:
import socket
true_socket = socket.socket
def bound_socket(*a, **k):
sock = true_socket(*a, **k)
sock.bind((sourceIP, 0))
return sock
socket.socket = bound_socket
Depending on your exact needs (do you need all sockets to be bound to the same source IP, or...?) you could simply run this before using urllib2 normally, or (in more complex ways of course) run it at need just for those outgoing sockets you DO need to bind in a certain way (then each time restore socket.socket = true_socket to get out of the way for future sockets yet to be created). The second alternative adds its own complications to orchestrate properly, so I'm waiting for you to clarify whether you do need such complications before explaining them all.
AKX's good answer is a variant on the "copy / paste / edit" alternative so I don't need to expand much on that -- note however that it doesn't exactly reproduce socket.create_connection in its connect method, see the source here (at the very end of the page) and decide what other functionality of the create_connection function you may want to embody in your copied/pasted/edited version if you decide to go that route.
|
Compile the Python interpreter statically?
|
I'm building a special-purpose embedded Python interpreter and want to avoid having dependencies on dynamic libraries so I want to compile the interpreter with static libraries instead (e.g. libc.a not libc.so).
I would also like to statically link all dynamic libraries that are part of the Python standard library. I know this can be done using Freeze.py, but is there an alternative so that it can be done in one step?
|
I found this (mainly concerning static compilation of Python modules):
http://bytes.com/groups/python/23235-build-static-python-executable-linux
Which describes a file used for configuration located here:
<Python_Source>/Modules/Setup
If this file isn't present, it can be created by copying:
<Python_Source>/Modules/Setup.dist
The Setup file has tons of documentation in it and the README included with the source offers lots of good compilation information as well.
I haven't tried compiling yet, but I think with these resources, I should be successful when I try. I will post my results as a comment here.
Update
To get a pure-static python executable, you must also configure as follows:
./configure LDFLAGS="-static -static-libgcc" CPPFLAGS="-static"
Once you build with these flags enabled, you will likely get lots of warnings about "renaming because library isn't present". This means that you have not configured Modules/Setup correctly and need to:
a) add a single line (near the top) like this:
*static*
(that's asterisk/star the word "static" and asterisk with no spaces)
b) uncomment all modules that you want to be available statically (such as math, array, etc...)
You may also need to add specific linker flags (as mentioned in the link I posted above). My experience so far has been that the libraries are working without modification.
It may also be helpful to run make with as follows:
make 2>&1 | grep 'renaming'
This will show all modules that are failing to compile due to being statically linked.
|
Equivalent of NotImplementedError for fields in Python
|
In Python 2.x when you want to mark a method as abstract, you can define it like so:
class Base:
def foo(self):
raise NotImplementedError("Subclasses should implement this!")
Then if you forget to override it, you get a nice reminder exception. Is there an equivalent way to mark a field as abstract? Or is stating it in the class docstring all you can do?
At first I thought I could set the field to NotImplemented, but when I looked up what it's actually for (rich comparisons) it seemed abusive.
|
Yes, you can. Use the @property decorator. For instance, if you have a field called "example" then can't you do something like this:
class Base(object):
@property
def example(self):
raise NotImplementedError("Subclasses should implement this!")
Running the following produces a NotImplementedError just like you want.
b = Base()
print b.example
|
Python hashable dicts
|
As an exercise, and mostly for my own amusement, I'm implementing a backtracking packrat parser. The inspiration for this is i'd like to have a better idea about how hygenic macros would work in an algol-like language (as apposed to the syntax free lisp dialects you normally find them in). Because of this, different passes through the input might see different grammars, so cached parse results are invalid, unless I also store the current version of the grammar along with the cached parse results. (EDIT: a consequence of this use of key-value collections is that they should be immutable, but I don't intend to expose the interface to allow them to be changed, so either mutable or immutable collections are fine)
The problem is that python dicts cannot appear as keys to other dicts. Even using a tuple (as I'd be doing anyways) doesn't help.
>>> cache = {}
>>> rule = {"foo":"bar"}
>>> cache[(rule, "baz")] = "quux"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>>
I guess it has to be tuples all the way down. Now the python standard library provides approximately what i'd need, collections.namedtuple has a very different syntax, but can be used as a key. continuing from above session:
>>> from collections import namedtuple
>>> Rule = namedtuple("Rule",rule.keys())
>>> cache[(Rule(**rule), "baz")] = "quux"
>>> cache
{(Rule(foo='bar'), 'baz'): 'quux'}
Ok. But I have to make a class for each possible combination of keys in the rule I would want to use, which isn't so bad, because each parse rule knows exactly what parameters it uses, so that class can be defined at the same time as the function that parses the rule.
Edit: An additional problem with namedtuples is that they are strictly positional. Two tuples that look like they should be different can in fact be the same:
>>> you = namedtuple("foo",["bar","baz"])
>>> me = namedtuple("foo",["bar","quux"])
>>> you(bar=1,baz=2) == me(bar=1,quux=2)
True
>>> bob = namedtuple("foo",["baz","bar"])
>>> you(bar=1,baz=2) == bob(bar=1,baz=2)
False
tl'dr: How do I get dicts that can be used as keys to other dicts?
Having hacked a bit on the answers, here's the more complete solution I'm using. Note that this does a bit extra work to make the resulting dicts vaguely immutable for practical purposes. Of course it's still quite easy to hack around it by calling dict.__setitem__(instance, key, value) but we're all adults here.
class hashdict(dict):
"""
hashable dict implementation, suitable for use as a key into
other dicts.
>>> h1 = hashdict({"apples": 1, "bananas":2})
>>> h2 = hashdict({"bananas": 3, "mangoes": 5})
>>> h1+h2
hashdict(apples=1, bananas=3, mangoes=5)
>>> d1 = {}
>>> d1[h1] = "salad"
>>> d1[h1]
'salad'
>>> d1[h2]
Traceback (most recent call last):
...
KeyError: hashdict(bananas=3, mangoes=5)
based on answers from
http://stackoverflow.com/questions/1151658/python-hashable-dicts
"""
def __key(self):
return tuple(sorted(self.items()))
def __repr__(self):
return "{0}({1})".format(self.__class__.__name__,
", ".join("{0}={1}".format(
str(i[0]),repr(i[1])) for i in self.__key()))
def __hash__(self):
return hash(self.__key())
def __setitem__(self, key, value):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def __delitem__(self, key):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def clear(self):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def pop(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def popitem(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def setdefault(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
def update(self, *args, **kwargs):
raise TypeError("{0} does not support item assignment"
.format(self.__class__.__name__))
# update is not ok because it mutates the object
# __add__ is ok because it creates a new object
# while the new object is under construction, it's ok to mutate it
def __add__(self, right):
result = hashdict(self)
dict.update(result, right)
return result
if __name__ == "__main__":
import doctest
doctest.testmod()
|
Hashables should be immutable -- not enforcing this but TRUSTING you not to mutate a dict after its first use as a key, the following approach would work:
class hashabledict(dict):
def __key(self):
return tuple((k,self[k]) for k in sorted(self))
def __hash__(self):
return hash(self.__key())
def __eq__(self, other):
return self.__key() == other.__key()
If you DO need to mutate your dicts and STILL want to use them as keys, complexity explodes hundredfolds -- not to say it can't be done, but I'll wait until a VERY specific indication before I get into THAT incredible morass!-)
|
Python iterators â how to dynamically assign self.next within a new style class?
|
As part of some WSGI middleware I want to write a python class that wraps an iterator to implement a close method on the iterator.
This works fine when I try it with an old-style class, but throws a TypeError when I try it with a new-style class. What do I need to do to get this working with a new-style class?
Example:
class IteratorWrapper1:
def __init__(self, otheriter):
self._iterator = otheriter
self.next = otheriter.next
def __iter__(self):
return self
def close(self):
if getattr(self._iterator, 'close', None) is not None:
self._iterator.close()
# other arbitrary resource cleanup code here
class IteratorWrapper2(object):
def __init__(self, otheriter):
self._iterator = otheriter
self.next = otheriter.next
def __iter__(self):
return self
def close(self):
if getattr(self._iterator, 'close', None) is not None:
self._iterator.close()
# other arbitrary resource cleanup code here
if __name__ == "__main__":
for i in IteratorWrapper1(iter([1, 2, 3])):
print i
for j in IteratorWrapper2(iter([1, 2, 3])):
print j
Gives the following output:
1
2
3
Traceback (most recent call last):
...
TypeError: iter() returned non-iterator of type 'IteratorWrapper2'
|
What you're trying to do makes sense, but there's something evil going on inside Python here.
class foo(object):
c = 0
def __init__(self):
self.next = self.next2
def __iter__(self):
return self
def next(self):
if self.c == 5: raise StopIteration
self.c += 1
return 1
def next2(self):
if self.c == 5: raise StopIteration
self.c += 1
return 2
it = iter(foo())
# Outputs: <bound method foo.next2 of <__main__.foo object at 0xb7d5030c>>
print it.next
# 2
print it.next()
# 1?!
for x in it:
print x
foo() is an iterator which modifies its next method on the fly--perfectly legal anywhere else in Python. The iterator we create, it, has the method we expect: it.next is next2. When we use the iterator directly, by calling next(), we get 2. Yet, when we use it in a for loop, we get the original next, which we've clearly overwritten.
I'm not familiar with Python internals, but it seems like an object's "next" method is being cached in tp_iternext (http://docs.python.org/c-api/typeobj.html#tp_iternext), and then it's not updated when the class is changed.
This is definitely a Python bug. Maybe this is described in the generator PEPs, but it's not in the core Python documentation, and it's completely inconsistent with normal Python behavior.
You could work around this by keeping the original next function, and wrapping it explicitly:
class IteratorWrapper2(object):
def __init__(self, otheriter):
self.wrapped_iter_next = otheriter.next
def __iter__(self):
return self
def next(self):
return self.wrapped_iter_next()
for j in IteratorWrapper2(iter([1, 2, 3])):
print j
... but that's obviously less efficient, and you should not have to do that.
|
Alternative to the `match = re.match(); if match: ...` idiom?
|
If you want to check if something matches a regex, if so, print the first group, you do..
import re
match = re.match("(\d+)g", "123g")
if match is not None:
print match.group(1)
This is completely pedantic, but the intermediate match variable is a bit annoying..
Languages like Perl do this by creating new $1..$9 variables for match groups, like..
if($blah ~= /(\d+)g/){
print $1
}
From this reddit comment,
with re_context.match('^blah', s) as match:
if match:
...
else:
...
..which I thought was an interesting idea, so I wrote a simple implementation of it:
#!/usr/bin/env python2.6
import re
class SRE_Match_Wrapper:
def __init__(self, match):
self.match = match
def __exit__(self, type, value, tb):
pass
def __enter__(self):
return self.match
def __getattr__(self, name):
if name == "__exit__":
return self.__exit__
elif name == "__enter__":
return self.__name__
else:
return getattr(self.match, name)
def rematch(pattern, inp):
matcher = re.compile(pattern)
x = SRE_Match_Wrapper(matcher.match(inp))
return x
return match
if __name__ == '__main__':
# Example:
with rematch("(\d+)g", "123g") as m:
if m:
print(m.group(1))
with rematch("(\d+)g", "123") as m:
if m:
print(m.group(1))
(This functionality could theoretically be patched into the _sre.SRE_Match object)
It would be nice if you could skip the execution of the with statement's code block, if there was no match, which would simplify this to..
with rematch("(\d+)g", "123") as m:
print(m.group(1)) # only executed if the match occurred
..but this seems impossible based of what I can deduce from PEP 343
Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf..
|
I don't think it's trivial. I don't want to have to sprinkle a redundant conditional around my code if I'm writing code like that often.
This is slightly odd, but you can do this with an iterator:
import re
def rematch(pattern, inp):
matcher = re.compile(pattern)
matches = matcher.match(inp)
if matches:
yield matches
if __name__ == '__main__':
for m in rematch("(\d+)g", "123g"):
print(m.group(1))
The odd thing is that it's using an iterator for something that isn't iterating--it's closer to a conditional, and at first glance it might look like it's going to yield multiple results for each match.
It does seem odd that a context manager can't cause its managed function to be skipped entirely; while that's not explicitly one of the use cases of "with", it seems like a natural extension.
|
Is it better to use an exception or a return code in Python?
|
You may know this recommendation from Microsoft about the use of exceptions in .NET:
Performance Considerations
...
Throw exceptions only for
extraordinary conditions, ...
In addition, do not throw an exception
when a return code is sufficient...
(See the whole text at http://msdn.microsoft.com/en-us/library/system.exception.aspx.)
As a point of comparison, would you recommend the same for Python code?
|
The pythonic thing to do is to raise and handle exceptions. The excellent book "Python in a nutshell" discusses this in 'Error-Checking Strategies' in Chapter 6.
The book discusses EAFP ("it's easier to ask forgiveness than permission") vs. LBYL ("look before you leap").
So to answer your question:
No, I would not recommend the same for python code. I suggest you read chapter 6 of Python in a nutshell.
|
Mercurial scripting with python
|
I am trying to get the mercurial revision number/id (it's a hash not a number) programmatically in python.
The reason is that I want to add it to the css/js files on our website like so:
<link rel="stylesheet" href="example.css?{% mercurial_revision "example.css" %}" />
So that whenever a change is made to the stylesheet, it will get a new url and no longer use the old cached version.
OR if you know where to find good documentation for the mercurial python module, that would also be helpful. I can't seem to find it anywhere.
My Solution
I ended up using subprocess to just run a command that gets the hg node. I chose this solution because the api is not guaranteed to stay the same, but the bash interface probably will:
import subprocess
def get_hg_rev(file_path):
pipe = subprocess.Popen(
["hg", "log", "-l", "1", "--template", "{node}", file_path],
stdout=subprocess.PIPE
)
return pipe.stdout.read()
example use:
> path_to_file = "/home/jim/workspace/lgr/pinax/projects/lgr/site_media/base.css"
> get_hg_rev(path_to_file)
'0ed525cf38a7b7f4f1321763d964a39327db97c4'
|
It's true there's no official API, but you can get an idea about best practices by reading other extensions, particularly those bundled with hg. For this particular problem, I would do something like this:
from mercurial import ui, hg
from mercurial.node import hex
repo = hg.repository('/path/to/repo/root', ui.ui())
fctx = repo.filectx('/path/to/file', 'tip')
hexnode = hex(fctx.node())
Update At some point the parameter order changed, now it's like this:
repo = hg.repository(ui.ui(), '/path/to/repo/root' )
|
Integrate Python And C++
|
I'm learning C++ because it's a very flexible language. But for internet things like Twitter, Facebook, Delicious and others, Python seems a much better solution.
Is it possible to integrate C++ and Python in the same project?
|
Interfacing Python with C/C++ is not an easy task.
Here I copy/paste a previous answer on a previous question for the different methods to write a python extension. Featuring Boost.Python, SWIG, Pybindgen...
You can write an extension yourself in C or C++ with the Python C-API.
In a word: don't do that except for learning how to do it. It's very difficult to do it correctly. You will have to increment and decrement references by hand and write a lot of code just to expose one function, with very few benefits.
Swig:
pro: you can generate bindings for many scripting languages.
cons: I don't like the way the parser works. I don't know if they've made some progress but two years ago the C++ parser was quite limited. Most of the time I had to copy/paste my .h headers to add some % characters and to give extra hints to the swig parser.
I also needed to deal with the Python C-API from time to time for (not so) complicated type conversions.
I'm not using it anymore.
Boost.Python:
pro:
It's a very complete library. It allows you to do almost everything that is possible with the C-API, but in C++. I never had to write a C-API code with this library. I also never encountered a bug due to the library. Code for bindings either works like a charm or refuses to compile.
It's probably one of the best solutions currently available if you already have some C++ library to bind. But if you only have a small C function to rewrite, I would probably try with Cython.
cons: if you don't have a precompiled Boost.Python library you're going to use Bjam (sort of a replacement of make). I really hate Bjam and its syntax.
Python libraries created with B.P tend to become obese. It also takes a lot of time to compile them.
Py++: it's Boost.Python made easy. Py++ uses a C++ parser to read your code and then generates Boost.Python code automatically. You also have a great support from its author (no it's not me ;-) ).
cons: only the problems due to Boost.Python itself.
Edit this project looks discontinued. While probably still working it may be better to consider switching.
Pybindgen:
It generates the code dealing with the C-API. You can either describe functions and classes in a Python file, or let Pybindgen read your headers and generate bindings automatically (for this it uses pygccxml, a python library wrote by the author of Py++).
cons: it's a young project, with a smaller team than Boost.Python. There are still some limitations: you cannot expose your own C++ exceptions, you cannot use multiple inheritance for your C++ classes.
Anyway it's worth trying!
Pyrex and Cython:
Here you don't write real C/C++ but a mix between Python and C. This intermediate code will generate a regular Python module.
Edit Jul 22 2013: Now Py++ looks discontinued, I'm now looking for a good alternative. I'm currently experimenting with Cython for my C++ library. This language is a mix between Python and C. Within a Cython function you can use either Python or C/C++ entities (functions, variables, objects, ...).
Cython is quite easy to learn, has very good performance, and you can even avoid C/C++ completely if you don't have to interface legacy C++ libraries.
However for C++ it comes with some problems. It is less "automagic" than Py++ was, so it's probably better for stable C++ API (which is now the case of my library). The biggest problem I see with Cython is with C++ polymorphism. With Py++/boost:python I was able to define a virtual method in C++, override it in Python, and have the Python version called within C++. With Cython it's still doable but you need to explicitly use the C-Python API.
Edit 2015-12-14:
There is a new one, pybind11, similar to Boost.Python but with some potential advantages. For example it uses C++11 language features to make it simpler to create new bindings. Also it is a header-only library, so there is nothing to compile before using it, and no library to link.
I played with it a little bit and it was indeed quite simple and pleasant to use. My only fear is that like Boot.Python it could lead to long compilation time and large libraries. I haven't done any benchmark yet.
|
SQLAlchemy and django, is it production ready?
|
Has anyone used SQLAlchemy in addition to Django's ORM?
I'd like to use Django's ORM for object manipulation and SQLalchemy for complex queries (like those that require left outer joins).
Is it possible?
Note: I'm aware about django-sqlalchemy but the project doesn't seem to be production ready.
|
What I would do,
Define the schema in Django orm, let it write the db via syncdb. You get the admin interface.
In view1 you need a complex join
def view1(request):
import sqlalchemy
data = sqlalchemy.complex_join_magic(...)
...
payload = {'data': data, ...}
return render_to_response('template', payload, ...)
|
Count occurrence of a character in a string
|
What's the simplest way to count the number of occurrences of a character in a string?
e.g. count the number of times 'a' appears in 'Mary had a little lamb'
|
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
Or:
from collections import Counter
sentence = 'Mary had a little lamb'
print(Counter(list(sentence))['a'])
|
Print current call stack from a method in Python code
|
In Python, how can I print the current call stack from within a method (for debugging purposes).
|
Here's an example of getting the stack via the traceback module, and printing it:
import traceback
def f():
g()
def g():
for line in traceback.format_stack():
print(line.strip())
f()
# Prints:
# File "so-stack.py", line 10, in <module>
# f()
# File "so-stack.py", line 4, in f
# g()
# File "so-stack.py", line 7, in g
# for line in traceback.format_stack():
If you really only want to print the stack to stderr, you can use:
traceback.print_stack()
Or to print to stdout (useful if want to keep redirected output together), use:
traceback.print_stack(file=sys.stdout)
But getting it via traceback.format_stack() lets you do whatever you like with it.
|
Python search in lists of lists
|
I have a list of two-item lists and need to search for things in it.
If the list is:
list =[ ['a','b'], ['a','c'], ['b','d'] ]
I can search for a pair easily by doing
['a','b'] in list
Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:
for i in range (0, len(list)):
if list[i][1]==search:
found=1
But is there a (better) way without the for loop? I don't need to know i or keep the loop going after it's found.
|
Nothing against RichieHindle's and Anon's answers, but here's how I'd write it:
data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
any(e[1] == search for e in data)
Like RichieHindle said, there is a hidden loop in the implementation of any (although I think it breaks out of the loop as soon as it finds a match).
|
Having Django serve downloadable files
|
I want users on the site to be able to download files whose paths are obscured so they cannot be directly downloaded.
For instance, I'd like the URL to be something like this, "http://example.com/download/?f=somefile.txt
And on the server, I know that all downloadable files reside in a folder "/home/user/files/".
Is there a way to make Django serve that file for download as opposed to trying to find a URL and View to display it?
|
For the "best of both worlds" you could combine S.Lott's solution with the xsendfile module: django generates the path to the file (or the file itself), but the actual file serving is handled by Apache/Lighttpd. Once you've set up mod_xsendfile, integrating with your view takes a few lines of code:
from django.utils.encoding import smart_str
response = HttpResponse(mimetype='application/force-download') # mimetype is replaced by content_type for django 1.7
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
# It's usually a good idea to set the 'Content-Length' header too.
# You can also set any other required headers: Cache-Control, etc.
return response
Of course, this will only work if you have control over your server, or your hosting company has mod_xsendfile already set up.
|
Remove all occurrences of a value from a Python list
|
In Python remove() will remove the first occurrence of value in a list.
How to remove all occurrences of a value from a list, without sorting the list?
This is what I have in mind.
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> def remove_values_from_list(the_list, val):
while val in the_list:
the_list.remove(val)
>>> remove_values_from_list(x, 2)
>>> x
[1, 3, 4, 3]
|
Functional approach:
2.x
>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]
3.x
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]
|
Creating a board game simulator (Python?) (Pygame?)
|
I've decided to start working on programming an old favorite of mine. I've never done a game before and also never done a large project in Python.
The game is the old Avalon Hill game Russian Campaign
I've been playing with PyGame a little bit and was wondering if there were reasons not to try to do this with PyGame and go after some other engine/language.
What would be the disadvantages of using Pygame to build this?
I'm not worried about AI, primarily I'd just love to get a minimal two player version of the game up and running. Bonuses would be the ability to save the state of the game and also to play over a network.
Do's and Dont's for starting this project would be greatly appreciated.
|
Separate the "back-end" engine (which keeps track of board state, receives move orders from front-ends, generates random numbers to resolve battles, sends updates to front-ends, deals with saving and restoring specific games, ...) from "front-end" ones, which basically supply user interfaces for all of this.
PyGame is one suitable technology for a client-side front-end, but you could implement multiple front-ends (maybe a PyGame one, a browser-based one, a text-based one for debugging, etc, etc). The back-end of course could care less about PyGame or other UI technologies. Python is fine for most front-ends (except ones that need to be in Javascript, Actionscript, etc, if you write front-ends for browsers, Flash, etc;-) and definitely fine for thre back-end.
Run back-end and front-ends as separate processes and communicate as simply as you possibly can -- for a turn-based game (as I believe this one is), XML-RPC or some even simpler variant (JSON payloads going back and forth over HTTP POST and replies to them, say) would seem best.
I'd start with the back-end (probably using JSON for payloads, as I mentioned), as a dirt-simple WSGI server (maybe with a touch of werkzeug or the like to help out with mdidleware), and a simple-as-dirt debugging command-line client. At each step I would then be enriching either the server side (back-end) or the client side (front-end) carefully avoiding doing too-big OR any simultaneous "steps". I wouldn't use "heavy" technologies nor any big frameworks doing magical things behind my back (no ORMs, Django, SOAP, ...).
Make sure you use a good source code repository (say hg, or maybe svn if you know you'll be doing it all alone, or bazaar or git if you already know them).
|
Implement touch using Python?
|
touch is a Unix utility that sets the modification and access times of files to the current time of day. If the file doesn't exist, it is created with default permissions.
How would you implement it as a Python function? Try to be cross platform and complete.
(Current Google results for "python touch file" are not that great, but point to os.utime.)
|
This tries to be a little more race-free than the other solutions. (The with keyword is new in Python 2.5.)
import os
def touch(fname, times=None):
with open(fname, 'a'):
os.utime(fname, times)
Roughly equivalent to this.
import os
def touch(fname, times=None):
fhandle = open(fname, 'a')
try:
os.utime(fname, times)
finally:
fhandle.close()
Now, to really make it race-free, you need to use futimes and change the timestamp of the open filehandle, instead of opening the file and then changing the timestamp on the filename (which may have been renamed). Unfortunately, Python doesn't seem to provide a way to call futimes without going through ctypes or similar...
EDIT
As noted by Nate Parsons, Python 3.3 will add specifying a file descriptor (when os.supports_fd) to functions such as os.utime, which will use the futimes syscall instead of the utimes syscall under the hood. In other words:
import os
def touch(fname, mode=0o666, dir_fd=None, **kwargs):
flags = os.O_CREAT | os.O_APPEND
with os.fdopen(os.open(fname, flags=flags, mode=mode, dir_fd=dir_fd)) as f:
os.utime(f.fileno() if os.utime in os.supports_fd else fname,
dir_fd=None if os.supports_fd else dir_fd, **kwargs)
|
How to implement a scripting language into a C application?
|
I have a C application and I want to include a Scripting Language to put certain functionality into scripts. I just have no experience with that and don't know exactly where to start (Still learning C and trying to understand the application).
How does embedding and communication between my app and the scripts actually work? I think I need the interpreter for the scripting language as a library (.dll on Windows or C Source Code that can be compiled into my application)? And then can I do something like
interpreter->run("myscript", some_object);
How would the script know about the properties of the object? Say my script wants to read or modify some_object->some_field?
Are there any scripting languages that are optimized for that sort of embedding? I know that there is Lua which is popular in game dev, and languages like Python, Perl, PHP or Ruby which seem to be more targeted as stand-alone applications, but my knowledge in the deep architecture does not allow more educated guesses :) (Tagged Lua and Python because they would be my favorites, but as long as it runs on x86 Windows, Linux and Mac OS X, I'm open for other scripting languages as long as they are easy to implement into a C application)
|
Lua. It has a very small footprint, is rather fast, and I found it (subjectively) to have the most pleasant API to interact with C.
If you want to touch the Lua objects from C - it's quite easy using the built-in APIs. If you want to touch C data from Lua - it's a bit more work, typically you'd need to make wrapper methods to expose what you want to allow the Lua to modify.
Small code base and tight control over the amount of default libraries introduced into your embeded interpreter also means that you can make reasonable assumptions over the security.
The only odd part is the 1-based array numbering, however, it was not that big of a deal compared to what I thought, given the existence of the iterators.
How to integrate with C: the distribution tarball for Lua has a directory "etc" with a few very good useful examples that should quickly get you started. Specifically - etc/min.c shows how to start up an interpreter, make it interpret the file, and make it call the C function ('print' in that case). From there on you can go by reading the Lua documentation and the source of the standard libraries included with the distribution.
|
models.py getting huge, what is the best way to break it up?
|
Directions from my supervisor:
"I want to avoid putting any logic in the models.py. From here on out, let's use that as only classes for accessing the database, and keep all logic in external classes that use the models classes, or wrap them."
I feel like this is the wrong way to go. I feel that keeping logic out of the models just to keep the file small is a bad idea. If the logic is best in the model, that's where it really should go regardless of file size.
So is there a simple way to just use includes? In PHP-speak, I'd like to propose to the supervisor that we just have models.py include() the model classes from other places. Conceptually, this would allow the models to have all the logic we want, yet keep file size down via increasing the number of files (which leads to less revision control problems like conflicts, etc.).
So, is there a simple way to remove model classes from the models.py file, but still have the models work with all of the Django tools? Or, is there a completely different yet elegant solution to the general problem of a "large" models.py file? Any input would be appreciated.
|
It's natural for model classes to contain methods to operate on the model. If I have a Book model, with a method book.get_noun_count(), that's where it belongs--I don't want to have to write "get_noun_count(book)", unless the method actually intrinsically belongs with some other package. (It might--for example, if I have a package for accessing Amazon's API with "get_amazon_product_id(book)".)
I cringed when Django's documentation suggested putting models in a single file, and I took a few minutes from the very beginning to figure out how to split it into a proper subpackage.
site/models/__init__.py
site/models/book.py
__init__.py looks like:
from .book import Book
so I can still write "from site.models import Book".
The following is only required for versions prior to Django 1.7, see
https://code.djangoproject.com/ticket/3591
The only trick is that you need to explicitly set each model's application, due to a bug in Django: it assumes that the application name is the third-to-last entry in the model path. "site.models.Book" results in "site", which is correct; "site.models.book.Book" makes it think the application name is "models". This is a pretty nasty hack on Django's part; it should probably search the list of installed applications for a prefix match.
class Book(models.Model):
class Meta: app_label = "site"
You could probably use a base class or metaclass to generalize this, but I haven't bothered with that yet.
|
How to use schemas in Django?
|
I whould like to use postgreSQL schemas with django, how can I do this?
|
I've been using:
db_table = '"schema"."tablename"'
in the past without realising that only work for read-only operation. When you try to add new record it would fail because the sequence would be something like "schema.tablename"_column_id_seq.
db_table = 'schema\".\"tablename'
does work so far. Thanks.
|
Iterate over a string 2 (or n) characters at a time in Python
|
Earlier today I needed to iterate over a string 2 characters at a time for parsing a string formatted like "+c-R+D-E" (there are a few extra letters).
I ended up with this, which works, but it looks ugly. I ended up commenting what it was doing because it felt non-obvious. It almost seems pythonic, but not quite.
# Might not be exact, but you get the idea, use the step
# parameter of range() and slicing to grab 2 chars at a time
s = "+c-R+D-e"
for op, code in (s[i:i+2] for i in range(0, len(s), 2)):
print op, code
Are there some better/cleaner ways to do this?
|
Dunno about cleaner, but there's another alternative:
for (op, code) in zip(s[0::2], s[1::2]):
print op, code
A no-copy version:
from itertools import izip, islice
for (op, code) in izip(islice(s, 0, None, 2), islice(s, 1, None, 2)):
print op, code
|
Reading integers from binary file in Python
|
I'm trying to read a BMP file in Python. I know the first two bytes
indicate the BMP firm. The next 4 bytes are the file size. When I excecute:
fin = open("hi.bmp", "rb")
firm = fin.read(2)
file_size = int(fin.read(4))
I get
ValueError: invalid literal for int() with base 10: 'F#\x13'
What I want to do is reading those four bytes as an integer... It seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly?
|
The read method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in struct module: http://docs.python.org/library/struct.html.
import struct
print(struct.unpack('i', fin.read(4)))
Note that unpack always returns a tuple, so struct.unpack('i', fin.read(4))[0] gives the integer value that you are after.
You should probably use the format string '<i' (< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.
|
fast-ish python/jython IPC?
|
All I want to do is make some RPC calls over sockets. I have a server that does backendish stuff running jython 2.5. I need to make some calls from a frontend server running Django on CPython. I've been beating my head against a wall getting any form of IPC going.
The list of things I've tried:
Apache Thrift doesn't have any actual releases, just snapshots. I'd like to use something stable.
JSON-RPC is interesting, and it should be able to run over sockets, but in practice most of the implementations only seem to work over HTTP. HTTP overhead is exactly what I'm trying to avoid.
Protocol Buffers is really only a serialization protocol. From what I gather protobuf provides interface generation for RPC, but it's only the interface. Actually writing all the connection code is up to the user. If I'm going to be stuck using sockets, I'll just use JSON for serialization. It's simpler and faster.
Pyro doesn't work properly with Jython as a server. Some sort of socket timeout issue. I've sent a message to the mailing list.
pysage Yay for message passing! Only it requires python 2.6 or the processing module (which has compiled extensions). Jython is version 2.5 and doesn't allow compiled extensions. Shit.
Candygram is an interesting alternative to pysage, but as far as I can tell it's unmaintained. I haven't even tried it out with Jython. Any experiences with it?
Twisted Perspective Broker Twisted doesn't work on Jython.
I know that it'd be a snap doing this with XML-RPC, which makes me even more cranky. I want to avoid the overhead of HTTP, but at the same time I really don't want to get down and dirty with sockets to implement my own protocol. I'll do it wrong if I do.
Any ideas? I'm probably going to cry for about 20 minutes and then just use XML-RPC.
|
Have you considered Hessian? From the blurb:
The Hessian binary web service
protocol makes web services usable
without requiring a large framework,
and without learning yet another
alphabet soup of protocols. Because it
is a binary protocol, it is
well-suited to sending binary data
without any need to extend the
protocol with attachments.
It has Python client and Java server (and more besides).
Update: If you're dead against HTTP, why not just use SocketServer and pickle? Not much of a protocol needed, hard to get wrong. Send / receive pickled strings with length prefixes.
|
Image resizing with django?
|
I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:
from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:
from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.
Thank you!
|
If it's OK for you, there is a Django application ready, doing exactly what you want:
https://github.com/sorl/sorl-thumbnail
|
Calculate difference in keys contained in two Python dictionaries
|
Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not in dictA. What is the fastest way to go about it?
Should I convert the dictionary keys into a set and then go about?
Interested in knowing your thoughts...
Thanks for your responses.
Apologies for not stating my question properly.
My scenario is like this - I have a dictA which can be the same as dictB or may have some keys missing as compared to dictB or else the value of some keys might be different which has to be set to that of dictA key's value.
Problem is the dictionary has no standard and can have values which can be dict of dict.
Say
dictA={'key1':a, 'key2':b, 'key3':{'key11':cc, 'key12':dd}, 'key4':{'key111':{....}}}
dictB={'key1':a, 'key2:':newb, 'key3':{'key11':cc, 'key12':newdd, 'key13':ee}.......
So 'key2' value has to be reset to the new value and 'key13' has to be added inside the dict.
The key value does not have a fixed format. It can be a simple value or a dict or a dict of dict.
|
You can use set operations on the keys:
diff = set(dictb.keys()) - set(dicta.keys())
Here is a class to find all the possibilities: what was added, what was removed, which key-value pairs are the same, and which key-value pairs are changed.
class DictDiffer(object):
"""
Calculate the difference between two dictionaries as:
(1) items added
(2) items removed
(3) keys same in both but changed values
(4) keys same in both and unchanged values
"""
def __init__(self, current_dict, past_dict):
self.current_dict, self.past_dict = current_dict, past_dict
self.set_current, self.set_past = set(current_dict.keys()), set(past_dict.keys())
self.intersect = self.set_current.intersection(self.set_past)
def added(self):
return self.set_current - self.intersect
def removed(self):
return self.set_past - self.intersect
def changed(self):
return set(o for o in self.intersect if self.past_dict[o] != self.current_dict[o])
def unchanged(self):
return set(o for o in self.intersect if self.past_dict[o] == self.current_dict[o])
Here is some sample output:
>>> a = {'a': 1, 'b': 1, 'c': 0}
>>> b = {'a': 1, 'b': 2, 'd': 0}
>>> d = DictDiffer(b, a)
>>> print "Added:", d.added()
Added: set(['d'])
>>> print "Removed:", d.removed()
Removed: set(['c'])
>>> print "Changed:", d.changed()
Changed: set(['b'])
>>> print "Unchanged:", d.unchanged()
Unchanged: set(['a'])
Available as a github repo:
https://github.com/hughdbrown/dictdiffer
|
How to strip decorators from a function in python
|
Let's say I have the following:
def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
return decorated
@with_connection
def spam(connection):
# Do something
I want to test the spam function without going through the hassle of setting up a connection (or whatever the decorator is doing).
Given spam, how do I strip the decorator from it and get the underlying "undecorated" function?
|
In the general case, you can't, because
@with_connection
def spam(connection):
# Do something
is equivalent to
def spam(connection):
# Do something
spam = with_connection(spam)
which means that the "original" spam might not even exist anymore. A (not too pretty) hack would be this:
def with_connection(f):
def decorated(*args, **kwargs):
f(get_connection(...), *args, **kwargs)
decorated._original = f
return decorated
@with_connection
def spam(connection):
# Do something
spam._original(testcon) # calls the undecorated function
|
Python: access class property from string
|
I have a class like the following:
class User:
def __init__(self):
self.data = []
self.other_data = []
def doSomething(self, source):
// if source = 'other_data' how to access self.other_data
I want to pass a string for the source variable in doSomething and access the class member of the same name.
I have tried getattr which only works on functions (from what I can tell) as well as having User extend dict and using self.__getitem__, but that doesn't work either. What is the best way to do this?
|
x = getattr(self, source) will work just perfectly if source names ANY attribute of self, include the other_data in your example.
|
In Python, how do I indicate I'm overriding a method?
|
In Java, for example, the @Override annotation not only provides compile-time checking of an override but makes for excellent self-documenting code. I'm just looking for documentation (although if it's an indicator to some checker like pylint, that's a bonus). I can add a comment or docstring somewhere, but what is the idiomatic way to indicate an override in Python?
|
UPDATE (23.05.2015): Based on this and fwc:s answer I created a pip installable package https://github.com/mkorpela/overrides
From time to time I end up here looking at this question.
Mainly this happens after (again) seeing the same bug in our code base: Someone has forgotten some "interface" implementing class while renaming a method in the "interface"..
Well Python ain't Java but Python has power -- and explicit is better than implicit -- and there are real concrete cases in the real world where this thing would have helped me.
So here is a sketch of overrides decorator. This will check that the class given as a parameter has the same method (or something) name as the method being decorated.
If you can think of a better solution please post it here!
def overrides(interface_class):
def overrider(method):
assert(method.__name__ in dir(interface_class))
return method
return overrider
It works as follows:
class MySuperInterface(object):
def my_method(self):
print 'hello world!'
class ConcreteImplementer(MySuperInterface):
@overrides(MySuperInterface)
def my_method(self):
print 'hello kitty!'
and if you do a faulty version it will raise an assertion error during class loading:
class ConcreteFaultyImplementer(MySuperInterface):
@overrides(MySuperInterface)
def your_method(self):
print 'bye bye!'
>> AssertionError!!!!!!!
|
IronPython vs. Python .NET
|
I want to access some .NET assemblies written in C# from Python code.
A little research showed I have two choices:
IronPython with .NET interface capability/support built-in
Python with the Python .NET package
What are the trade-offs between both solutions?
|
If you want to mainly base your code on the .NET framework, I'd highly recommend IronPython vs Python.NET. IronPython is pretty much native .NET - so it just works great when integrating with other .NET langauges.
Python.NET is good if you want to just integrate one or two components from .NET into a standard python application.
There are notable differences when using IronPython - but most of them are fairly subtle. Python.NET uses the standard CPython runtime, so this Wiki page is a relevant discussion of the differences between the two implementations. The largest differences occur in the cost of exceptions - so some of the standard python libraries don't perform as well in IronPython due to their implementation.
|
Python 2 CSV writer produces wrong line terminator on Windows
|
According to the its documentation csv.writer should use '\r\n' as lineterminator by default.
import csv
with open("test.csv", "w") as f:
writer = csv.writer(f)
rows = [(0,1,2,3,4),
(-0,-1,-2,-3,-4),
("a","b","c","d","e"),
("A","B","C","D","E")]
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
writer.writerows(rows)
print writer.dialect.lineterminator.replace("\r", "\\r").replace("\n", "\\n")
This prints
\r\n
\r\n
as expected. But, the created csv-file uses the lineterminator '\r\r\n'
0,1,2,3,4
0,-1,-2,-3,-4
a,b,c,d,e
A,B,C,D,E
Is this a bug or is there something wrong in my usage of csv.writer?
Python version:
ActivePython 2.6.2.2 (ActiveState
Software Inc.) based on Python 2.6.2
(r262:71600, Apr 21 2009, 15:05:37)
[MSC v.1500 32 bit (Intel)] on win32
on Windows Vista
|
In Python 2.x, always open your file in binary mode, as documented. csv writes \r\n as you expected, but then the underlying Windows text file mechanism cuts in and changes that \n to \r\n ... total effect: \r\r\n
From the csv.writer documentation:
If csvfile is a file object, it must be opened with the 'b' flag on platforms where that makes a difference.
There seems to be some reticence about actually uttering the name of the main culprit :-)
|
How to create an optimized packing function in python?
|
So I have been given the task to create a shipping module for a webshop system. It may be a bit overkill, but I would really like to create one that can figure out how to pack parcels in the most optimized way. Having learned programming simply by doing it, this is an area where I have no knowledge - yet! Anyways I can just give short description of the actual problem.
So when users by stuff at webshops they will have x products in their cart with possibly varying sizes and weight. So I want to give that list of products to the function and let it figure out how these products should be packed in parcel(s).
max length of parcel: 100
max width of parcel: 50
max height of parcel: 50
max weight of parcel: 20
Every product has a weight, length, width and height as well.
Since parcels and products is basically boxes, I'm guessing this would be rather complex, as there are different ways of putting the products inside the parcel. My goal is not to make the perfect packaging function, but I would like to do something better than just putting products inside the parcel until a limit has been reached.
Now, I don't expect you guys to make this for me, but what I would like to ask is three things.
Where can I find good online resources that will teach me the basics needed?
Are there some native python tools that would be good to use?
Some pointers of what I need to be aware of, pitfalls etc
Like I said, I don't plan for this to be perfect and 100% optimized, but I would like to end up with something that will come close. I would hate if users feel that the sending fee will be a lot higher than it actual is.
|
Thatâs your typical knapsack problem. Many solutions for different languages can be found at Rosetta Code.
|
How do I get urllib2 to log ALL transferred bytes
|
I'm writing a web-app that uses several 3rd party web APIs, and I want to keep track of the low level request and responses for ad-hock analysis. So I'm looking for a recipe that will get Python's urllib2 to log all bytes transferred via HTTP. Maybe a sub-classed Handler?
|
Well, I've found how to setup the built-in debugging mechanism of the library:
import logging, urllib2, sys
hh = urllib2.HTTPHandler()
hsh = urllib2.HTTPSHandler()
hh.set_http_debuglevel(1)
hsh.set_http_debuglevel(1)
opener = urllib2.build_opener(hh, hsh)
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.NOTSET)
But I'm still looking for a way to dump all the information transferred.
|
How can I profile a SQLAlchemy powered application?
|
Does anyone have experience profiling a Python/SQLAlchemy app? And what are the best way to find bottlenecks and design flaws?
We have a Python application where the database layer is handled by SQLAlchemy. The application uses a batch design, so a lot of database requests is done sequentially and in a limited timespan. It currently takes a bit too long to run, so some optimization is needed. We don't use the ORM functionality, and the database is PostgreSQL.
|
Sometimes just plain SQL logging (enabled via python's logging module or via the echo=True argument on create_engine()) can give you an idea how long things are taking. For example if you log something right after a SQL operation, you'd see something like this in your log:
17:37:48,325 INFO [sqlalchemy.engine.base.Engine.0x...048c] SELECT ...
17:37:48,326 INFO [sqlalchemy.engine.base.Engine.0x...048c] {<params>}
17:37:48,660 DEBUG [myapp.somemessage]
if you logged myapp.somemessage right after the operation, you know it took 334ms to complete the SQL part of things.
Logging SQL will also illustrate if dozens/hundreds of queries are being issued which could be better organized into much fewer queries via joins. When using the SQLAlchemy ORM, the "eager loading" feature is provided to partially (contains_eager()) or fully (eagerload(), eagerload_all()) automate this activity, but without the ORM it just means to use joins so that results across multiple tables can be loaded in one result set instead of multiplying numbers of queries as more depth is added (i.e. r + r*r2 + r*r2*r3 ...)
If logging reveals that individual queries are taking too long, you'd need a breakdown of how much time was spent within the database processing the query, sending results over the network, being handled by the DBAPI, and finally being received by SQLAlchemy's result set and/or ORM layer. Each of these stages can present their own individual bottlenecks, depending on specifics.
For that you need to use profiling, such as cProfile or hotshot. Here is a decorator I use:
import cProfile as profiler
import gc, pstats, time
def profile(fn):
def wrapper(*args, **kw):
elapsed, stat_loader, result = _profile("foo.txt", fn, *args, **kw)
stats = stat_loader()
stats.sort_stats('cumulative')
stats.print_stats()
# uncomment this to see who's calling what
# stats.print_callers()
return result
return wrapper
def _profile(filename, fn, *args, **kw):
load_stats = lambda: pstats.Stats(filename)
gc.collect()
began = time.time()
profiler.runctx('result = fn(*args, **kw)', globals(), locals(),
filename=filename)
ended = time.time()
return ended - began, load_stats, locals()['result']
To profile a section of code, place it in a function with the decorator:
@profile
def go():
return Session.query(FooClass).filter(FooClass.somevalue==8).all()
myfoos = go()
The output of profiling can be used to give an idea where time is being spent. If for example you see all the time being spent within cursor.execute(), that's the low level DBAPI call to the database, and it means your query should be optimized, either by adding indexes or restructuring the query and/or underlying schema. For that task I would recommend using pgadmin along with its graphical EXPLAIN utility to see what kind of work the query is doing.
If you see many thousands of calls related to fetching rows, it may mean your query is returning more rows than expected - a cartesian product as a result of an incomplete join can cause this issue. Yet another issue is time spent within type handling - a SQLAlchemy type such as Unicode will perform string encoding/decoding on bind parameters and result columns, which may not be needed in all cases.
The output of a profile can be a little daunting but after some practice they are very easy to read. There was once someone on the mailing list claiming slowness, and after having him post the results of profile, I was able to demonstrate that the speed problems were due to network latency - the time spent within cursor.execute() as well as all Python methods was very fast, whereas the majority of time was spent on socket.receive().
If you're feeling ambitious, there's also a more involved example of SQLAlchemy profiling within the SQLAlchemy unit tests, if you poke around http://www.sqlalchemy.org/trac/browser/sqlalchemy/trunk/test/aaa_profiling . There, we have tests using decorators that assert a maximum number of method calls being used for particular operations, so that if something inefficient gets checked in, the tests will reveal it (it is important to note that in Python, function calls have the highest overhead of any operation, and the count of calls is more often than not nearly proportional to time spent). Of note are the the "zoomark" tests which use a fancy "SQL capturing" scheme which cuts out the overhead of the DBAPI from the equation - although that technique isn't really necessary for garden-variety profiling.
|
How can I parse JSON in Google App Engine?
|
I'd like to parse a JSON string into an object under Google App Engine (python). What do you recommend? Something to encode/stringify would be nice too. Is what you recommend built in, or a library that I have to include in my app? Is it secure? Thanks.
|
Consider using Django's json lib, which is included with GAE.
from django.utils import simplejson as json
# load the object from a string
obj = json.loads( string )
The link above has examples of Django's serializer, and here's the link for simplejson's documentation.
If you're looking at storing Python class instances or objects (as opposed to compositions of lists, strings, numbers, and dictionaries), you probably want to look at pickle.
I hope that helps.
Incidentally, to get Django 1.0 (instead of Django 0.96) running on GAE, you can use the following call in your main.py, per this article:
from google.appengine.dist import use_library
use_library('django', '1.0')
Edit: Native JSON support in Google App Engine 1.6.0 with Python 2.7
As of Google App Engine 1.6.0, you can use the Python 2.7 runtime by adding runtime: python27 in app.yaml, and then you can import the native JSON library with import json.
|
Connecting to APNS for iPhone Using Python
|
I'm trying to send push notifications to an iPhone using Python. I've exported my certificate and private key into a p12 file from keychain access and then converted it into pem file using the following command:
openssl pkcs12 -in cred.p12 -out cert.pem -nodes -clcerts
I'm using APNSWrapper in Python for the connection.
I run the following code:
deviceToken = 'Qun\xaa\xd ... c0\x9c\xf6\xca'
# create wrapper
wrapper = APNSNotificationWrapper('/path/to/cert/cert.pem', True)
# create message
message = APNSNotification()
message.token(deviceToken)
message.badge(5)
# add message to tuple and send it to APNS server
wrapper.append(message)
wrapper.notify()
And then I get the error message:
ssl.SSLError: (1, '_ssl.c:485:
error:14094416:SSL routines:SSL3_READ_BYTES:sslv3 alert certificate unknown')
Can anyone help me out on this?
|
I recently did this using Django - http://leecutsco.de/2009/07/14/push-on-the-iphone/
May be useful? It's making use of no extra libraries other than those included with Python already. Wouldn't take much to extract the send_message() method out.
|
What is a basic example of single inheritance using the super() keyword in Python?
|
Let's say I have the following classes set up:
class Foo:
def __init__(self, frob, frotz):
self.frobnicate = frob
self.frotz = frotz
class Bar:
def __init__(self, frob, frizzle):
self.frobnicate = frob
self.frotz = 34
self.frazzle = frizzle
How can I (if I can at all) use super() in this context to eliminate the duplicate code?
|
Assuming you want class Bar to set the value 34 within its constructor, this would work:
class Foo(object):
def __init__(self, frob, frotz):
self.frobnicate = frob
self.frotz = frotz
class Bar(Foo):
def __init__(self, frob, frizzle):
super(Bar, self).__init__(frob, frizzle)
self.frotz = 34
self.frazzle = frizzle
bar = Bar(1,2)
print "frobnicate:", bar.frobnicate
print "frotz:", bar.frotz
print "frazzle:", bar.frazzle
However, super introduces its own complications. See e.g. super considered harmful. For completeness, here's the equivalent version without super.
class Foo(object):
def __init__(self, frob, frotz):
self.frobnicate = frob
self.frotz = frotz
class Bar(Foo):
def __init__(self, frob, frizzle):
Foo.__init__(self, frob, frizzle)
self.frotz = 34
self.frazzle = frizzle
bar = Bar(1,2)
print "frobnicate:", bar.frobnicate
print "frotz:", bar.frotz
print "frazzle:", bar.frazzle
|
How to efficiently calculate a running standard deviation?
|
I have an array of lists of numbers, e.g.:
[0] (0.01, 0.01, 0.02, 0.04, 0.03)
[1] (0.00, 0.02, 0.02, 0.03, 0.02)
[2] (0.01, 0.02, 0.02, 0.03, 0.02)
...
[n] (0.01, 0.00, 0.01, 0.05, 0.03)
What I would like to do is efficiently calculate the mean and standard deviation at each index of a list, across all array elements.
To do the mean, I have been looping through the array and summing the value at a given index of a list. At the end, I divide each value in my "averages list" by n.
To do the standard deviation, I loop through again, now that I have the mean calculated.
I would like to avoid going through the array twice, once for the mean and then once for the SD (after I have a mean).
Is there an efficient method for calculating both values, only going through the array once? Any code in an interpreted language (e.g. Perl or Python) or pseudocode is fine.
|
The answer is to use Welford's algorithm, which is very clearly defined after the "naive methods" in:
Wikipedia: Algorithms for calculating variance
It's more numerically stable than either the two-pass or online simple sum of squares collectors suggested in other responses. The stability only really matters when you have lots of values that are close to each other as they lead to what is known as "catastrophic cancellation" in the floating point literature.
You might also want to brush up on the difference between dividing by the number of samples (N) and N-1 in the variance calculation (squared deviation). Dividing by N-1 leads to an unbiased estimate of variance from the sample, whereas dividing by N on average underestimates variance (because it doesn't take into account the variance between the sample mean and the true mean).
I wrote two blog entries on the topic which go into more details, including how to delete previous values online:
Computing Sample Mean and Variance Online in One Pass
Deleting Values in Welfordâs Algorithm for Online Mean and Variance
You can also take a look at my Java implement; the javadoc, source, and unit tests are all online:
Javadoc: stats.OnlineNormalEstimator
Source: stats.OnlineNormalEstimator.java
JUnit Source: test.unit.stats.OnlineNormalEstimatorTest.java
LingPipe Home Page
|
Elegant Python function to convert CamelCase to snake_case?
|
Example:
>>> convert('CamelCase')
'camel_case'
|
This is pretty thorough:
def convert(name):
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
Works with all these (and doesn't harm already-un-cameled versions):
>>> convert('CamelCase')
'camel_case'
>>> convert('CamelCamelCase')
'camel_camel_case'
>>> convert('Camel2Camel2Case')
'camel2_camel2_case'
>>> convert('getHTTPResponseCode')
'get_http_response_code'
>>> convert('get2HTTPResponseCode')
'get2_http_response_code'
>>> convert('HTTPResponseCode')
'http_response_code'
>>> convert('HTTPResponseCodeXYZ')
'http_response_code_xyz'
Or if you're going to call it a zillion times, you can pre-compile the regexes:
first_cap_re = re.compile('(.)([A-Z][a-z]+)')
all_cap_re = re.compile('([a-z0-9])([A-Z])')
def convert(name):
s1 = first_cap_re.sub(r'\1_\2', name)
return all_cap_re.sub(r'\1_\2', s1).lower()
Don't forget to import the regular expression module
import re
|
Convert string to Python class object?
|
Given a string as user input to a python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:
class Foo:
pass
str_to_class("Foo")
==> <class __main__.Foo at 0x69ba0>
Is this possible?
|
This could work:
import sys
def str_to_class(str):
return getattr(sys.modules[__name__], str)
|
How to filter files (with known type) from os.walk?
|
I have list from os.walk. But I want to exclude some directories and files. I know how to do it with directories:
for root, dirs, files in os.walk('C:/My_files/test'):
if "Update" in dirs:
dirs.remove("Update")
But how can I do it with files, which type I know. because this doesn't work:
if "*.dat" in files:
files.remove("*.dat")
|
files = [ fi for fi in files if not fi.endswith(".dat") ]
|
Decoding double encoded utf8 in Python
|
I've got a problem with strings that I get from one of my clients over xmlrpc. He sends me utf8 strings that are encoded twice :( so when I get them in python I have an unicode object that has to be decoded one more time, but obviously python doesn't allow that. I've noticed my client however I need to do quick workaround for now before he fixes it.
Raw string from tcp dump:
<string>Rafa\xc3\x85\xc2\x82</string>
this is converted into:
u'Rafa\xc5\x82'
The best we get is:
eval(repr(u'Rafa\xc5\x82')[1:]).decode("utf8")
This results in correct string which is:
u'Rafa\u0142'
this works however is ugly as hell and cannot be used in production code.
If anyone knows how to fix this problem in more suitable way please write.
Thanks,
Chris
|
>>> s = u'Rafa\xc5\x82'
>>> s.encode('raw_unicode_escape').decode('utf-8')
u'Rafa\u0142'
>>>
|
Change current process environment's LD_LIBRARY_PATH
|
Is it possible to change environment variables of current process?
More specifically in a python script I want to change LD_LIBRARY_PATH so that on import of a module 'x' which depends on some xyz.so, xyz.so is taken from my given path in LD_LIBRARY_PATH
is there any other way to dynamically change path from where library is loaded?
Edit: I think I need to mention that I have already tried thing like
os.environ["LD_LIBRARY_PATH"] = mypath
os.putenv('LD_LIBRARY_PATH', mypath)
but these modify the env. for spawned sub-process, not the current process, and module loading doesn't consider the new LD_LIBRARY_PATH
Edit2, so question is can we change environment or something so the library loader sees it and loads from there?
|
The reason
os.environ["LD_LIBRARY_PATH"] = ...
doesn't work is simple: this environment variable controls behavior of the dynamic loader (ld-linux.so.2 on Linux, ld.so.1 on Solaris), but the loader only looks at LD_LIBRARY_PATH once at process startup. Changing the value of LD_LIBRARY_PATH in the current process after that point has no effect (just as the answer to this question says).
You do have some options:
A. If you know that you are going to need xyz.so from /some/path, and control the execution of python script from the start, then simply set LD_LIBRARY_PATH to your liking (after checking that it is not already so set), and re-execute yourself. This is what Java does.
B. You can import /some/path/xyz.so via its absolute path before importing x.so. When you then import x.so, the loader will discover that it has already loaded xyz.so, and will use the already loaded module instead of searching for it again.
C. If you build x.so yourself, you can add -Wl,-rpath=/some/path to its link line, and then importing x.so will cause the loader to look for dependent modules in /some/path.
|
In Python 2.4, how can I strip out characters after ';'?
|
Let's say I'm parsing a file, which uses ; as the comment character. I don't want to parse comments. So if I a line looks like this:
example.com. 600 IN MX 8 s1b9.example.net ; hello!
Is there an easier/more-elegant way to strip chars out other than this:
rtr = ''
for line in file:
trig = False
for char in line:
if not trig and char != ';':
rtr += char
else:
trig = True
if rtr[max(rtr)] != '\n':
rtr += '\n'
|
I'd recommend saying
line.split(";")[0]
which will give you a string of all characters up to but not including the first ";" character. If no ";" character is present, then it will give you the entire line.
|
Add text to Existing PDF using Python
|
I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.
Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.
Thanks in advance.
Richard.
Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?
|
I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:
read your PDF using PdfFileReader(), we'll call this input
create a new pdf containing your text to add using ReportLab, save this as a string object
read the string object using PdfFileReader(), we'll call this text
create a new PDF object using PdfFileWriter(), we'll call this output
iterate through input and apply .mergePage(text.getPage(0)) for each page you want the text added to, then use output.addPage() to add the modified pages to a new document
This works well for simple text additions. See PyPDF's sample for watermarking a document.
Here is some code to answer the question below:
packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
<do something with canvas>
can.save()
packet.seek(0)
input = PdfFileReader(packet)
From here you can merge the pages of the input file with another document
|
Activate a virtualenv via fabric as deploy user
|
I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.
def git_pull():
sudo('su deploy')
# here i need to switch to the virtualenv
run('git pull')
I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'
Anybody have an example and explanation of how they have done this?
|
As an update to bitprophet's forecast: With Fabric 1.0 you can make use of prefix() and your own context managers.
from __future__ import with_statement
from fabric.api import *
from contextlib import contextmanager as _contextmanager
env.hosts = ['servername']
env.user = 'deploy'
env.keyfile = ['$HOME/.ssh/deploy_rsa']
env.directory = '/path/to/virtualenvs/project'
env.activate = 'source /path/to/virtualenvs/project/bin/activate'
@_contextmanager
def virtualenv():
with cd(env.directory):
with prefix(env.activate):
yield
def deploy():
with virtualenv():
run('pip freeze')
|
Using subprocess.Popen for Process with Large Output
|
I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
errcode = p.wait()
retval = p.stdout.read()
errmess = p.stderr.read()
if errcode:
log.error('cmd failed <%s>: %s' % (errcode,errmess))
There are comments in the docs that seem to indicate the potential issue. Under wait, there is:
Warning: This will deadlock if the child process generates enough output to a stdout or stderr pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use communicate() to avoid that.
though under communicate, I see:
Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.
So it is unclear to me that I should use either of these if I have a large amount of data. They don't indicate what method I should use in that case.
I do need the return value from the exec and do parse and use both the stdout and stderr.
So what is an equivalent method in Python to exec an external app that is going to have large output?
|
You're doing blocking reads to two files; the first needs to complete before the second starts. If the application writes a lot to stderr, and nothing to stdout, then your process will sit waiting for data on stdout that isn't coming, while the program you're running sits there waiting for the stuff it wrote to stderr to be read (which it never will be--since you're waiting for stdout).
There are a few ways you can fix this.
The simplest is to not intercept stderr; leave stderr=None. Errors will be output to stderr directly. You can't intercept them and display them as part of your own message. For commandline tools, this is often OK. For other apps, it can be a problem.
Another simple approach is to redirect stderr to stdout, so you only have one incoming file: set stderr=STDOUT. This means you can't distinguish regular output from error output. This may or may not be acceptable, depending on how the application writes output.
The complete and complicated way of handling this is select (http://docs.python.org/library/select.html). This lets you read in a non-blocking way: you get data whenever data appears on either stdout or stderr. I'd only recommend this if it's really necessary. This probably doesn't work in Windows.
|
Spoofing the origination IP address of an HTTP request
|
This only needs to work on a single subnet and is not for malicious use.
I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools provide this functionality, but I want to build it into my own.
The tool uses Python's urllib2 for transport. Is it possible to send HTTP requests with spoofed IP addresses for the packets making up the request?
|
This is a misunderstanding of HTTP. The HTTP protocol is based on top of TCP. The TCP protocol relies on a 3 way handshake to initialize requests.
Needless to say, if you spoof your originating IP address, you will never get past the synchronization stage and no HTTP information will be sent (the server can't send it to a legal host).
If you need to test an IP load balancer, this is not the way to do it.
|
Controlling mouse with Python
|
How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?
|
Tested on WinXP, Python 2.6 after installing pywin32 (pywin32-214.win32-py2.6.exe in my case):
import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)
|
Python base 36 encoding
|
How can I encode an integer with base 36 in Python and then decode it again?
|
I wish I had read this before. Here is the answer:
def base36encode(number):
if not isinstance(number, (int, long)):
raise TypeError('number must be an integer')
if number < 0:
raise ValueError('number must be positive')
alphabet, base36 = ['0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', '']
while number:
number, i = divmod(number, 36)
base36 = alphabet[i] + base36
return base36 or alphabet[0]
def base36decode(number):
return int(number, 36)
print(base36encode(1412823931503067241))
print(base36decode('AQF8AA0006EH'))
|
Python: Multicore processing?
|
I've been reading about Python's multiprocessing module. I still don't think I have a very good understanding of what it can do.
Let's say I have a quadcore processor and I have a list with 1,000,000 integers and I want the sum of all the integers. I could simply do:
list_sum = sum(my_list)
But this only sends it to one core.
Is it possible, using the multiprocessing module, to divide the array up and have each core get the sum of it's part and return the value so the total sum may be computed?
Something like:
core1_sum = sum(my_list[0:500000]) #goes to core 1
core2_sum = sum(my_list[500001:1000000]) #goes to core 2
all_core_sum = core1_sum + core2_sum #core 3 does final computation
Any help would be appreciated.
|
Yes, it's possible to do this summation over several processes, very much like doing it with multiple threads:
from multiprocessing import Process, Queue
def do_sum(q,l):
q.put(sum(l))
def main():
my_list = range(1000000)
q = Queue()
p1 = Process(target=do_sum, args=(q,my_list[:500000]))
p2 = Process(target=do_sum, args=(q,my_list[500000:]))
p1.start()
p2.start()
r1 = q.get()
r2 = q.get()
print r1+r2
if __name__=='__main__':
main()
However, it is likely that doing it with multiple processes is likely slower than doing it in a single process, as copying the data forth and back is more expensive than summing them right away.
|
Unbuffered read from process using subprocess in Python
|
I am trying to read from a process that produces long and time-consuming output. However, I want to catch it's output as and when it is produced. But using something like the following seems to be buffering the command's output, so I end up getting the output lines all at once:
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, bufsize=0)
for line in p.stdout:
print line
I am trying this on MacOS 10.5
|
The file iterator is doing some internal buffering on its own. Try this:
line = p.stdout.readline()
while line:
print line
line = p.stdout.readline()
|
Python Properties & Swig
|
I am attempting to create python bindings for some C++ code using swig. I seem have run into a problem trying to create python properties from some accessor functions I have for methods like the following:
class Player {
public:
void entity(Entity* entity);
Entity* entity() const;
};
I tried creating a property using the python property function but it seems that the wrapper classes swig generates are not compatible with it at least for setters.
How do you create properties using swig?
|
There is an easy way to make python properties from methods with swig.
Suppose C++ code Example.h:
C++ header
class Example{
public:
void SetX(int x);
int GetX() const;
};
Lets convert this setter and getter to python propery 'x'. The trick is in .i file. We add some "swiggy" inline python code (with %pythoncode) that is inserted in a body of a resulting python class (in the auto-generated python code).
Swig wrapping Example.i
%module example
%{
#include "example.h"
%}
class Example{
public:
void SetX(int x);
int GetX() const;
%pythoncode %{
__swig_getmethods__["x"] = GetX
__swig_setmethods__["x"] = SetX
if _newclass: x = property(GetX, SetX)
%}
};
Check the python code:
python test code
import example
test = example.Example()
test.x = 5
print "Ha ha ha! It works! X = ", repr(test.x)
That is it!
Make it simplier!
There is no need to rewrite a class definition. Thanks to Joshua advice, one could use SWIG directive %extend ClassName { }.
Swig wrapping Example.i
%module example
%{
#include "example.h"
%}
%extend Example{
%pythoncode %{
__swig_getmethods__["x"] = GetX
__swig_setmethods__["x"] = SetX
if _newclass: x = property(GetX, SetX)
%}
};
Hiding setter and getter functions
As one may see, test.GetX() and test.SetX() are still in place after conversion. One can hide them by:
a) Rename functions by using %rename, add '_' in the beginning thus making methods "private" for python. In the a SWIG interface .i
Example.i
...
class Example{
%rename(_SetX) SetX(int);
%rename(_GetX) GetX();
...
(%rename may be placed in some separated place to save the possibility to convert this class to other languages, which don't need these '_')
b) or one can play with %feature("shadow")
Why is it so?
Why do we have to use such things to convert methods to a property by using SWIG?
As it was said, SWIG selfishly overrides _setattr_, so one have to use _swig_getmethods_ and _swig_setmethods_ to register functions and stay in the swig way.
Why may one prefer this way?
The methods listed above, especially with PropertyVoodoo are... It is like burning the house to fry an egg. Also it breaks the classes layout, as one have to create inherited classes to make python properties from C++ methods. I mean if class Cow returns class Milk and the inherited class is MilkWithProperties(Milk), how to make Cow to produce MilkWithProperties?
This approach allows one to:
explicitly control what C++ methods to convert to python properties
conversion rules are located in swig interface(*.i) files, the place where they are supposed to be
one resulting autogenerated .py file
stay in the swig syntax of insertions in swig generated .py file
%pythoncode is ignored if one wraps library to other languages
Update
In a newer version SWIG abandoned _swig_property so just use property. It works with old version of swig the same. I've changed the post.
|
Creating child frames of main frame in wxPython
|
I am trying create a new frame in wxPython that is a child of the main frame so that when the main frame is closed, the child frame will also be closed.
Here is a simplified example of the problem that I am having:
#! /usr/bin/env python
import wx
class App(wx.App):
def OnInit(self):
frame = MainFrame()
frame.Show()
self.SetTopWindow(frame)
return True
class MainFrame(wx.Frame):
title = "Main Frame"
def __init__(self):
wx.Frame.__init__(self, None, 1, self.title) #id = 5
menuFile = wx.Menu()
menuAbout = wx.Menu()
menuAbout.Append(2, "&About...", "About this program")
menuBar = wx.MenuBar()
menuBar.Append(menuAbout, "&Help")
self.SetMenuBar(menuBar)
self.CreateStatusBar()
self.Bind(wx.EVT_MENU, self.OnAbout, id=2)
def OnQuit(self, event):
self.Close()
def OnAbout(self, event):
AboutFrame().Show()
class AboutFrame(wx.Frame):
title = "About this program"
def __init__(self):
wx.Frame.__init__(self, 1, -1, self.title) #trying to set parent=1 (id of MainFrame())
if __name__ == '__main__':
app = App(False)
app.MainLoop()
If I set AboutFrame's parent frame to None (on line 48) then the About frame is succesfully created and displayed but it stays open when the main frame is closed.
Is this the approach that I should be taking to create child frames of the main frame or should I be doing it differently, eg. using the onClose event of the main frame to close any child frames (this way sounds very 'hackish').
If I am taking the correct approach, why is it not working?
|
class AboutFrame(wx.Frame):
title = "About this program"
def __init__(self):
wx.Frame.__init__(self, wx.GetApp().TopWindow, title=self.title)
|
Algorithms to identify Markov generated content?
|
Markov chains are a (almost standard) way to generate random gibberish which looks intelligent to untrained eye. How would you go about identifying markov generated text from human written text.
It would be awesome if the resources you point to are Python friendly.
|
One simple approach would be to have a large group of humans read input text for you and see if the text makes sense. I'm only half-joking, this is a tricky problem.
I believe this to be a hard problem, because Markov-chain generated text is going to have a lot of the same properties of real human text in terms of word frequency and simple relationships between the ordering of words.
The differences between real text and text generated by a Markov chain are in higher-level rules of grammar and in semantic meaning, which are hard to encode programmatically. The other problem is that Markov chains are good enough at generating text that they sometimes come up with grammatically and semantically correct statements.
As an example, here's an aphorism from the kantmachine:
Today, he would feel convinced that
the human will is free; to-morrow,
considering the indissoluble chain of
nature, he would look on freedom as a
mere illusion and declare nature to be
all-in-all.
While this string was written by a computer program, it's hard to say that a human would never say this.
I think that unless you can give us more specific details about the computer and human-generated text that expose more obvious differences it will be difficult to solve this using computer programming.
|
How to trim whitespace (including tabs)?
|
Is there a function that will trim not only spaces for whitespace, but also tabs?
|
Whitespace on the both sides:
s = " \t a string example\t "
s = s.strip()
Whitespace on the right side:
s = s.rstrip()
Whitespace on the left side:
s = s.lstrip()
As thedz points out, you can provide an argument to strip arbitrary characters to any of these functions like this:
s = s.strip(' \t\n\r')
This will strip any space, \t, \n, or \r characters from the left-hand side, right-hand side, or both sides of the string.
The examples above only remove strings from the left-hand and right-hand sides of strings. If you want to also remove characters from the middle of a string, try re.sub:
import re
print re.sub('[\s+]', '', s)
That should print out:
astringexample
|
Python loop counter in a for loop
|
In my example code below, is the counter = 0 really required, or is there a better, more Python, way to get access to a loop counter? I saw a few PEPs related to loop counters, but they were either deferred or rejected (PEP 212 and PEP 281).
This is a simplified example of my problem. In my real application this is done with graphics and the whole menu has to be repainted each frame. But this demonstrates it in a simple text way that is easy to reproduce.
Maybe I should also add that I'm using Python 2.5, although I'm still interested if there is a way specific to 2.6 or higher.
# Draw all the options, but highlight the selected index
def draw_menu(options, selected_index):
counter = 0
for option in options:
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
counter += 1
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(option, 2) # Draw menu with "Option2" selected
When run, it outputs:
[ ] Option 0
[ ] Option 1
[*] Option 2
[ ] Option 3
|
Use enumerate() like so:
def draw_menu(options, selected_index):
for counter, option in enumerate(options):
if counter == selected_index:
print " [*] %s" % option
else:
print " [ ] %s" % option
options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)
Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.
|
How do I define a unique property for a Model in Google App Engine?
|
I need some properties to be unique. How can I achieve this?
Is there something like unique=True?
I'm using Google App Engine for Python.
|
Google has provided function to do that:
http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_or_insert
Model.get_or_insert(key_name, **kwds)
Attempts to get the entity of the model's kind with the given key name. If it exists, get_or_insert() simply returns it. If it doesn't exist, a new entity with the given kind, name, and parameters in kwds is created, stored, and returned.
The get and subsequent (possible) put are wrapped in a transaction to ensure atomicity. Ths means that get_or_insert() will never overwrite an existing entity, and will insert a new entity if and only if no entity with the given kind and name exists.
In other words, get_or_insert() is equivalent to this Python code:
def txn():
entity = MyModel.get_by_key_name(key_name, parent=kwds.get('parent'))
if entity is None:
entity = MyModel(key_name=key_name, **kwds)
entity.put()
return entity
return db.run_in_transaction(txn)
Arguments:
key_name
The name for the key of the entity
**kwds
Keyword arguments to pass to the model class's constructor if an instance with the specified key name doesn't exist. The parent argument is required if the desired entity has a parent.
Note: get_or_insert() does not accept an RPC object.
The method returns an instance of the model class that represents the requested entity, whether it existed or was created by the method. As with all datastore operations, this method can raise a TransactionFailedError if the transaction could not be completed.
|
How to solve the "Mastermind" guessing game?
|
How would you create an algorithm to solve the following puzzle, "Mastermind"?
Your opponent has chosen four different colours from a set of six (yellow, blue, green, red, orange, purple). You must guess which they have chosen, and in what order. After each guess, your opponent tells you how many (but not which) of the colours you guessed were the right colour in the right place ["blacks"] and how many (but not which) were the right colour but in the wrong place ["whites"]. The game ends when you guess correctly (4 blacks, 0 whites).
For example, if your opponent has chosen (blue, green, orange, red), and you guess (yellow, blue, green, red), you will get one "black" (for the red), and two whites (for the blue and green). You would get the same score for guessing (blue, orange, red, purple).
I'm interested in what algorithm you would choose, and (optionally) how you translate that into code (preferably Python). I'm interested in coded solutions that are:
Clear (easily understood)
Concise
Efficient (fast in making a guess)
Effective (least number of guesses to solve the puzzle)
Flexible (can easily answer questions about the algorithm, e.g. what is its worst case?)
General (can be easily adapted to other types of puzzle than Mastermind)
I'm happy with an algorithm that's very effective but not very efficient (provided it's not just poorly implemented!); however, a very efficient and effective algorithm implemented inflexibly and impenetrably is not of use.
I have my own (detailed) solution in Python which I have posted, but this is by no means the only or best approach, so please post more! I'm not expecting an essay ;)
|
Key tools: entropy, greediness, branch-and-bound; Python, generators, itertools, decorate-undecorate pattern
In answering this question, I wanted to build up a language of useful functions to explore the problem. I will go through these functions, describing them and their intent. Originally, these had extensive docs, with small embedded unit tests tested using doctest; I can't praise this methodology highly enough as a brilliant way to implement test-driven-development. However, it does not translate well to StackOverflow, so I will not present it this way.
Firstly, I will be needing several standard modules and future imports (I work with Python 2.6).
from __future__ import division # No need to cast to float when dividing
import collections, itertools, math
I will need a scoring function. Originally, this returned a tuple (blacks, whites), but I found output a little clearer if I used a namedtuple:
Pegs = collections.namedtuple('Pegs', 'black white')
def mastermindScore(g1,g2):
matching = len(set(g1) & set(g2))
blacks = sum(1 for v1, v2 in itertools.izip(g1,g2) if v1 == v2)
return Pegs(blacks, matching-blacks)
To make my solution general, I pass in anything specific to the Mastermind problem as keyword arguments. I have therefore made a function that creates these arguments once, and use the **kwargs syntax to pass it around. This also allows me to easily add new attributes if I need them later. Note that I allow guesses to contain repeats, but constrain the opponent to pick distinct colours; to change this, I only need change G below. (If I wanted to allow repeats in the opponent's secret, I would need to change the scoring function as well.)
def mastermind(colours, holes):
return dict(
G = set(itertools.product(colours,repeat=holes)),
V = set(itertools.permutations(colours, holes)),
score = mastermindScore,
endstates = (Pegs(holes, 0),))
def mediumGame():
return mastermind(("Yellow", "Blue", "Green", "Red", "Orange", "Purple"), 4)
Sometimes I will need to partition a set based on the result of applying a function to each element in the set. For instance, the numbers 1..10 can be partitioned into even and odd numbers by the function n % 2 (odds give 1, evens give 0). The following function returns such a partition, implemented as a map from the result of the function call to the set of elements that gave that result (e.g. { 0: evens, 1: odds }).
def partition(S, func, *args, **kwargs):
partition = collections.defaultdict(set)
for v in S: partition[func(v, *args, **kwargs)].add(v)
return partition
I decided to explore a solver that uses a greedy entropic approach. At each step, it calculates the information that could be obtained from each possible guess, and selects the most informative guess. As the numbers of possibilities grow, this will scale badly (quadratically), but let's give it a try! First, I need a method to calculate the entropy (information) of a set of probabilities. This is just -âp log p. For convenience, however, I will allow input that are not normalized, i.e. do not add up to 1:
def entropy(P):
total = sum(P)
return -sum(p*math.log(p, 2) for p in (v/total for v in P if v))
So how am I going to use this function? Well, for a given set of possibilities, V, and a given guess, g, the information we get from that guess can only come from the scoring function: more specifically, how that scoring function partitions our set of possibilities. We want to make a guess that distinguishes best among the remaining possibilites â divides them into the largest number of small sets â because that means we are much closer to the answer. This is exactly what the entropy function above is putting a number to: a large number of small sets will score higher than a small number of large sets. All we need to do is plumb it in.
def decisionEntropy(V, g, score):
return entropy(collections.Counter(score(gi, g) for gi in V).values())
Of course, at any given step what we will actually have is a set of remaining possibilities, V, and a set of possible guesses we could make, G, and we will need to pick the guess which maximizes the entropy. Additionally, if several guesses have the same entropy, prefer to pick one which could also be a valid solution; this guarantees the approach will terminate. I use the standard python decorate-undecorate pattern together with the built-in max method to do this:
def bestDecision(V, G, score):
return max((decisionEntropy(V, g, score), g in V, g) for g in G)[2]
Now all I need to do is repeatedly call this function until the right result is guessed. I went through a number of implementations of this algorithm until I found one that seemed right. Several of my functions will want to approach this in different ways: some enumerate all possible sequences of decisions (one per guess the opponent may have made), while others are only interested in a single path through the tree (if the opponent has already chosen a secret, and we are just trying to reach the solution). My solution is a "lazy tree", where each part of the tree is a generator that can be evaluated or not, allowing the user to avoid costly calculations they won't need. I also ended up using two more namedtuples, again for clarity of code.
Node = collections.namedtuple('Node', 'decision branches')
Branch = collections.namedtuple('Branch', 'result subtree')
def lazySolutionTree(G, V, score, endstates, **kwargs):
decision = bestDecision(V, G, score)
branches = (Branch(result, None if result in endstates else
lazySolutionTree(G, pV, score=score, endstates=endstates))
for (result, pV) in partition(V, score, decision).iteritems())
yield Node(decision, branches) # Lazy evaluation
The following function evaluates a single path through this tree, based on a supplied scoring function:
def solver(scorer, **kwargs):
lazyTree = lazySolutionTree(**kwargs)
steps = []
while lazyTree is not None:
t = lazyTree.next() # Evaluate node
result = scorer(t.decision)
steps.append((t.decision, result))
subtrees = [b.subtree for b in t.branches if b.result == result]
if len(subtrees) == 0:
raise Exception("No solution possible for given scores")
lazyTree = subtrees[0]
assert(result in endstates)
return steps
This can now be used to build an interactive game of Mastermind where the user scores the computer's guesses. Playing around with this reveals some interesting things. For example, the most informative first guess is of the form (yellow, yellow, blue, green), not (yellow, blue, green, red). Extra information is gained by using exactly half the available colours. This also holds for 6-colour 3-hole Mastermind â (yellow, blue, green) â and 8-colour 5-hole Mastermind â (yellow, yellow, blue, green, red).
But there are still many questions that are not easily answered with an interactive solver. For instance, what is the most number of steps needed by the greedy entropic approach? And how many inputs take this many steps? To make answering these questions easier, I first produce a simple function that turns the lazy tree of above into a set of paths through this tree, i.e. for each possible secret, a list of guesses and scores.
def allSolutions(**kwargs):
def solutions(lazyTree):
return ((((t.decision, b.result),) + solution
for t in lazyTree for b in t.branches
for solution in solutions(b.subtree))
if lazyTree else ((),))
return solutions(lazySolutionTree(**kwargs))
Finding the worst case is a simple matter of finding the longest solution:
def worstCaseSolution(**kwargs):
return max((len(s), s) for s in allSolutions(**kwargs)) [1]
It turns out that this solver will always complete in 5 steps or fewer. Five steps! I know that when I played Mastermind as a child, I often took longer than this. However, since creating this solver and playing around with it, I have greatly improved my technique, and 5 steps is indeed an achievable goal even when you don't have time to calculate the entropically ideal guess at each step ;)
How likely is it that the solver will take 5 steps? Will it ever finish in 1, or 2, steps? To find that out, I created another simple little function that calculates the solution length distribution:
def solutionLengthDistribution(**kwargs):
return collections.Counter(len(s) for s in allSolutions(**kwargs))
For the greedy entropic approach, with repeats allowed: 7 cases take 2 steps; 55 cases take 3 steps; 229 cases take 4 steps; and 69 cases take the maximum of 5 steps.
Of course, there's no guarantee that the greedy entropic approach minimizes the worst-case number of steps. The final part of my general-purpose language is an algorithm that decides whether or not there are any solutions for a given worst-case bound. This will tell us whether greedy entropic is ideal or not. To do this, I adopt a branch-and-bound strategy:
def solutionExists(maxsteps, G, V, score, **kwargs):
if len(V) == 1: return True
partitions = [partition(V, score, g).values() for g in G]
maxSize = max(len(P) for P in partitions) ** (maxsteps - 2)
partitions = (P for P in partitions if max(len(s) for s in P) <= maxSize)
return any(all(solutionExists(maxsteps-1,G,s,score) for l,s in
sorted((-len(s), s) for s in P)) for i,P in
sorted((-entropy(len(s) for s in P), P) for P in partitions))
This is definitely a complex function, so a bit more explanation is in order. The first step is to partition the remaining solutions based on their score after a guess, as before, but this time we don't know what guess we're going to make, so we store all partitions. Now we could just recurse into every one of these, effectively enumerating the entire universe of possible decision trees, but this would take a horrifically long time. Instead I observe that, if at this point there is no partition that divides the remaining solutions into more than n sets, then there can be no such partition at any future step either. If we have k steps left, that means we can distinguish between at most nk-1 solutions before we run out of guesses (on the last step, we must always guess correctly). Thus we can discard any partitions that contain a score mapped to more than this many solutions. This is the next two lines of code.
The final line of code does the recursion, using Python's any and all functions for clarity, and trying the highest-entropy decisions first to hopefully minimize runtime in the positive case. It also recurses into the largest part of the partition first, as this is the most likely to fail quickly if the decision was wrong. Once again, I use the standard decorate-undecorate pattern, this time to wrap Python's sorted function.
def lowerBoundOnWorstCaseSolution(**kwargs):
for steps in itertools.count(1):
if solutionExists(maxsteps=steps, **kwargs):
return steps
By calling solutionExists repeatedly with an increasing number of steps, we get a strict lower bound on the number of steps needed in the worst case for a Mastermind solution: 5 steps. The greedy entropic approach is indeed optimal.
Out of curiosity, I invented another guessing game, which I nicknamed "twoD". In this, you try to guess a pair of numbers; at each step, you get told if your answer is correct, if the numbers you guessed are no less than the corresponding ones in the secret, and if the numbers are no greater.
Comparison = collections.namedtuple('Comparison', 'less greater equal')
def twoDScorer(x, y):
return Comparison(all(r[0] <= r[1] for r in zip(x, y)),
all(r[0] >= r[1] for r in zip(x, y)),
x == y)
def twoD():
G = set(itertools.product(xrange(5), repeat=2))
return dict(G = G, V = G, score = twoDScorer,
endstates = set(Comparison(True, True, True)))
For this game, the greedy entropic approach has a worst case of five steps, but there is a better solution possible with a worst case of four steps, confirming my intuition that myopic greediness is only coincidentally ideal for Mastermind. More importantly, this has shown how flexible my language is: all the same methods work for this new guessing game as did for Mastermind, letting me explore other games with a minimum of extra coding.
What about performance? Obviously, being implemented in Python, this code is not going to be blazingly fast. I've also dropped some possible optimizations in favour of clear code.
One cheap optimization is to observe that, on the first move, most guesses are basically identical: (yellow, blue, green, red) is really no different from (blue, red, green, yellow), or (orange, yellow, red, purple). This greatly reduces the number of guesses we need consider on the first step â otherwise the most costly decision in the game.
However, because of the large runtime growth rate of this problem, I was not able to solve the 8-colour, 5-hole Mastermind problem, even with this optimization. Instead, I ported the algorithms to C++, keeping the general structure the same and employing bitwise operations to boost performance in the critical inner loops, for a speedup of many orders of magnitude. I leave this as an exercise to the reader :)
|
What is the best way to call a Python script from another Python script?
|
I have a script named test1.py which is not in a module. It just has code that should execute when the script itself is run. There are no functions, classes, methods, etc. I have another script which runs as a service. I want to call test1.py from the script running as a service.
For example:
File test1.py
print "I am a test"
print "see! I do nothing productive."
File service.py
# Lots of stuff here
test1.py # do whatever is in test1.py
I'm aware of one method which is opening the file, reading the contents, and basically eval'ing it. I'm assuming there's a better way of doing this. Or at least I hope so.
|
The usual way to do this is something like the following.
test1.py
def some_func():
print 'in test 1, unproductive'
if __name__ == '__main__':
# test1.py executed as script
# do something
some_func()
service.py
import test1
def service_func():
print 'service func'
if __name__ == '__main__':
# service.py executed as script
# do something
service_func()
test1.some_func()
|
Persistent Python Command-Line History
|
I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the readline module which offers functions like: read_history_file, write_history_file, and set_startup_hook. I'm not quite savvy enough to put this into practice though, so could someone please help? My thoughts on the solution are:
(1) Modify .login PYTHONSTARTUP to run a python script.
(2) In that python script file do something like:
def command_history_hook():
import readline
readline.read_history_file('.python_history')
command_history_hook()
(3) Whenever the interpreter exits, write the history to the file. I guess the best way to do this is to define a function in your startup script and exit using that function:
def ex():
import readline
readline.write_history_file('.python_history')
exit()
It's very annoying to have to exit using parentheses, though: ex(). Is there some python sugar that would allow ex (without the parens) to run the ex function?
Is there a better way to cause the history file to write each time? Thanks in advance for all solutions/suggestions.
Also, there are two architectural choices as I can see. One choice is to have a unified command history. The benefit is simplicity (the alternative that follows litters your home directory with a lot of files.) The disadvantage is that interpreters you run in separate terminals will be populated with each other's command histories, and they will overwrite one another's histories. (this is okay for me since I'm usually interested in closing an interpreter and reopening one immediately to reload modules, and in that case that interpreter's commands will have been written to the file.) One possible solution to maintain separate history files per terminal is to write an environment variable for each new terminal you create:
def random_key()
''.join([choice(string.uppercase + string.digits) for i in range(16)])
def command_history_hook():
import readline
key = get_env_variable('command_history_key')
if key:
readline.read_history_file('.python_history_{0}'.format(key))
else:
set_env_variable('command_history_key', random_key())
def ex():
import readline
key = get_env_variable('command_history_key')
if not key:
set_env_variable('command_history_key', random_key())
readline.write_history_file('.python_history_{0}'.format(key))
exit()
By decreasing the random key length from 16 to say 1 you could decrease the number of files littering your directories to 36 at the expense of possible (2.8% chance) of overlap.
|
I think the suggestions in the Python documentation pretty much cover what you want. Look at the example pystartup file toward the end of section 13.3:
http://docs.python.org/tutorial/interactive.html
or see this page:
http://rc98.net/pystartup
But, for an out of the box interactive shell that provides all this and more, take a look at using IPython:
http://ipython.scipy.org/moin/
|
How to exit from Python without traceback?
|
I would like to know how to I exit from Python without having an traceback dump on the output.
I still want want to be able to return an error code but I do not want to display the traceback log.
I want to be able to exit using exit(number) without trace but in case of an Exception (not an exit) I want the trace.
|
You are presumably encountering an exception and the program is exiting because of this (with a traceback). The first thing to do therefore is to catch that exception, before exiting cleanly (maybe with a message, example given).
Try something like this in your main routine:
import sys, traceback
def main():
try:
do main program stuff here
....
except KeyboardInterrupt:
print "Shutdown requested...exiting"
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()
|
How to specify which eth interface Django test server should listen on?
|
As the title says, in a multiple ethernet interfaces with multiple IP environment, the default Django test server is not attached to the network that I can access from my PC. Is there any way to specify the interface which Django test server should use?
-- Added --
The network configuration is here.
I'm connecting to the machine via 143.248.x.y address from my PC. (My PC is also in 143.248.a.b network.) But I cannot find this address. Normal apache works very well as well as other custom daemons running on other ports.
The one who configured this machine is not me, so I don't know much details of the network...
eth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78
inet addr:192.168.6.100 Bcast:192.168.2.255 Mask:255.255.255.0
inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:441917680 errors:0 dropped:0 overruns:0 frame:0
TX packets:357190979 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:191664873035 (178.5 GB) TX bytes:324846526526 (302.5 GB)
eth1 Link encap:Ethernet HWaddr 00:15:17:88:97:79
inet addr:172.10.1.100 Bcast:172.10.1.255 Mask:255.255.255.0
inet6 addr: fe80::215:17ff:fe88:9779/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:1113794891 errors:0 dropped:97 overruns:0 frame:0
TX packets:699821135 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:843942929141 (785.9 GB) TX bytes:838436421169 (780.8 GB)
Base address:0x2000 Memory:b8800000-b8820000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:1085510396 errors:0 dropped:0 overruns:0 frame:0
TX packets:1085510396 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:422100792153 (393.1 GB) TX bytes:422100792153 (393.1 GB)
peth0 Link encap:Ethernet HWaddr 00:15:17:88:97:78
inet6 addr: fe80::215:17ff:fe88:9778/64 Scope:Link
UP BROADCAST RUNNING PROMISC MULTICAST MTU:1500 Metric:1
RX packets:441918386 errors:0 dropped:742 overruns:0 frame:0
TX packets:515286699 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:199626686230 (185.9 GB) TX bytes:337365591758 (314.1 GB)
Base address:0x2020 Memory:b8820000-b8840000
veth0 Link encap:Ethernet HWaddr 00:00:00:00:00:00
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
veth1 Link encap:Ethernet HWaddr 00:00:00:00:00:00
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
veth2 Link encap:Ethernet HWaddr 00:00:00:00:00:00
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
veth3 Link encap:Ethernet HWaddr 00:00:00:00:00:00
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
vif0.0 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
vif0.1 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
vif0.2 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
vif0.3 Link encap:Ethernet HWaddr fe:ff:ff:ff:ff:ff
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
-- Added (2) --
Finally I used w3m (a text-mode web browser which runs on terminal) to connect from localhost. :P
|
I think the OP is referring to having multiple interfaces configured on the test machine.
You can specify the IP address that Django will bind to as follows:
# python manage.py runserver 0.0.0.0:8000
This would bind Django to all interfaces on port 8000. You can pass any active IP address in place of 0.0.0.0, so simply use the IP address of the interface you want to bind to.
Hope this helps.
|
Good or bad practice in Python: import in the middle of a file
|
Suppose I have a relatively long module, but need an external module or method only once.
Is it considered OK to import that method or module in the middle of the module?
Or should imports only be in the first part of the module.
Example:
import string, pythis, pythat
...
...
...
...
def func():
blah
blah
blah
from pysomething import foo
foo()
etc
etc
etc
...
...
...
Please justify your answer and add links to PEPs or relevant sources
|
PEP 8 authoritatively states:
Imports are always put at the top of
the file, just after any module
comments and docstrings, and before module globals and constants.
PEP 8 should be the basis of any "in-house" style guide, since it summarizes what the core Python team has found to be the most effective style, overall (and with individual dissent of course, as on any other language, but consensus and the BDFL agree on PEP 8).
|
Unicode to UTF8 for CSV Files - Python via xlrd
|
I'm trying to translate an Excel spreadsheet to CSV using the Python xlrd and csv modules, but am getting hung up on encoding issues. Xlrd produces output from Excel in Unicode, and the CSV module requires UTF-8.
I imaging that this has nothing to do with the xlrd module: everything works fine outputing to stdout or other outputs that don't require a specific encoding.
The worksheet is encoded as UTF-16-LE, according to book.encoding
The simplified version of what I'm doing is:
from xlrd import *
import csv
b = open_workbook('file.xls')
s = b.sheet_by_name('Export')
bc = open('file.csv','w')
bcw = csv.writer(bc,csv.excel,b.encoding)
for row in range(s.nrows):
this_row = []
for col in range(s.ncols):
this_row.append(s.cell_value(row,col))
bcw.writerow(this_row)
This produces the following error, about 740 lines in:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xed' in position 5: ordinal not in range(128)
The value is seems to be getting hung up on is "516-777316" -- the text in the original Excel sheet is "516-7773167" (with a 7 on the end)
I'll be the first to admit that I have only a vague sense of how character encoding works, so most of what I've tried so far are various fumbling permutations of .encode and .decode on the s.cell_value(row,col)
If someone could suggest a solution I would appreciate it -- even better if you could provide an explanation of what's not working and why, so that I can more easily debug these problems myself in the future.
Thanks in advance!
EDIT:
Thanks for the comments so far.
When I user this_row.append(s.cell(row,col)) (e.g. s.cell instead of s.cell_value) the entire document writes without errors.
The output isn't particularly desirable (text:u'516-7773167'), but it avoids the error even though the offending characters are still in the output.
This makes me think that the challenge might be in xlrd after all.
Thoughts?
|
I expect the cell_value return value is the unicode string that's giving you problems (please print its type() to confirm that), in which case you should be able to solve it by changing this one line:
this_row.append(s.cell_value(row,col))
to:
this_row.append(s.cell_value(row,col).encode('utf8'))
If cell_value is returning multiple different types, then you need to encode if and only if it's returning a unicode string; so you'd split this line into a few lines:
val = s.cell_value(row, col)
if isinstance(val, unicode):
val = val.encode('utf8')
this_row.append(val)
|
python non-privileged ICMP
|
While trying to figure out the best method to ping (ICMP) something from python, I came across these questions:
How can I perform a ping or traceroute in python, accessing the output as it is produced?
ping a site in python
How can I perform a ping or traceroute using native python?
The answers generally boil down to "use this third party module with root privileges" or "use the system's ping command and parse the output". Of the native methods, icmplib and M. Cowles and J. Diemer's ping.py explicitly mention the need for root privileges, as does the scapy manual.
So from that front, natively sending ICMP pings without special privileges seems impossible. The system ping command does manage somehow, but its man page doesn't shed any light on how. The man page for icmp, on the other hand, seems to say it's possible:
Non-privileged ICMP
ICMP sockets can be opened with the SOCK_DGRAM socket type without
requiring root privileges. The synopsis is the following:
socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)
Datagram oriented ICMP sockets offer a subset of the functionality avail-
able to raw ICMP sockets. Only IMCP request messages of the following
types can be sent: ICMP_ECHO, ICMP_TSTAMP or ICMP_MASKREQ.
So it would seem that, at least according to icmp, it's allowed. So why is it that all the python tools are unable to do this? Are the python tools too general and expect any work on privileged sockets to be privileged? Would it be possible to write a ping function in C that can ping without root privileges, and extend python with this? Has anyone done this? Have I just misunderstood the problem?
|
The ping program is installed setuid root. This allows any user to use the program, and still be able to open a raw socket.
After it opens the raw socket, it typically drops root privs.
You generally need a raw socket to do ICMP correctly, and raw sockets are usually restricted. So it's not really python's fault at all.
Regarding the bit about ICMP above, apparently many implementations don't really support those combinations of flags well. So it is likely that most implmentations just use the way they "know" works on most / all architectures.
|
Django FileField with upload_to determined at runtime
|
I'm trying to set up my uploads so that if user joe uploads a file it goes to MEDIA_ROOT/joe as opposed to having everyone's files go to MEDIA_ROOT. The problem is I don't know how to define this in the model. Here is how it currently looks:
class Content(models.Model):
name = models.CharField(max_length=200)
user = models.ForeignKey(User)
file = models.FileField(upload_to='.')
So what I want is instead of '.' as the upload_to, have it be the user's name.
I understand that as of Django 1.0 you can define your own function to handle the upload_to but that function has no idea of who the user will be either so I'm a bit lost.
Thanks for the help!
|
You've probably read the documentation, so here's an easy example to make it make sense:
def content_file_name(instance, filename):
return '/'.join(['content', instance.user.username, filename])
class Content(models.Model):
name = models.CharField(max_length=200)
user = models.ForeignKey(User)
file = models.FileField(upload_to=content_file_name)
As you can see, you don't even need to use the filename given - you could override that in your upload_to callable too if you liked.
|
Automatically Generated Python Code from an UML diagram?
|
The question is not the same as Whatâs the best way to generate a UML diagram from Python source code?, but the other way around.
Topcoder UML tool automatically generates code in only Java or C#. Since I need to create a very depended data structure at a point, I am hesitant to turn to Java. I want to use Python. So:
Is there an UML-like tool that
automatically generates Python code
from your diagram?
If there is, is it possible to generate it from the Topcoder UML tool?
Can you shortly compare the tools?
|
Enterprise Architect is able to generate python code code from UML diagrams.
It is also able to also perform some reverse engineering, and therefore maintain the two versions (UML and python) synchronized together.
However, I have never used it in that way, except for some small tests just to see it in action. I personally find productivity in Python so high, that even if I am really satisfied with EA, I prefer it just to document the design.
|
Hosting Mercurial with IIS 6
|
I'm trying to set up Mercurial repositories to be hosted by IIS under Windows Server 2003. Following this post I installed Python 2.5.4.4 and Mercurial 1.3, set up virtual dir, extracted library.zip and created hgwebdir.config.
However, when I trying to open the http://hostname/hg/hgwebdir.cgi I got an error âThe specified CGI application misbehaved by not returning a complete set of HTTP headers.â I did all by best:
Checked IIS mappings to both .py and .cgi extensions. I even tried to use FastCGI with no success.
Created âHello Worldâ in the same dir and checked that it works fine.
Checked read/exec permissions to Python, IIS and repos directories for IUSR, IWAM and NETWORK SERVICE.
Tried to apply two different patches from Mercurial mailing list. Since they both are old I haven't success with it.
INstalled Sysinternals' procmon and checked for filesystem errors during request. I found nothing except lots of Buffer Overflow results in Python process while it loads it's libraries.
Tried to add 'Content-type: text/html' to the script.
One more thing is when I'm requesting inexistent script file (e.g /hg/inexist.cgi) I have the same error. Nothing helped!
|
Some more things that I needed to fix:
Where the various HOWTOs say to use c:\whatever\Python26\python.exe -u "%s" "%s" instead use c:\whatever\Python26\python.exe -u -O -B "%s" "%s" -O causes it to also look for .pyo files (not just .py or .pyc, which at least in my version weren't present). -B causes it to not attempt to compile .py files that it finds into .pyo files (which fails due to lacking write permissions)
I'd installed Python 2.7. Mercurial 1.6.2's .pyo files were compiled with Python 2.6. This resulted in a magic number error. Uninstalling 2.7 and installing 2.6.5 fixed this. (If you're reading this at some point in the future, this point may no longer be relevant - check the name of the DLL in Mercurial's directory, or TortoiseHg's directory, depending on where you took library.zip from)
hgwebdir.cgi is now just hgweb.cgi - webdir was integrated into it
|
Using module 'subprocess' with timeout
|
Here's the Python code to run an arbitrary command returning its stdout data, or raise an exception on non-zero exit codes:
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
communicate is used to wait for the process to exit:
stdoutdata, stderrdata = proc.communicate()
The subprocess module does not support timeout--ability to kill a process running for more than X number of seconds--therefore, communicate may take forever to run.
What is the simplest way to implement timeouts in a Python program meant to run on Windows and Linux?
|
I don't know much about the low level details; but, given that in
python 2.6 the API offers the ability to wait for threads and
terminate processes, what about running the process in a separate
thread?
import subprocess, threading
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout):
def target():
print 'Thread started'
self.process = subprocess.Popen(self.cmd, shell=True)
self.process.communicate()
print 'Thread finished'
thread = threading.Thread(target=target)
thread.start()
thread.join(timeout)
if thread.is_alive():
print 'Terminating process'
self.process.terminate()
thread.join()
print self.process.returncode
command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=3)
command.run(timeout=1)
The output of this snippet in my machine is:
Thread started
Process started
Process finished
Thread finished
0
Thread started
Process started
Terminating process
Thread finished
-15
where it can be seen that, in the first execution, the process
finished correctly (return code 0), while the in the second one the
process was terminated (return code -15).
I haven't tested in windows; but, aside from updating the example
command, I think it should work since I haven't found in the
documentation anything that says that thread.join or process.terminate
is not supported.
|
Hierarchical Bayes for R or Python
|
Hierarchical Bayes models are commonly used in Marketing, Political Science, and Econometrics. Yet, the only package I know of is bayesm, which is really a companion to a book (Bayesian Statistics and Marketing, by Rossi, et al.) Am I missing something? Is there a software package for R or Python doing the job out there, and/or a worked-out example in the associated language?
|
There's OpenBUGS and R helper packages. Check out Gelman's site for his book, which has most of the relevant links:
http://www.stat.columbia.edu/~gelman/software/
Example of computation in R and Bugs
On the Python side, I only know of PyMC:
http://code.google.com/p/pymc/
An example statistical model
EDIT: Added a link to the appropriate appendix from Gelman's book, available online, for an example using R and BUGS.
|
Python - Get relative path of all files and subfolders in a directory
|
I am searching for a good way to get relative paths of files and (sub)folders within a specific folder.
For my current approach I am using os.walk(). It is working but it does not seem "pythonic" to me:
myFolder = "myfolder"
fileSet = set() # yes, I need a set()
for root, dirs, files in os.walk(myFolder):
for fileName in files:
fileSet.add(root.replace(myFolder, "") + os.sep + fileName)
Any other suggestions?
Thanks
|
Use os.path.relpath(). This is exactly its intended use.
import os
rootDir = "myfolder"
fileSet = set()
for dir_, _, files in os.walk(rootDir):
for fileName in files:
relDir = os.path.relpath(dir_, rootDir)
relFile = os.path.join(relDir, fileName)
fileSet.add(relFile)
Note that os.path.relpath() was added in Python 2.6 and is supported on Windows and Unix.
|
Is there a standard pythonic way to treat physical units / quantities in python?
|
Is there a standard pythonic way to treat physical units / quantities in python? I saw different module-specific solutions from different fields like physics or neuroscience. But I would rather like to use a standard method than "island"-solutions as others should be able to easily read my code.
|
The best solution is the Unum package. a de-facto standard, imho.
|
How to start a background process in Python?
|
I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.
|
While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess module. For simple commands its equivalent, but it offers more options if you want to do something complicated.
Example for your case:
import subprocess
subprocess.Popen(["rm","-r","some.file"])
This should run rm -r somefile in the background. But be wary: subprocess.Popen() only runs a process in the background if nothing in the python script depends on the output of the command being run:
For example, the following command will not run in the background:
import subprocess
ls_output=subprocess.Popen(["ls", "-a"], stdout=subprocess.PIPE)
See the documentation here.
Also, a point of clarification: "Background" purely a shell concept: what you probably want is to spawn a new process. I've used "background" here to refer to shell-background-like behavior, but don't mistake this for the process actually being in the background.
|
How can I take a screenshot/image of a website using Python?
|
What I want to achieve is to get a website screenshot from any website in python.
Env: Linux
|
Here is a simple solution using webkit:
http://webscraping.com/blog/Webpage-screenshots-with-webkit/
import sys
import time
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *
class Screenshot(QWebView):
def __init__(self):
self.app = QApplication(sys.argv)
QWebView.__init__(self)
self._loaded = False
self.loadFinished.connect(self._loadFinished)
def capture(self, url, output_file):
self.load(QUrl(url))
self.wait_load()
# set to webpage size
frame = self.page().mainFrame()
self.page().setViewportSize(frame.contentsSize())
# render image
image = QImage(self.page().viewportSize(), QImage.Format_ARGB32)
painter = QPainter(image)
frame.render(painter)
painter.end()
print 'saving', output_file
image.save(output_file)
def wait_load(self, delay=0):
# process app events until page loaded
while not self._loaded:
self.app.processEvents()
time.sleep(delay)
self._loaded = False
def _loadFinished(self, result):
self._loaded = True
s = Screenshot()
s.capture('http://webscraping.com', 'website.png')
s.capture('http://webscraping.com/blog', 'blog.png')
|
Actions triggered by field change in Django
|
How do I have actions occur when a field gets changed in one of my models? In this particular case, I have this model:
class Game(models.Model):
STATE_CHOICES = (
('S', 'Setup'),
('A', 'Active'),
('P', 'Paused'),
('F', 'Finished')
)
name = models.CharField(max_length=100)
owner = models.ForeignKey(User)
created = models.DateTimeField(auto_now_add=True)
started = models.DateTimeField(null=True)
state = models.CharField(max_length=1, choices=STATE_CHOICES, default='S')
and I would like to have Units created, and the 'started' field populated with the current datetime (among other things), when the state goes from Setup to Active.
I suspect that a model instance method is needed, but the docs don't seem to have much to say about using them in this manner.
Update: I've added the following to my Game class:
def __init__(self, *args, **kwargs):
super(Game, self).__init__(*args, **kwargs)
self.old_state = self.state
def save(self, force_insert=False, force_update=False):
if self.old_state == 'S' and self.state == 'A':
self.started = datetime.datetime.now()
super(Game, self).save(force_insert, force_update)
self.old_state = self.state
|
Django has a nifty feature called signals, which are effectively triggers that are set off at specific times:
Before/after a model's save method is called
Before/after a model's delete method is called
Before/after an HTTP request is made
Read the docs for full info, but all you need to do is create a receiver function and register it as a signal. This is usually done in models.py.
from django.core.signals import request_finished
def my_callback(sender, **kwargs):
print "Request finished!"
request_finished.connect(my_callback)
Simple, eh?
|
Split a list into parts based on a set of indexes in Python
|
What is the best way to split a list into parts based on an arbitrary number of indexes? E.g. given the code below
indexes = [5, 12, 17]
list = range(20)
return something like this
part1 = list[:5]
part2 = list[5:12]
part3 = list[12:17]
part4 = list[17:]
If there are no indexes it should return the entire list.
|
This is the simplest and most pythonic solution I can think of:
def partition(alist, indices):
return [alist[i:j] for i, j in zip([0]+indices, indices+[None])]
if the inputs are very large, then the iterators solution should be more convenient:
from itertools import izip, chain
def partition(alist, indices):
pairs = izip(chain([0], indices), chain(indices, [None]))
return (alist[i:j] for i, j in pairs)
and of course, the very, very lazy guy solution (if you don't mind to get arrays instead of lists, but anyway you can always revert them to lists):
import numpy
partition = numpy.split
|
Double Iteration in List Comprehension
|
In Python you can have multiple iterators in a list comprehension, like
[(x,y) for x in a for y in b]
for some suitable sequences a and b. I'm aware of the nested loop semantics of Python's list comprehensions.
My question is: Can one iterator in the comprehension refer to the other? In other words: Could I have something like this:
[x for x in a for a in b]
where the current value of the outer loop is the iterator of the inner?
As an example, if I have a nested list:
a=[[1,2],[3,4]]
what would the list comprehension expression be to achieve this result:
[1,2,3,4]
?? (Please only list comprehension answers, since this is what I want to find out).
|
To answer your question with your own suggestion:
>>> [x for b in a for x in b] # Works fine
While you asked for list comprehension answers, let me also point out the excellent itertools.chain():
>>> from itertools import chain
>>> list(chain.from_iterable(a))
>>> list(chain(*a)) # If you're using python < 2.6
|
combine javascript files at deployment in python
|
I'm trying to reduce the number of scripts included in our website and we use buildout to handle deployments. Has anybody successfully implemented a method of combining and compressing scripts with buildout?
|
Here's a Python script I made that I use with all my heavy JavaScript projects. I'm using YUICompressor, but you can change the code to use another compressor.
import os, os.path, shutil
YUI_COMPRESSOR = 'yuicompressor-2.4.2.jar'
def compress(in_files, out_file, in_type='js', verbose=False,
temp_file='.temp'):
temp = open(temp_file, 'w')
for f in in_files:
fh = open(f)
data = fh.read() + '\n'
fh.close()
temp.write(data)
print ' + %s' % f
temp.close()
options = ['-o "%s"' % out_file,
'--type %s' % in_type]
if verbose:
options.append('-v')
os.system('java -jar "%s" %s "%s"' % (YUI_COMPRESSOR,
' '.join(options),
temp_file))
org_size = os.path.getsize(temp_file)
new_size = os.path.getsize(out_file)
print '=> %s' % out_file
print 'Original: %.2f kB' % (org_size / 1024.0)
print 'Compressed: %.2f kB' % (new_size / 1024.0)
print 'Reduction: %.1f%%' % (float(org_size - new_size) / org_size * 100)
print ''
#os.remove(temp_file)
I use it like this (the below is just a code snippet, and assumes that the compress function exists in the current namespace):
SCRIPTS = [
'app/js/libs/EventSource.js',
'app/js/libs/Hash.js',
'app/js/libs/JSON.js',
'app/js/libs/ServiceClient.js',
'app/js/libs/jquery.hash.js',
'app/js/libs/Application.js',
'app/js/intro.js',
'app/js/jquery-extras.js',
'app/js/settings.js',
'app/js/api.js',
'app/js/game.js',
'app/js/user.js',
'app/js/pages.intro.js',
'app/js/pages.home.js',
'app/js/pages.log-in.js',
'app/js/pages.log-out.js',
'app/js/pages.new-command.js',
'app/js/pages.new-frame.js',
'app/js/pages.not-found.js',
'app/js/pages.register.js',
'app/js/pages.outro.js',
'app/js/outro.js',
]
SCRIPTS_OUT_DEBUG = 'app/js/multifarce.js'
SCRIPTS_OUT = 'app/js/multifarce.min.js'
STYLESHEETS = [
'app/media/style.css',
]
STYLESHEETS_OUT = 'app/media/style.min.css'
def main():
print 'Compressing JavaScript...'
compress(SCRIPTS, SCRIPTS_OUT, 'js', False, SCRIPTS_OUT_DEBUG)
print 'Compressing CSS...'
compress(STYLESHEETS, STYLESHEETS_OUT, 'css')
if __name__ == '__main__':
main()
|
Cython and numpy speed
|
I'm using cython for a correlation calculation in my python program. I have two audio data sets and I need to know the time difference between them. The second set is cut based on onset times and then slid across the first set. There are two for-loops: one slides the set and the inner loop calculates correlation at that point. This method works very well and it's accurate enough.
The problem is that with pure python this takes more than one minute. With my cython code, it takes about 17 seconds. This still is too much. Do you have any hints how to speed-up this code:
import numpy as np
cimport numpy as np
cimport cython
FTYPE = np.float
ctypedef np.float_t FTYPE_t
@cython.boundscheck(False)
def delay(np.ndarray[FTYPE_t, ndim=1] f, np.ndarray[FTYPE_t, ndim=1] g):
cdef int size1 = f.shape[0]
cdef int size2 = g.shape[0]
cdef int max_correlation = 0
cdef int delay = 0
cdef int current_correlation, i, j
# Move second data set frame by frame
for i in range(0, size1 - size2):
current_correlation = 0
# Calculate correlation at that point
for j in range(size2):
current_correlation += f[<unsigned int>(i+j)] * g[j]
# Check if current correlation is highest so far
if current_correlation > max_correlation:
max_correlation = current_correlation
delay = i
return delay
|
Edit:
There's now scipy.signal.fftconvolve which would be the preferred approach to doing the FFT based convolution approach that I describe below. I'll leave the original answer to explain the speed issue, but in practice use scipy.signal.fftconvolve.
Original answer:
Using FFTs and the convolution theorem will give you dramatic speed gains by converting the problem from O(n^2) to O(n log n). This is particularly useful for long data sets, like yours, and can give speed gains of 1000s or much more, depending on length. It's also easy to do: just FFT both signals, multiply, and inverse FFT the product. numpy.correlate doesn't use the FFT method in the cross-correlation routine and is better used with very small kernels.
Here's an example
from timeit import Timer
from numpy import *
times = arange(0, 100, .001)
xdata = 1.*sin(2*pi*1.*times) + .5*sin(2*pi*1.1*times + 1.)
ydata = .5*sin(2*pi*1.1*times)
def xcorr(x, y):
return correlate(x, y, mode='same')
def fftxcorr(x, y):
fx, fy = fft.fft(x), fft.fft(y[::-1])
fxfy = fx*fy
xy = fft.ifft(fxfy)
return xy
if __name__ == "__main__":
N = 10
t = Timer("xcorr(xdata, ydata)", "from __main__ import xcorr, xdata, ydata")
print 'xcorr', t.timeit(number=N)/N
t = Timer("fftxcorr(xdata, ydata)", "from __main__ import fftxcorr, xdata, ydata")
print 'fftxcorr', t.timeit(number=N)/N
Which gives the running times per cycle (in seconds, for a 10,000 long waveform)
xcorr 34.3761689901
fftxcorr 0.0768054962158
It's clear the fftxcorr method is much faster.
If you plot out the results, you'll see that they are very similar near zero time shift. Note, though, as you get further away the xcorr will decrease and the fftxcorr won't. This is because it's a bit ambiguous what to do with the parts of the waveform that don't overlap when the waveforms are shifted. xcorr treats it as zero and the FFT treats the waveforms as periodic, but if it's an issue it can be fixed by zero padding.
|
python interpolation
|
I have a set of data's as,
Table-1
X1 | Y1
------+--------
0.1 | 0.52147
0.02 | 0.8879
0.08 | 0.901
0.11 | 1.55
0.15 | 1.82
0.152 | 1.95
Table-2
X2 | Y2
-----+------
0.2 | 0.11
0.21 | 0.112
0.34 | 0.120
0.33 | 1.121
I have to interpolate Table-2 'Y2' value for Table-1 'X1' value like,
X1 | Y2
-------+-------
0.1 |
0.02 |
0.08 |
0.11 |
0.15 |
0.152 |
Note: Both Table-1 & 2 are unequal intervals with number of (X | Y) entries will differ, for eg. here we have 6 (X1 | Y1) entries in Table-1 and only 4 (X2 | Y2) in Table-2
Please help me which interpolation algorithm to use in Numpy, and how to proceed?
|
numpy.interp seems to be the function you want: pass your X1 as the first argument x, your X2 as the second argument xp, your Y2 as the third argument fp, and you'll get the Y values corresponding to the X1 coordinates (looks like you want to completely ignore the existing Y1, right? this is what this does - otherwise you'll have to clarify your question much better explaining what role you have in might for the Y1's!).
If you want more than linear interpolation, I suggest you see scipy.interpolate and its tutorial rather than trying to stretch numpy beyond its simplicity;-).
|
Importing files in Python from __init__.py
|
Suppose I have the following structure:
app/
__init__.py
foo/
a.py
b.py
c.py
__init__.py
a.py, b.py and c.py share some common imports (logging, os, re, etc). Is it possible to import these three or four common modules from the __init__.py file so I don't have to import them in every one of the files?
Edit: My goal is to avoid having to import 5-6 modules in each file and it's not related to performance reasons.
|
You can do this using a common file such as include.py, but it goes against recommended practices because it involves a wildcard import. Consider the following files:
app/
__init__.py
foo/
a.py
b.py
c.py
include.py <- put the includes here.
__init__.py
Now, in a.py, etc., do:
from include import *
As stated above, it's not recommended because wildcard-imports are discouraged.
|
Adding a field to a structured numpy array
|
What is the cleanest way to add a field to a structured numpy array? Can it be done destructively, or is it necessary to create a new array and copy over the existing fields? Are the contents of each field stored contiguously in memory so that such copying can be done efficiently?
|
If you're using numpy 1.3, there's also numpy.lib.recfunctions.append_fields().
For many installations, you'll need to import numpy.lib.recfunctions to access this. import numpy will not allow one to see the numpy.lib.recfunctions
|
get request data in Django form
|
Is it possible to get request.user data in a form class? I want to clean an email address to make sure that it's unique, but if it's the current users email address then it should pass.
This is what I currently have which works great for creating new users, but if I want to edit a user I run into the problem of their email not validating, because it comes up as being taken already. If I could check that it's their email using request.user.email then I would be able to solve my problem, but I'm not sure how to do that.
class editUserForm(forms.Form):
email_address = forms.EmailField(widget=forms.TextInput(attrs={'class':'required'}))
def clean_email_address(self):
this_email = self.cleaned_data['email_address']
test = UserProfiles.objects.filter(email = this_email)
if len(test)>0:
raise ValidationError("A user with that email already exists.")
else:
return this_email
|
As ars and Diarmuid have pointed out, you can pass request.user into your form, and use it in validating the email. Diarmuid's code, however, is wrong. The code should actually read:
from django import forms
class UserForm(forms.Form):
email_address = forms.EmailField(widget = forms.TextInput(attrs = {'class':'required'}))
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(UserForm, self).__init__(*args, **kwargs)
def clean_email_address(self):
email = self.cleaned_data.get('email_address')
if self.user and self.user.email == email:
return email
if UserProfile.objects.filter(email=email).count():
raise forms.ValidationError(u'That email address already exists.')
return email
Then, in your view, you can use it like so:
def someview(request):
if request.method == 'POST':
form = UserForm(request.POST, user=request.user)
if form.is_valid():
# Do something with the data
pass
else:
form = UserForm(user=request.user)
# Rest of your view follows
Note that you should pass request.POST as a keyword argument, since your constructor expects 'user' as the first positional argument.
Doing it this way, you need to pass user as a keyword argument. You can either pass request.POST as a positional argument, or a keyword argument (via data=request.POST).
|
Python - tempfile.TemporaryFile cannot be read; why?
|
The official documentation for TemporaryFile reads:
The mode parameter defaults to 'w+b'
so that the file created can be read
and written without being closed.
Yet, the below code does not work as expected:
import tempfile
def play_with_fd():
with tempfile.TemporaryFile() as f:
f.write('test data\n')
f.write('most test data\n')
print 'READ:', f.read()
f.write('further data')
print 'READ:', f.read()
f.write('even more')
print 'READ:', f.read()
print 'READ:', f.read()
print 'READ:', f.read()
if __name__ == '__main__':
play_with_fd()
The output I get is:
> python play.py
READ:
READ:
READ:
READ:
READ:
Can anyone explain this behavior? Is there a way to read from temporary files at all? (without having to use the low-level mkstemp that wouldn't automatically delete the files; and I don't care about named files)
|
You must put
f.seek(0)
before trying to read the file (this will send you to the beginning of the file), and
f.seek(0, 2)
to return to the end so you can assure you won't overwrite it.
|
recursive lambda-expressions possible?
|
I'm trying to write a lambda-expression that calls itself, but i can't seem to find any syntax for that, or even if it's possible.
Essentially what I wanted to transfer the following function into the following lambda expression: (I realize it's a silly application, it just adds, but I'm exploring what I can do with lambda-expressions in python)
def add(a, b):
if a <= 0:
return b
else:
return 1 + add(a - 1, b)
add = lambda a, b: [1 + add(a-1, b), b][a <= 0]
but calling the lambda form of add results in a runtime error because the maximum recursion depth is reached. Is it even possible to do this in python? Or am I just making some stupid mistake? Oh, I'm using python3.0, but I don't think that should matter?
|
Maybe you need a Y combinator?
Edit - make that a Z combinator (I hadn't realized that Y combinators are more for call-by-name)
Using the definition of the Z combinator from Wikipedia
>>> Z = lambda f: (lambda x: f(lambda *args: x(x)(*args)))(lambda x: f(lambda *args: x(x)(*args)))
Using this, you can then define add as a completely anonymous function (ie. no reference to its name in its definition)
>>> add = Z(lambda f: lambda a, b: b if a <= 0 else 1 + f(a - 1, b))
>>> add(1, 1)
2
>>> add(1, 5)
6
|
How to write an application for the system tray in Linux
|
How do I write my application so it'll live in the system tray on Linux? In fact, just like CheckGmail.
As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon.
Is there an API, class or something for doing this? All I'm able to find seems to be for Windows.
If I have to be language specific, then preferably in C/C++ but a solution in Python will most likely also do.
Thanks.
|
The Qt framework contains a QSystemTrayIcon class. This means that you can write an application in C++ or Python (or any other language with Qt bindings, including C#, Ada, Pascal, Perl, PHP and Ruby) and run your application on Windows, Linux, Mac or any other supported Qt operating system. I should add that Qt applications generally do a pretty good job of looking native on whatever operating system you are using without very much effort (even between Gnome/KDE on Linux). Qt also has excellent documentation, lots of sample code, a generous license and is well-maintained.
|
Filter by property
|
Is it possible to filter by property?
i have a method in my model:
@property
def myproperty(self):
[..]
and now i want to filter by this property like:
MyModel.objects.filter(myproperty=[..])
is this somehow possible?
|
Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.
|
Listing serial (COM) ports on Windows?
|
I'm looking for a robust way to list the available serial (COM) ports on a Windows machine. There's this post about using WMI, but I would like something less .NET specific - I want to get the list of ports in a Python or a C++ program, without .NET.
I currently know of two other approaches:
Reading the information in the HARDWARE\\DEVICEMAP\\SERIALCOMM registry key. This looks like a great option, but is it robust? I can't find a guarantee online or in MSDN that this registry cell indeed always holds the full list of available ports.
Tryint to call CreateFile on COMN with N a number from 1 to something. This isn't good enough, because some COM ports aren't named COMN. For example, some virtual COM ports created are named CSNA0, CSNB0, and so on, so I wouldn't rely on this method.
Any other methods/ideas/experience to share?
Edit: by the way, here's a simple Python implementation of reading the port names from registry:
import _winreg as winreg
import itertools
def enumerate_serial_ports():
""" Uses the Win32 registry to return a iterator of serial
(COM) ports existing on this computer.
"""
path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
try:
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)
except WindowsError:
raise IterationError
for i in itertools.count():
try:
val = winreg.EnumValue(key, i)
yield (str(val[1]), str(val[0]))
except EnvironmentError:
break
|
Using pySerial with Python:
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
print p
|
How do I get monotonic time durations in python?
|
I want to log how long something takes in real walltime. Currently I'm doing this:
startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
But that will fail (produce incorrect results) if the time is adjusted while the SQL query (or whatever it is) is running.
I don't want to just benchmark it. I want to log it in a live application in order to see trends on a live system.
I want something like clock_gettime(CLOCK_MONOTONIC,...), but in Python. And preferably without having to write a C module that calls clock_gettime().
|
That function is simple enough that you can use ctypes to access it:
#!/usr/bin/env python
__all__ = ["monotonic_time"]
import ctypes, os
CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
class timespec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long)
]
librt = ctypes.CDLL('librt.so.1', use_errno=True)
clock_gettime = librt.clock_gettime
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
def monotonic_time():
t = timespec()
if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_))
return t.tv_sec + t.tv_nsec * 1e-9
if __name__ == "__main__":
print monotonic_time()
|
Django ORM for desktop application
|
Recently, I have become increasingly familiar with Django. I have a new project that I am working on that will be using Python for a desktop application. Is it possible to use the Django ORM in a desktop application? Or should I just go with something like SQLAlchemy?
|
The Django people are sensible people with a philosophy of decoupling things. So yes, in theory you should be perfectly able to use Django's ORM in a standalone application.
Here's one guide I found: Django ORM as a standalone component.
|
Remove items from a list while iterating in Python
|
I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
for tup in somelist:
if determine(tup):
code_to_remove_tup
What should I use in place of code_to_remove_tup? I can't figure out how to remove the item in this fashion.
|
The answers suggesting list comprehensions are ALMOST correct -- except that they build a completely new list and then give it the same name the old list as, they do NOT modify the old list in place. That's different from what you'd be doing by selective removal, as in @Lennart's suggestion -- it's faster, but if your list is accessed via multiple references the fact that you're just reseating one of the references and NOT altering the list object itself can lead to subtle, disastrous bugs.
Fortunately, it's extremely easy to get both the speed of list comprehensions AND the required semantics of in-place alteration -- just code:
somelist[:] = [tup for tup in somelist if determine(tup)]
Note the subtle difference with other answers: this one is NOT assigning to a barename - it's assigning to a list slice that just happens to be the entire list, thereby replacing the list contents within the same Python list object, rather than just reseating one reference (from previous list object to new list object) like the other answers.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.