instruction
stringlengths 12
148
| input
stringlengths 16
30.2k
| output
stringlengths 11
27.3k
|
|---|---|---|
How to tell for which object attribute pickle fails?
|
When you pickle an object that has some attributes which cannot be pickled it will fail with a generic error message like:
PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed
Is there any way to tell which attribute caused the exception? I am using Python 2.5.2.
Even though I understand in principle the root cause of the problem (e.g. in the above example having an instance method) it can still be very hard to exactly pinpoint it. In my case I already defined a custom __getstate__ method, but forgot about a critical attribute. This happened in a complicated structure of nested objects, so it took me a while to identify the bad attribute.
As requested, here is one simple example were pickle intentionally fails:
import cPickle as pickle
import new
class Test(object):
pass
def test_func(self):
pass
test = Test()
pickle.dumps(test)
print "now with instancemethod..."
test.test_meth = new.instancemethod(test_func, test)
pickle.dumps(test)
This is the output:
now with instancemethod...
Traceback (most recent call last):
File "/home/wilbert/develop/workspace/Playground/src/misc/picklefail.py", line 15, in <module>
pickle.dumps(test)
File "/home/wilbert/lib/python2.5/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
Unfortunately there is no hint that the attribute test_meth causes the problem.
|
You could file a bug against Python for not including more helpful error messages. In the meantime, modify the _reduce_ex() function in copy_reg.py.
if base is self.__class__:
print self # new
raise TypeError, "can't pickle %s objects" % base.__name__
Output:
<bound method ?.test_func of <__main__.Test object at 0xb7f4230c>>
Traceback (most recent call last):
File "nopickle.py", line 14, in ?
pickle.dumps(test)
File "/usr/lib/python2.4/copy_reg.py", line 69, in _reduce_ex
raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects
|
Adding elements to python generators
|
Is it possible to append elements to a python generator?
I'm currently trying to get all images from a set of disorganized folders and write them to a new directory. To get the files, I'm using os.walk() which returns a list of image files in a single directory. While I can make a generator out of this single list, I don't know how to combine all these lists into one single generator. Any help would be much appreciated.
Related:
Flattening a shallow list in python
|
You are looking for itertools.chain. It will combine multiple iterables into a single one, like this:
>>> for i in itertools.chain([1,2,3], [4,5,6]):
... print i
...
1
2
3
4
5
6
|
How do I create a Django form that displays a checkbox label to the right of the checkbox?
|
When I define a Django form class similar to this:
def class MyForm(forms.Form):
check = forms.BooleanField(required=True, label="Check this")
It expands to HTML that looks like this:
<form action="." id="form" method=POST>
<p><label for="check">Check this:</label> <input type="checkbox" name="check" id="check" /></p>
<p><input type=submit value="Submit"></p>
</form>
I would like the checkbox input element to have a label that follows the checkbox, not the other way around. Is there a way to convince Django to do that?
[Edit]
Thanks for the answer from Jonas - still, while it fixes the issue I asked about (checkbox labels are rendered to the right of the checkbox) it introduces a new problem (all widget labels are rendered to the right of their widgets...)
I'd like to avoid overriding _html_output() since it's obviously not designed for it. The design I would come up with would be to implement a field html output method in the Field classes, override the one for the Boolean field and use that method in _html_output(). Sadly, the Django developers chose to go a different way, and I would like to work within the existing framework as much as possible.
CSS sounds like a decent approach, except that I don't know enough CSS to pull this off or even to decide whether I like this approach or not. Besides, I prefer markup that still resembles the final output, at least in rendering order.
Furthermore, since it can be reasonable to have more than one style sheet for any particular markup, doing this in CSS could mean having to do it multiple times for multiple styles, which pretty much makes CSS the wrong answer.
[Edit]
Seems like I'm answering my own question below. If anyone has a better idea how to do this, don't be shy.
|
Here's a solution I've come up with (Django v1.1):
{% load myfilters %}
[...]
{% for field in form %}
[...]
{% if field.field.widget|is_checkbox %}
{{ field }}{{ field.label_tag }}
{% else %}
{{ field.label_tag }}{{ field }}
{% endif %}
[...]
{% endfor %}
You'll need to create a custom template tag (in this example in a "myfilters.py" file) containing something like this:
from django import template
from django.forms.fields import CheckboxInput
register = template.Library()
@register.filter(name='is_checkbox')
def is_checkbox(value):
return isinstance(value, CheckboxInput)
More info on custom template tags available here.
Edit: in the spirit of asker's own answer:
Advantages:
No futzing with CSS.
The markup ends up looking the way it's supposed to.
I didn't hack Django internals. (but had to look at quite a bunch)
The template is nice, compact and idiomatic.
The filter code plays nice regardless of the exact values of the labels and input field names.
Disadvantages:
There's probably something somewhere out there that does it better and faster.
Unlikely that the client will be willing to pay for all the time spent on this just to move the label to the right...
|
Python serialize lexical closures?
|
Is there a way to serialize a lexical closure in Python using the standard library? pickle and marshal appear not to work with lexical closures. I don't really care about the details of binary vs. string serialization, etc., it just has to work. For example:
def foo(bar, baz) :
def closure(waldo) :
return baz * waldo
return closure
I'd like to just be able to dump instances of closure to a file and read them back.
Edit:
One relatively obvious way that this could be solved is with some reflection hacks to convert lexical closures into class objects and vice-versa. One could then convert to classes, serialize, unserialize, convert back to closures. Heck, given that Python is duck typed, if you overloaded the function call operator of the class to make it look like a function, you wouldn't even really need to convert it back to a closure and the code using it wouldn't know the difference. If any Python reflection API gurus are out there, please speak up.
|
PiCloud has released an open-source (LGPL) pickler which can handle function closure and a whole lot more useful stuff. It can be used independently of their cloud computing infrastructure - it's just a normal pickler. The whole shebang is documented here, and you can download the code via 'pip install cloud'. Anyway, it does what you want. Let's demonstrate that by pickling a closure:
import pickle
from StringIO import StringIO
import cloud
# generate a closure
def foo(bar, baz):
def closure(waldo):
return baz * waldo
return closure
closey = foo(3, 5)
# use the picloud pickler to pickle to a string
f = StringIO()
pickler = cloud.serialization.cloudpickle.CloudPickler(f)
pickler.dump(closey)
#rewind the virtual file and reload
f.seek(0)
closey2 = pickle.load(f)
Now we have closey, the original closure, and closey2, the one that has been restored from a string serialisation. Let's test 'em.
>>> closey(4)
20
>>> closey2(4)
20
Beautiful. The module is pure pythonâyou can open it up and easily see what makes the magic work. (The answer is a lot of code.)
|
Django - Set Up A Scheduled Job?
|
I've been working on a web app using Django, and I'm curious if there is a way to schedule a job to run periodically.
Basically I just want to run through the database and make some calculations/updates on an automatic, regular basis, but I can't seem to find any documentation on doing this.
Does anyone know how to set this up?
To clarify: I know I can set up a cron job to do this, but I'm curious if there is some feature in Django that provides this functionality. I'd like people to be able to deploy this app themselves without having to do much config (preferably zero).
I've considered triggering these actions "retroactively" by simply checking if a job should have been run since the last time a request was sent to the site, but I'm hoping for something a bit cleaner.
|
One solution that I have employed is to do this:
1) Create a custom management command, e.g.
python manage.py my_cool_command
2) Use cron (on Linux) or at (on Windows) to run my command at the required times.
This is a simple solution that doesn't require installing a heavy AMQP stack. However there are nice advantages to using something like Celery, mentioned in the other answers. In particular, with Celery it is nice to not have to spread your application logic out into crontab files. However the cron solution works quite nicely for a small to medium sized application and where you don't want a lot of external dependencies.
EDIT:
In later version of windows the at command is deprecated for Windows 8, Server 2012 and above. You can use schtasks.exe for same use.
|
How do YOU deploy your WSGI application? (and why it is the best way)
|
Deploying a WSGI application. There are many ways to skin this cat. I am currently using apache2 with mod-wsgi, but I can see some potential problems with this.
So how can it be done?
Apache Mod-wsgi (the other mod-wsgi's seem to not be worth it)
Pure Python web server eg paste, cherrypy, Spawning, Twisted.web
as 2 but with reverse proxy from nginx, apache2 etc, with good static file handling
Conversion to other protocol such as FCGI with a bridge (eg Flup) and running in a conventional web server.
More?
I want to know how you do it, and why it is the best way to do it. I would absolutely love you to bore me with details about the whats and the whys, application specific stuff, etc. I will upvote any non-insane answer.
|
As always: It depends ;-)
When I don't need any apache features I am going with a pure python webserver like paste etc. Which one exactly depends on your application I guess and can be decided by doing some benchmarks. I always wanted to do some but never came to it. I guess Spawning might have some advantages in using non blocking IO out of the box but I had sometimes problems with it because of the patching it's doing.
You are always free to put a varnish in front as well of course.
If an Apache is required I am usually going with solution 3 so that I can keep processes separate. You can also more easily move processes to other servers etc. I simply like to keep things separate.
For static files I am using right now a separate server for a project which just serves static images/css/js. I am using lighttpd as webserver which has great performance (in this case I don't have a varnish in front anymore).
Another useful tool is supervisord for controlling and monitoring these services.
I am additionally using buildout for managing my deployments and development sandboxes (together with virtualenv).
|
Has anyone used SciPy with IronPython?
|
I've been able to use the standard Python modules from IronPython, but I haven't gotten SciPy to work yet. Has anyone been able to use SciPy from IronPython? What did you have to do to make it work?
Update: See Numerical computing in IronPython with Ironclad
Update: Microsoft is partnering with Enthought to make SciPy for .NET.
|
Some of my workmates are working on Ironclad, a project that will make extension modules for CPython work in IronPython. It's still in development, but parts of numpy, scipy and some other modules already work. You should try it out to see whether the parts of scipy you need are supported.
It's an open-source project, so if you're interested you could even help. In any case, some feedback about what you're trying to do and what parts we should look at next is helpful too.
|
Generating unique, ordered Pythagorean triplets
|
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks.
import math
def main():
for x in range (1, 1000):
for y in range (1, 1000):
for z in range(1, 1000):
if x*x == y*y + z*z:
print y, z, x
print '-'*50
if __name__ == '__main__':
main()
|
Pythagorean Triples make a good example for claiming "for loops considered harmful", because for loops seduce us into thinking about counting, often the most irrelevant part of a task.
(I'm going to stick with pseudo-code to avoid language biases, and to keep the pseudo-code streamlined, I'll not optimize away multiple calculations of e.g. x * x and y * y.)
Version 1:
for x in 1..N {
for y in 1..N {
for z in 1..N {
if x * x + y * y == z * z then {
// use x, y, z
}
}
}
}
is the worst solution. It generates duplicates, and traverses parts of the space that aren't useful (e.g. whenever z < y). Its time complexity is cubic on N.
Version 2, the first improvement, comes from requiring x < y < z to hold, as in:
for x in 1..N {
for y in x+1..N {
for z in y+1..N {
if x * x + y * y == z * z then {
// use x, y, z
}
}
}
}
which reduces run time and eliminates duplicated solutions. However, it is still cubic on N; the improvement is just a reduction of the co-efficient of N-cubed.
It is pointless to continue examining increasing values of z after z * z < x * x + y * y no longer holds. That fact motivates Version 3, the first step away from brute-force iteration over z:
for x in 1..N {
for y in x+1..N {
z = y + 1
while z * z < x * x + y * y {
z = z + 1
}
if z * z == x * x + y * y and z <= N then {
// use x, y, z
}
}
}
For N of 1000, this is about 5 times faster than Version 2, but it is still cubic on N.
The next insight is that x and y are the only independent variables; z depends on their values, and the last z value considered for the previous value of y is a good starting search value for the next value of y. That leads to Version 4:
for x in 1..N {
y = x+1
z = y+1
while z <= N {
while z * z < x * x + y * y {
z = z + 1
}
if z * z == x * x + y * y and z <= N then {
// use x, y, z
}
y = y + 1
}
}
which allows y and z to "sweep" the values above x only once. Not only is it over 100 times faster for N of 1000, it is quadratic on N, so the speedup increases as N grows.
I've encountered this kind of improvement often enough to be mistrustful of "counting loops" for any but the most trivial uses (e.g. traversing an array).
Update: Apparently I should have pointed out a few things about V4 that are easy to overlook.
Both of the while loops are controlled by the value of z (one directly, the other indirectly through the square of z). The inner while is actually speeding up the outer while, rather than being orthogonal to it. It's important to look at what the loops are doing, not merely to count how many loops there are.
All of the calculations in V4 are strictly integer arithmetic. Conversion to/from floating-point, as well as floating-point calculations, are costly by comparison.
V4 runs in constant memory, requiring only three integer variables. There are no arrays or hash tables to allocate and initialize (and, potentially, to cause an out-of-memory error).
The original question allowed all of x, y, and x to vary over the same range. V1..V4 followed that pattern.
Below is a not-very-scientific set of timings (using Java under Eclipse on my older laptop with other stuff running...), where the "use x, y, z" was implemented by instantiating a Triple object with the three values and putting it in an ArrayList. (For these runs, N was set to 10,000, which produced 12,471 triples in each case.)
Version 4: 46 sec.
using square root: 134 sec.
array and map: 400 sec.
The "array and map" algorithm is essentially:
squares = array of i*i for i in 1 .. N
roots = map of i*i -> i for i in 1 .. N
for x in 1 .. N
for y in x+1 .. N
z = roots[squares[x] + squares[y]]
if z exists use x, y, z
The "using square root" algorithm is essentially:
for x in 1 .. N
for y in x+1 .. N
z = (int) sqrt(x * x + y * y)
if z * z == x * x + y * y then use x, y, z
The actual code for V4 is:
public Collection<Triple> byBetterWhileLoop() {
Collection<Triple> result = new ArrayList<Triple>(limit);
for (int x = 1; x < limit; ++x) {
int xx = x * x;
int y = x + 1;
int z = y + 1;
while (z <= limit) {
int zz = xx + y * y;
while (z * z < zz) {++z;}
if (z * z == zz && z <= limit) {
result.add(new Triple(x, y, z));
}
++y;
}
}
return result;
}
Note that x * x is calculated in the outer loop (although I didn't bother to cache z * z); similar optimizations are done in the other variations.
I'll be glad to provide the Java source code on request for the other variations I timed, in case I've mis-implemented anything.
|
In Python, why can a function modify some arguments as perceived by the caller, but not others?
|
I'm new to Python and am trying to understand its approach to variable scope. In this example, why is f() able to alter the value of x, as perceived within main(), but not the value of n?
def f(n, x):
n = 2
x.append(4)
print 'In f():', n, x
def main():
n = 1
x = [0,1,2,3]
print 'Before:', n, x
f(n, x)
print 'After: ', n, x
main()
Output:
Before: 1 [0, 1, 2, 3]
In f(): 2 [0, 1, 2, 3, 4]
After: 1 [0, 1, 2, 3, 4]
|
Some answers contain the word "copy" in a context of a function call. I find it confusing.
Python doesn't copy objects you pass during a function call ever.
Function parameters are names. When you call a function Python binds these parameters to whatever objects you pass (via names in a caller scope).
Objects can be mutable (like lists) or immutable (like integers, strings in Python). Mutable object you can change. You can't change a name, you just can bind it to another object.
Your example is not about scopes or namespaces, it is about naming and binding and mutability of an object in Python.
def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
n = 2 # put `n` label on `2` balloon
x.append(4) # call `append` method of whatever object `x` is referring to.
print 'In f():', n, x
x = [] # put `x` label on `[]` ballon
# x = [] has no effect on the original list that is passed into the function
Here are nice pictures on the difference between variables in other languages and names in Python.
|
How does python close files that have been gc'ed?
|
I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close:
>>> f = open('somefile.txt')
>>> del f
Just out of sheer curiosity, how does this work? I notice that file doesn't include a __del__ method.
|
In CPython, at least, files are closed when the file object is deallocated. See the file_dealloc function in Objects/fileobject.c in the CPython source. Dealloc methods are sort-of like __del__ for C types, except without some of the problems inherent to __del__.
|
Why not always use psyco for Python code?
|
psyco seems to be quite helpful in optimizing Python code, and it does it in a very non-intrusive way.
Therefore, one has to wonder. Assuming you're always on a x86 architecture (which is where most apps run these days), why not just always use psyco for all Python code? Does it make mistakes sometimes and ruins the correctness of the program? Increases the runtime for some weird cases?
Have you had any negative experiences with it? My most negative experience so far was that it made my code faster by only 15%. Usually it's better.
Naturally, using psyco is not a replacement for efficient algorithms and coding. But if you can improve the performance of your code for the cost of two lines (importing and calling psyco), I see no good reason not to.
|
1) The memory overhead is the main one, as described in other answers. You also pay the compilation cost, which can be prohibitive if you aren't selective. From the user reference:
Compiling everything is often overkill for medium- or large-sized applications. The drawbacks of compiling too much are in the time spent compiling, plus the amount of memory that this process consumes. It is a subtle balance to keep.
2) Performance can actually be harmed by Psyco compilation. Again from the user guide ("known bugs" section):
There are also performance bugs: situations in which Psyco slows down the code instead of accelerating it. It is difficult to make a complete list of the possible reasons, but here are a few common ones:
The built-in map and filter functions must be avoided and replaced by list comprehension. For example, map(lambda x: x*x, lst) should be replaced by the more readable but more recent syntax [x*x for x in lst].
The compilation of regular expressions doesn't seem to benefit from Psyco. (The execution of regular expressions is unaffected, since it is C code.) Don't enable Psyco on this module; if necessary, disable it explicitely, e.g. by calling psyco.cannotcompile(re.compile).
3) Finally, there are some relatively obscure situations where using Psyco will actually introduce bugs. Some of them are listed here.
|
Python "extend" for a dictionary
|
Which is the best way to extend a dictionary with another one? For instance:
>>> a = { "a" : 1, "b" : 2 }
>>> b = { "c" : 3, "d" : 4 }
>>> a
{'a': 1, 'b': 2}
>>> b
{'c': 3, 'd': 4}
I'm looking for any operation to obtain this avoiding for loop:
{ "a" : 1, "b" : 2, "c" : 3, "d" : 4 }
I wish to do something like:
a.extend(b) # This does not work
|
a.update(b)
Python Standard Library Documentation
|
Pause in Python
|
I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter.
After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output.
What is the most straightforward way to keep the interpreter window open until any key is pressed?
In batch files, one can end the script with pause. The closest thing to this I found in python is raw_input() which is sub-optimal because it requires pressing the return key (instead of any key).
Any ideas?
|
One way is to leave a raw_input() at the end so the script waits for you to press Enter before it terminates.
|
Instantiating a python class in C#
|
I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class?
The class looks (partially) like this:
class PokerCard:
"A card for playing poker, immutable and unique."
def __init__(self, cardName):
The test stub I wrote in C# is:
using System;
namespace pokerapp
{
class Program
{
static void Main(string[] args)
{
var card = new PokerCard(); // I also tried new PokerCard("Ah")
Console.WriteLine(card.ToString());
Console.ReadLine();
}
}
}
What do I have to do in order to instantiate this class in C#?
|
IronPython classes are not .NET classes. They are instances of IronPython.Runtime.Types.PythonType which is the Python metaclass. This is because Python classes are dynamic and support addition and removal of methods at runtime, things you cannot do with .NET classes.
To use Python classes in C# you will need to use the ObjectOperations class. This class allows you to operate on python types and instances in the semantics of the language itself. e.g. it uses the magic methods when appropriate, auto-promotes integers to longs etc. You can find out more about ObjectOperations by looking at the source or using reflector.
Here is an example. Calculator.py contains a simple class:
class Calculator(object):
def add(self, a, b):
return a + b
You can use it from your pre .NET 4.0 C# code like this:
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
ObjectOperations op = engine.Operations;
source.Execute(scope); // class object created
object klaz = scope.GetVariable("Calculator"); // get the class object
object instance = op.Call(klaz); // create the instance
object method = op.GetMember(instance, "add"); // get a method
int result = (int)op.Call(method, 4, 5); // call method and get result (9)
You will need to reference the assemblies IronPython.dll, Microsoft.Scripting and Microsoft.Scripting.Core.
C# 4 made this much easier with the new dynamic type.
ScriptEngine engine = Python.CreateEngine();
ScriptSource source = engine.CreateScriptSourceFromFile("Calculator.py");
ScriptScope scope = engine.CreateScope();
source.Execute(scope);
dynamic Calculator = scope.GetVariable("Calculator");
dynamic calc = Calculator();
int result = calc.add(4, 5);
If you are using Visual Studio 2010 or later with NuGet support simply execute this to download and reference the appropriate libraries.
Install-Package IronPython
|
Using only the DB part of Django
|
Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables?
If not, what would you recommend as "the Python equivalent of Hibernate"?
|
If you like Django's ORM, it's perfectly simple to use it "standalone"; I've written up several techniques for using parts of Django outside of a web context, and you're free to use any of them (or roll your own).
Shane above seems to be a bit misinformed on this and a few other points -- for example, Django can do multiple different databases, it just doesn't default to that (you need to do a custom manager on the models which use something other than the "main" DB, something that's not too hard and there are recipes floating around for it). It's true that Django itself doesn't do connection management/connection pooling, but personally I've always used external tools for that anyway (e.g., pgpool, which rocks harder than anything built in to an ORM ever could).
I'd suggest spending some time reading up and possibly trying a few likely Google searches (e.g., the post I linked you to comes up as the top result for "standalone Django script") to get a feel for what will actually best suit your needs and tastes -- it may be Django's ORM isn't right for you, and you shouldn't use it if it isn't, but unfortunately there's a lot of misinformation out there which muddies the waters.
Editing to respond to Shane:
Again, you seem to be misinformed: SQLAlchemy needs to be configured (i.e., told what DB to use, how to connect, etc.) before you can run queries with it, so how is the fact that Django needs similar configuration (accomplished via your choice of methods -- you do not need to have a full Django settings file) any disadvantage?
As for multiple DB support, you seem to be confused: the support is there at a low level. The query object -- not QuerySet, but the underlying Query object it will execute knows what DB it's connecting to, and accepts a DB connection as one of its initialization arguments. Telling one model to use one DB and another model to use another is as simple as setting up one method on a manager which passes the right connection info down into the Query. True, there's no higher-level API for this, but that's not the same as "no support" and not the same as "requires custom code" (unless you'd argue that configuring multiple DBs explicitly in SQLAlchemy, required if you want multiple DBs, is also "custom code").
As for whether you end up indirectly using things that aren't in django.db, well, so what? The fact that django.db imports bits of, say, django.utils because there are data structures and other bits of code which are useful for more than just an ORM is fine as far as I'm personally concerned; one might as well complain if something has external dependencies or makes use of standard Python libraries instead of being 100% self-contained.
|
How do I copy a string to the clipboard on Windows using Python?
|
I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?
|
Actually, pywin32 and ctypes seem to be an overkill for this simple task. Tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.
If all you need is to put some text to system clipboard, this will do it:
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.destroy()
And that's all, no need to mess around with platform-specific third-party libraries.
|
Python windows File Version attribute
|
Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.
|
Better to add a try/except in case the file has no version number attribute.
filever.py
from win32api import GetFileVersionInfo, LOWORD, HIWORD
def get_version_number (filename):
try:
info = GetFileVersionInfo (filename, "\\")
ms = info['FileVersionMS']
ls = info['FileVersionLS']
return HIWORD (ms), LOWORD (ms), HIWORD (ls), LOWORD (ls)
except:
return 0,0,0,0
if __name__ == '__main__':
import os
filename = os.environ["COMSPEC"]
print ".".join ([str (i) for i in get_version_number (filename)])
yourscript.py:
import os,filever
myPath="C:\\path\\to\\check"
for root, dirs, files in os.walk(myPath):
for file in files:
file = file.lower() # Convert .EXE to .exe so next line works
if (file.count('.exe') or file.count('.dll')): # Check only exe or dll files
fullPathToFile=os.path.join(root,file)
major,minor,subminor,revision=filever.get_version_number(fullPathToFile)
print "Filename: %s \t Version: %s.%s.%s.%s" % (file,major,minor,subminor,revision)
Cheers!
|
Python web programming
|
Good morning.
As the title indicates, I've got some questions about using python for web development.
What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, *nix and win environment.
My major concern when I last tried apache + mod_python + CherryPy was having to reload webserver to see the changes. Is it considered normal? For some reason cherrypy's autoreload didn't work at all.
What is the best setup to deploy a working Python app to production and why? I'm now using lighttpd for my PHP web apps, but how would it do for python compared to nginx for example?
Is it worth diving straight with a framework or to roll something simple of my own? I see that Django has got quite a lot of fans, but I'm thinking it would be overkill for my needs, so I've started looking into CherryPy.
How exactly are Python apps served if I have to reload httpd to see the changes? Something like a permanent process spawning child processes, with all the major file includes happening on server start and then just lazy loading needed resources?
Python supports multithreading, do I need to look into using that for a benefit when developing web apps? What would be that benefit and in what situations?
Big thanks!
|
What is the best setup for a development environment?
Doesn't much matter. We use Django, which runs in Windows and Unix nicely. For production, we use Apache in Red Hat.
Is having to reload webserver to see the changes considered normal?
Yes. Not clear why you'd want anything different. Web application software shouldn't be dynamic. Content yes. Software no.
In Django, we develop without using a web server of any kind on our desktop. The Django "runserver" command reloads the application under most circumstances. For development, this works great. The times when it won't reload are when we've damaged things so badly that the app doesn't properly.
What is the best setup to deploy a working Python app to production and why?
"Best" is undefined in this context. Therefore, please provide some qualification for "nest" (e.g., "fastest", "cheapest", "bluest")
Is it worth diving straight with a framework or to roll something simple of my own?
Don't waste time rolling your own. We use Django because of the built-in admin page that we don't have to write or maintain. Saves mountains of work.
How exactly are Python apps served if I have to reload httpd to see the changes?
Two methods:
Daemon - mod_wsgi or mod_fastcgi have a Python daemon process to which they connect. Change your software. Restart the daemon.
Embedded - mod_wsgi or mod_python have an embedded mode in which the Python interpreter is inside the mod, inside Apache. You have to restart httpd to restart that embedded interpreter.
Do I need to look into using multi-threaded?
Yes and no. Yes you do need to be aware of this. No, you don't need to do very much. Apache and mod_wsgi and Django should handle this for you.
|
Similar to Pass in Python for C#
|
In python we can ..
a = 5
if a == 5:
pass #Do Nothing
else:
print "Hello World"
I wonder if it a similar way to do this in C#
|
Use empty braces.
int a = 5;
if (a == 5) {}
else {
Console.Write("Hello World");
}
|
How can you profile a Python script?
|
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to __main__.
What is a good way to profile how long a python program takes to run?
|
Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations.
You can call it from within your code, or from the interpreter, like this:
import cProfile
cProfile.run('foo()')
Even more usefully, you can invoke the cProfile when running a script:
python -m cProfile myscript.py
To make it even easier, I made a little batch file called 'profile.bat':
python -m cProfile %1
So all I have to do is run:
profile euler048.py
And I get this:
1007 function calls in 0.061 CPU seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.061 0.061 <string>:1(<module>)
1000 0.051 0.000 0.051 0.000 euler048.py:2(<lambda>)
1 0.005 0.005 0.061 0.061 euler048.py:2(<module>)
1 0.000 0.000 0.061 0.061 {execfile}
1 0.002 0.002 0.053 0.053 {map}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler objects}
1 0.000 0.000 0.000 0.000 {range}
1 0.003 0.003 0.003 0.003 {sum}
EDIT: Updated link to a good video resource from PyCon 2013: http://lanyrd.com/2013/pycon/scdywg/
|
py2exe + sqlalchemy + sqlite problem
|
I am playing around with getting some basic stuff to work in Python before i go into full speed dev mode. Here are the specifics:
Python 2.5.4
PyQt4 4.4.3
SqlAlchemy 0.5.2
py2exe 0.6.9
setuptools 0.6c9
pysqlite 2.5.1
setup.py:
from distutils.core import setup
import py2exe
setup(windows=[{"script" : "main.py"}], options={"py2exe" : {"includes" : ["sip", "PyQt4.QtSql","sqlite3"],"packages":["sqlite3",]}})
py2exe appears to generate the .exe file correctly, but when i execute dist/main.exe i get this in the main.exe.log
Traceback (most recent call last):
File "main.py", line 18, in <module>
File "main.py", line 14, in main
File "db\manager.pyc", line 12, in __init__
File "sqlalchemy\engine\__init__.pyc", line 223, in create_engine
File "sqlalchemy\engine\strategies.pyc", line 48, in create
File "sqlalchemy\engine\url.pyc", line 91, in get_dialect
ImportError: No module named sqlite
I've been googling my heart out, but can't seem to find any solutions to this. If i can't get this to work now, my hopes of using Python for this project will be dashed and i will start over using Ruby... (not that there is anything wrong with Ruby, i just wanted to use this project as a good way to teach myself Python)
|
you need to include the sqlalchemy.databases.sqlite package
setup(
windows=[{"script" : "main.py"}],
options={"py2exe" : {
"includes": ["sip", "PyQt4.QtSql"],
"packages": ["sqlalchemy.databases.sqlite"]
}})
|
How to import classes defined in __init__.py
|
I am trying to organize some modules for my own use. I have something like this:
lib/
__init__.py
settings.py
foo/
__init__.py
someobject.py
bar/
__init__.py
somethingelse.py
In lib/__init__.py, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in __init__.py.
Rather than say:
lib/
__init__.py
settings.py
helperclass.py
foo/
__init__.py
someobject.py
bar/
__init__.py
somethingelse.py
from lib.settings import Values
from lib.helperclass import Helper
I want something like this:
lib/
__init__.py #Helper defined in this file
settings.py
foo/
__init__.py
someobject.py
bar/
__init__.py
somethingelse.py
from lib.settings import Values
from lib import Helper
Is it possible, or do I have to separate the class into another file?
EDIT
OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py?
The example here describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?
|
'lib/'s parent directory must be in sys.path.
Your 'lib/__init__.py' might look like this:
from . import settings # or just 'import settings' on old Python versions
class Helper(object):
pass
Then the following example should work:
from lib.settings import Values
from lib import Helper
Answer to the edited version of the question:
__init__.py defines how your package looks from outside. If you need to use Helper in settings.py then define Helper in a different file e.g., 'lib/helper.py'.
.
| `-- import_submodule.py
`-- lib
|-- __init__.py
|-- foo
| |-- __init__.py
| `-- someobject.py
|-- helper.py
`-- settings.py
2 directories, 6 files
The command:
$ python import_submodule.py
Output:
settings
helper
Helper in lib.settings
someobject
Helper in lib.foo.someobject
# ./import_submodule.py
import fnmatch, os
from lib.settings import Values
from lib import Helper
print
for root, dirs, files in os.walk('.'):
for f in fnmatch.filter(files, '*.py'):
print "# %s/%s" % (os.path.basename(root), f)
print open(os.path.join(root, f)).read()
print
# lib/helper.py
print 'helper'
class Helper(object):
def __init__(self, module_name):
print "Helper in", module_name
# lib/settings.py
print "settings"
import helper
class Values(object):
pass
helper.Helper(__name__)
# lib/__init__.py
#from __future__ import absolute_import
import settings, foo.someobject, helper
Helper = helper.Helper
# foo/someobject.py
print "someobject"
from .. import helper
helper.Helper(__name__)
# foo/__init__.py
import someobject
|
Run a linux system command as a superuser, using a python script
|
I have got postfix installed on my machine and I am updating virtual_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual_alias, I am running the command:sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfileBut I am getting the error:sudo: sorry, you must have a tty to run sudo
I want to run the mentioned sudo command in a non-human way(meaning, I am running this system command from a python script.). So how do I get this command run programmatically?
|
You can either run your python script as root itself - then you won't need to add privilege to reload postfix.
Or you can configure sudo to not need a password for /etc/init.d/postfix.
sudo configuration (via visudo) allows NOPASSWD: to allow the command without a password. See http://www.sudo.ws/sudo/man/sudoers.html#nopasswd_and_passwd
<username> ALL = NOPASSWD: /etc/init.d/postfix
or something similar.
|
Is it possible to generate and return a ZIP file with App Engine?
|
I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it.
Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generated and and sent in a single request/response cycle.
Does the Python zip module even exist in the App Engine environment?
|
zipfile is available at appengine and reworked example follows:
from contextlib import closing
from zipfile import ZipFile, ZIP_DEFLATED
from google.appengine.ext import webapp
from google.appengine.api import urlfetch
def addResource(zfile, url, fname):
# get the contents
contents = urlfetch.fetch(url).content
# write the contents to the zip file
zfile.writestr(fname, contents)
class OutZipfile(webapp.RequestHandler):
def get(self):
# Set up headers for browser to correctly recognize ZIP file
self.response.headers['Content-Type'] ='application/zip'
self.response.headers['Content-Disposition'] = \
'attachment; filename="outfile.zip"'
# compress files and emit them directly to HTTP response stream
with closing(ZipFile(self.response.out, "w", ZIP_DEFLATED)) as outfile:
# repeat this for every URL that should be added to the zipfile
addResource(outfile,
'https://www.google.com/intl/en/policies/privacy/',
'privacy.html')
addResource(outfile,
'https://www.google.com/intl/en/policies/terms/',
'terms.html')
|
Python regular expression matching a multiline block of text
|
I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)
some Varying TEXT\n
\n
DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n
[more of the above, ending with a newline]\n
[yep, there is a variable number of lines here]\n
\n
(repeat the above a few hundred times).
I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later).
I've tried with a few approaches:
re.compile(r"^>(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts
re.compile(r"(^[^>][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines
and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text.
I'd like match.group(1) to be some_Varying_Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.
If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.
|
Try this:
re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)
I think your biggest problem is that you're expecting the ^ and $ anchors to match linefeeds, but they don't. In multiline mode, ^ matches the position immediately following a newline and $ matches the position immediately preceding a newline.
Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:
re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)
BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.
|
Python Daemon Packaging Best Practices
|
I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled?
Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. init scripts on linux, services on windows, launchd on os x)?
|
The best tool I found for helping with init.d scripts is "start-stop-daemon". It will run any application, monitor run/pid files, create them when necessary, provide ways to stop the daemon, set process user/group ids, and can even background your process.
For example, this is a script which can start/stop a wsgi server:
#! /bin/bash
case "$1" in
start)
echo "Starting server"
# Activate the virtual environment
. /home/ali/wer-gcms/g-env/bin/activate
# Run start-stop-daemon, the $DAEMON variable contains the path to the
# application to run
start-stop-daemon --start --pidfile $WSGI_PIDFILE \
--user www-data --group www-data \
--chuid www-data \
--exec "$DAEMON"
;;
stop)
echo "Stopping WSGI Application"
# Start-stop daemon can also stop the application by sending sig 15
# (configurable) to the process id contained in the run/pid file
start-stop-daemon --stop --pidfile $WSGI_PIDFILE --verbose
;;
*)
# Refuse to do other stuff
echo "Usage: /etc/init.d/wsgi-application.sh {start|stop}"
exit 1
;;
esac
exit 0
You can also see there an example of how to use it with a virtualenv, which I would always recommend.
|
imploding a list for use in a python MySQLDB IN clause
|
I know how to map a list to a string:
foostring = ",".join( map(str, list_of_ids) )
And I know that I can use the following to get that string into an IN clause:
cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring))
What I need is to accomplish the same thing SAFELY (avoiding SQL injection) using MySQLDB. In the above example because foostring is not passed as an argument to execute, it is vulnerable. I also have to quote and escape outside of the mysql library.
(There is a related SO question, but the answers listed there either do not work for MySQLDB or are vulnerable to SQL injection.)
|
Use the list_of_ids directly:
format_strings = ','.join(['%s'] * len(list_of_ids))
cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings,
tuple(list_of_ids))
That way you avoid having to quote yourself, and avoid all kinds of sql injection.
Note that the data (list_of_ids) is going directly to mysql's driver, as a parameter (not in the query text) so there is no injection. You can leave any chars you want in the string, no need to remove or quote chars.
|
Python or IronPython
|
How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without?
Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) that would make it more attractive an option?
|
There are a number of important differences:
Interoperability with other .NET languages. You can use other .NET libraries from an IronPython application, or use IronPython from a C# application, for example. This interoperability is increasing, with a movement toward greater support for dynamic types in .NET 4.0. For a lot of detail on this, see these two presentations at PDC 2008.
Better concurrency/multi-core support, due to lack of a GIL. (Note that the GIL doesn't inhibit threading on a single-core machine---it only limits performance on multi-core machines.)
Limited ability to consume Python C extensions. The Ironclad project is making significant strides toward improving this---they've nearly gotten Numpy working!
Less cross-platform support; basically, you've got the CLR and Mono. Mono is impressive, though, and runs on many platforms---and they've got an implementation of Silverlight, called Moonlight.
Reports of improved performance, although I have not looked into this carefully.
Feature lag: since CPython is the reference Python implementation, it has the "latest and greatest" Python features, whereas IronPython necessarily lags behind. Many people do not find this to be a problem.
|
Any reasons not to use SQLObject over SQLAlchemy?
|
I don't expect to need much more than basic CRUD type functionality. I know that SQLAlchemy is more flexible, but the syntax etc of sqlobject just seem to be a bit easier to get up and going with.
|
I think SQLObject is more pythonic/simpler, so if it works for you, then stick with it.
SQLAlchemy takes a little more to learn, but can do more advanced things if you need that.
|
Why doesn't Python have static variables?
|
There is a questions asking how to simulate static variables in python.
Also, on the web one can find many different solutions to create static variables. (Though I haven't seen one that I like yet.)
Why doesn't Python support static variables in methods? Is this considered unpythonic or has it something to do with Python's syntax?
Edit:
I asked specifically about the why of the design decision and I haven't provided any code example because I wanted to avoid explanation to simulate static variables.
|
The idea behind this omission is that static variables are only useful in two situations: when you really should be using a class and when you really should be using a generator.
If you want to attach stateful information to a function, what you need is a class. A trivially simple class, perhaps, but a class nonetheless:
def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
do_stuff(my_bar)
foo(bar)
foo()
# -- becomes ->
class Foo(object):
def __init__(self, bar):
self.bar = bar
def __call__(self):
do_stuff(self.bar)
foo = Foo(bar)
foo()
foo()
If you want your function's behavior to change each time it's called, what you need is a generator:
def foo(bar):
static my_bar # doesn't work
if not my_bar:
my_bar = bar
my_bar = my_bar * 3 % 5
return my_bar
foo(bar)
foo()
# -- becomes ->
def foogen(bar):
my_bar = bar
while True:
my_bar = my_bar * 3 % 5
yield my_bar
foo = foogen(bar)
foo.next()
foo.next()
Of course, static variables are useful for quick-and-dirty scripts where you don't want to deal with the hassle of big structures for little tasks. But there, you don't really need anything more than global â it may seem a but kludgy, but that's okay for small, one-off scripts:
def foo():
global bar
do_stuff(bar)
foo()
foo()
|
Equation parsing in Python
|
How can I (easily) take a string such as "sin(x)*x^2" which might be entered by a user at runtime and produce a Python function that could be evaluated for any value of x?
|
Python's own internal compiler can parse this, if you use Python notation.
If your change the notation slightly, you'll be happier.
import compiler
eq= "sin(x)*x**2"
ast= compiler.parse( eq )
You get an abstract syntax tree that you can work with.
|
Choosing between different switch-case replacements in Python - dictionary or if-elif-else?
|
I recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as:
Using a dictionary (Many variants)
Using a Tuple
Using a function decorator (http://code.activestate.com/recipes/440499/)
Using Polymorphism (Recommended method instead of type checking objects)
Using an if-elif-else ladder
Someone even recommended the Visitor pattern (Possibly Extrinsic)
Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice).
Here is the specific problem:
(1)
def _setCurrentCurve(self, curve):
if curve == "sine":
self.currentCurve = SineCurve(startAngle = 0, endAngle = 14,
lineColor = (0.0, 0.0, 0.0), expansionFactor = 1,
centerPos = (0.0, 0.0))
elif curve == "quadratic":
self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0))
This method is called by a qt-slot in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs...
(2)
This second piece of code is a qt-slot that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict?
Here is the aforementioned slot-
def propertyChanged(self, name, value):
"""A Qt slot, to react to changes of SineCurve's properties."""
if name == "amplitude":
self.amplitude = value
elif name == "expansionFactor":
self.expansionFactor = value
elif name == "startAngle":
self.startAngle = value
elif name == "endAngle":
self.endAngle = value
For reference, here is the code for connecting to the above slot -
def _connectToPage(self, page):
for connectionData in page.getConnectibles():
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
lambda value, name = connectionData["property"]:\
self.currentCurve.propertyChanged(name, value))
self.connect(connectionData["object"],
SIGNAL(connectionData["signal"]),
self.hackedDisplayArea.update)
Note - The self.endAngle etc. are initialized in the constructor.
As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere?
My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use if-elif-else, when to use each of the other options?
|
Sigh. Too much hand-wringing over the wrong part of the problem. The switch statement is not the issue. There are many ways of expressing "alternative" that don't add meaning.
The issue is meaning -- not technical statement choices.
There are three common patterns.
Mapping a key to an object. Use a dictionary if it is almost totally static and you have a mapping between a simple key and another more complex thing. Building a dictionary on the fly each time you need it is silly. You can use this if it's what you mean: your "conditions" are simple, static key values that map to objects.
Variant behavior among subclasses. Use Polymorphism instead of type checking objects. Correct. If you have similar objects in multiple classes with variant behavior, they should be polymorphic. Use this as often as possible.
Other variant behavior. Use an if-elif-else ladder. Use this when you don't have largely static key-to-value mapping. Use this when the conditions are complex, or you mean procedures, not objects.
Everything else is just tricky code that can achieve similar results.
Using a Tuple. This is just dictionary without the mapping. This requires search, and search should be avoided whenever possible. Don't do this, it's inefficient. Use a dictionary.
Using a function decorator (http://code.activestate.com/recipes/440499/). Icky. This conceals the if-elif-elif nature of the problem you're solving. Don't do this, it isn't obvious that the choices are exclusive. Use anything else.
Someone even recommended the Visitor pattern. Use this when you have an object which follows the Composite design pattern. This depends on polymorphism to work, so it's not really a different solution.
|
What's the Python function like sum() but for multiplication? product()?
|
Python's sum() function returns the sum of numbers in an iterable.
sum([3,4,5]) == 3 + 4 + 5 == 12
I'm looking for the function that returns the product instead.
somelib.somefunc([3,4,5]) == 3 * 4 * 5 == 60
I'm pretty sure such a function exists, but I can't find it.
|
Actually, Guido vetoed the idea: http://bugs.python.org/issue1093
But, as noted in that issue, you can make one pretty easily:
from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator
reduce(operator.mul, (3, 4, 5), 1)
|
How do I use python for web development without relying on a framework?
|
I know the various frameworks have their benefits, but I personally want my web development in python to be as straight-forward as possible: less writing to the framework, more writing python.
The only thing I have found so far that lets me do this in the most obvious way possible is web.py but I have slight concerns on its performance.
For those of you using nginx(or another flavour)+mod_wsgi+web.py... how's performance? Can it be improved further?
For those of you who have used web.py, liked the idea and went on to write something better or found something better... care to point me to the source?
I'd like to hear about all the conspicuous, minimal yet powerful approaches.
|
The way to go is wsgi.
WSGI is the Web Server Gateway Interface. It is a specification for web servers and application servers to communicate with web applications (though it can also be used for more than that). It is a Python standard, described in detail in PEP 333.
All current frameworks support wsgi. A lot of webservers support it also (apache included, through mod_wsgi). It is the way to go if you want to write your own framework.
Here is hello world, written to wsgi directly:
def application(environ, start_response):
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
Put this in a file.py, point your mod_wsgi apache configuration to it, and it will run. Pure python. No imports. Just a python function.
If you are really writing your own framework, you could check werkzeug. It is not a framework, but a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility modules. It includes a powerful debugger, full featured request and response objects, HTTP utilities to handle entity tags, cache control headers, HTTP dates, cookie handling, file uploads, a powerful URL routing system and a bunch of community contributed addon modules. Takes the boring part out of your hands.
|
Converting an object into a subclass in Python?
|
Lets say I have a library function that I cannot change that produces an object of class A, and I have created a class B that inherits from A.
What is the most straightforward way of using the library function to produce an object of class B?
edit- I was asked in a comment for more detail, so here goes:
PyTables is a package that handles hierarchical datasets in python. The bit I use most is its ability to manage data that is partially on disk. It provides an 'Array' type which only comes with extended slicing, but I need to select arbitrary rows. Numpy offers this capability - you can select by providing a boolean array of the same length as the array you are selecting from. Therefore, I wanted to subclass Array to add this new functionality.
In a more abstract sense this is a problem I have considered before. The usual solution is as has already been suggested- Have a constructor for B that takes an A and additional arguments, and then pulls out the relevant bits of A to insert into B. As it seemed like a fairly basic problem, I asked to question to see if there were any standard solutions I wasn't aware of.
|
This can be done if the initializer of the subclass can handle it, or you write an explicit upgrader. Here is an example:
class A(object):
def __init__(self):
self.x = 1
class B(A):
def __init__(self):
super(B, self).__init__()
self._init_B()
def _init_B(self):
self.x += 1
a = A()
b = a
b.__class__ = B
b._init_B()
assert b.x == 2
|
Why does @foo.setter in Python not work for me?
|
So, I'm playing with decorators in Python 2.6, and I'm having some trouble getting them to work. Here is my class file:
class testDec:
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
What I thought this meant is to treat x like a property, but call these functions on get and set. So, I fired up IDLE and checked it:
>>> from testDec import testDec
from testDec import testDec
>>> t = testDec()
t = testDec()
>>> t.x
t.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testDec.py", line 18, in x
return self._x
AttributeError: testDec instance has no attribute '_x'
>>> t.x = 5
t.x = 5
>>> t.x
t.x
5
Clearly the first call works as expected, since I call the getter, and there is no default value, and it fails. OK, good, I understand. However, the call to assign t.x = 5 seems to create a new property x, and now the getter doesn't work!
What am I missing?
|
You seem to be using classic old-style classes. In order for properties to work correctly you need to use new-style classes instead (inherit from object). Just declare your class as MyClass(object):
class testDec(object):
@property
def x(self):
print 'called getter'
return self._x
@x.setter
def x(self, value):
print 'called setter'
self._x = value
It works:
>>> k = testDec()
>>> k.x
called getter
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/devel/class_test.py", line 6, in x
return self._x
AttributeError: 'testDec' object has no attribute '_x'
>>> k.x = 5
called setter
>>> k.x
called getter
5
>>>
|
Cheap exception handling in Python?
|
I read in an earlier answer that exception handling is cheap in Python so we shouldn't do pre-conditional checking.
I have not heard of this before, but I'm relatively new to Python. Exception handling means a dynamic call and a static return, whereas an if statement is static call, static return.
How can doing the checking be bad and the try-except be good, seems to be the other way around. Can someone explain this to me?
|
Don't sweat the small stuff. You've already picked one of the slower scripting languages out there, so trying to optimize down to the opcode is not going to help you much. The reason to choose an interpreted, dynamic language like Python is to optimize your time, not the CPU's.
If you use common language idioms, then you'll see all the benefits of fast prototyping and clean design and your code will naturally run faster as new versions of Python are released and the computer hardware is upgraded.
If you have performance problems, then profile your code and optimize your slow algorithms. But in the mean time, use exceptions for exceptional situations since it will make any refactoring you ultimately do along these lines a lot easier.
|
When is it (not) appropriate to bundle dependencies with an application?
|
Summary
I recently had a conversation with the creator of a framework that one of my applications depends on. During that conversation he mentioned as a sort of aside that it would make my life simpler if I just bundled his framework with my application and delivered to the end user a version that I knew was consistent with my code. Intuitively I have always tried to avoid doing this and, in fact, I have taken pains to segment my own code so that portions of it could be redistributed without taking the entire project (even when there was precious little chance anyone would ever reuse any of it). However, after mulling it over for some time I have not been able to come up with a particularly good reason why I do this. In fact, now that I have thought about it, I'm seeing a pretty compelling case to bundle all my smaller dependencies. I have come up with a list of pros and cons and I'm hoping someone can point out anything that I'm missing.
Pros
Consistency of versions means easier
testing and troubleshooting.
Application may reach a wider
audience since there appear to be
fewer components to install.
Small tweaks to the dependency can
more easily be made downstream and
delivered with the application,
rather than waiting for them to
percolate into the upstream code base.
Cons
More complex packaging process to include
dependencies.
User may end up with multiple copies
of a dependency on their machine.
Per bortzmeyer's response, there are potential security concerns with not being able to upgrade individual components.
Notes
For reference, my application is written in Python and the dependencies I'm referencing are "light", by which I mean small and not in very common use. (So they do not exist on all machines or even in all repositories.) And when I say "package with" my application, I mean distribute under my own source tree, not install with a script that resides inside my package, so there would be no chance of conflicting versions. I am also developing solely on Linux so there are no Windows installation issues to worry about.
All that being said, I am interested in hearing any thoughts on the broader (language-independent) issue of packaging dependencies as well. Is there something I am missing or is this an easy decision that I am just over-thinking?
Addendum 1
It is worth mentioning that I am also quite sensitive to the needs of downstream packagers. I would like it to be as straightforward as possible to wrap the application up in a distribution-specific Deb or RPM.
|
I favor bundling dependencies, if it's not feasible to use a system for automatic dependency resolution (i.e. setuptools), and if you can do it without introducing version conflicts. You still have to consider your application and your audience; serious developers or enthusiasts are more likely to want to work with a specific (latest) version of the dependency. Bundling stuff in may be annoying for them, since it's not what they expect.
But, especially for end-users of an application, I seriously doubt most people enjoy having to search for dependencies. As far as having duplicate copies goes, I would much rather spend an extra 10 milliseconds downloading some additional kilobytes, or spend whatever fraction of a cent on the extra meg of disk space, than spend 10+ minutes searching through websites (which may be down), downloading, installing (which may fail if versions are incompatible), etc.
I don't care how many copies of a library I have on my disk, as long as they don't get in each others' way. Disk space is really, really cheap.
|
Searching a list of objects in Python
|
Let's assume I'm creating a simple class to work similar to a C-style struct, to just hold data elements. I'm trying to figure out how to search the list of objects for objects with a certain attribute. Below is a trivial example to illustrate what I'm trying to do.
For instance:
class Data:
pass
myList = []
for i in range(20):
data = Data()
data.n = i
data.n_squared = i * i
myList.append(data)
How would I go about searching the myList list to determine if it contains an element with n == 5?
I've been Googling and searching the Python docs, and I think I might be able to do this with a list comprehension, but I'm not sure. I might add that I'm having to use Python 2.4.3 by the way, so any new gee-whiz 2.6 or 3.x features aren't available to me.
|
You can get a list of all matching elements with a list comprehension:
[x for x in myList if x.n == 30] # list of all elements with .n==30
If you simply want to determine if the list contains any element that matches and do it (relatively) efficiently, you can do
def contains(list, filter):
for x in list:
if filter(x):
return True
return False
if contains(myList, lambda x: x.n == 3) # True if any element has .n==3
# do stuff
|
AppEngine: Query datastore for records with value
|
I created a new property for my db model in the Google App Engine Datastore.
Old:
class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
New:
class Logo(db.Model):
name = db.StringProperty()
image = db.BlobProperty()
is_approved = db.BooleanProperty(default=False)
How to query for the Logo records, which to not have the 'is_approved' value set?
I tried
logos.filter("is_approved = ", None)
but it didn't work.
In the Data Viewer the new field values are displayed as .
|
According to the App Engine documentation on Queries and Indexes, there is a distinction between entities that have no value for a property, and those that have a null value for it; and "Entities Without a Filtered Property Are Never Returned by a Query." So it is not possible to write a query for these old records.
A useful article is Updating Your Model's Schema, which says that the only currently-supported way to find entities missing some property is to examine all of them. The article has example code showing how to cycle through a large set of entities and update them.
|
How to match a text node then follow parent nodes using XPath
|
I'm trying to parse some HTML with XPath. Following the simplified XML example below, I want to match the string 'Text 1', then grab the contents of the relevant content node.
<doc>
<block>
<title>Text 1</title>
<content>Stuff I want</content>
</block>
<block>
<title>Text 2</title>
<content>Stuff I don't want</content>
</block>
</doc>
My Python code throws a wobbly:
>>> from lxml import etree
>>>
>>> tree = etree.XML("<doc><block><title>Text 1</title><content>Stuff
I want</content></block><block><title>Text 2</title><content>Stuff I d
on't want</content></block></doc>")
>>>
>>> # get all titles
... tree.xpath('//title/text()')
['Text 1', 'Text 2']
>>>
>>> # match 'Text 1'
... tree.xpath('//title/text()="Text 1"')
True
>>>
>>> # Follow parent from selected nodes
... tree.xpath('//title/text()/../..//text()')
['Text 1', 'Stuff I want', 'Text 2', "Stuff I don't want"]
>>>
>>> # Follow parent from selected node
... tree.xpath('//title/text()="Text 1"/../..//text()')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lxml.etree.pyx", line 1330, in lxml.etree._Element.xpath (src/
lxml/lxml.etree.c:14542)
File "xpath.pxi", line 287, in lxml.etree.XPathElementEvaluator.__ca
ll__ (src/lxml/lxml.etree.c:90093)
File "xpath.pxi", line 209, in lxml.etree._XPathEvaluatorBase._handl
e_result (src/lxml/lxml.etree.c:89446)
File "xpath.pxi", line 194, in lxml.etree._XPathEvaluatorBase._raise
_eval_error (src/lxml/lxml.etree.c:89281)
lxml.etree.XPathEvalError: Invalid type
Is this possible in XPath? Do I need to express what I want to do in a different way?
|
Do you want that?
//title[text()='Text 1']/../content/text()
|
How to pass information using an HTTP redirect (in Django)
|
I have a view that accepts a form submission and updates a model.
After updating the model, I want to redirect to another page, and I want a message such as "Field X successfully updated" to appear on this page.
How can I "pass" this message to the other page? HttpResponseRedirect only accepts a URL. I've seen this done before on other sites. How is this accomplished?
|
This is a built-in feature of Django, called "messages"
See http://docs.djangoproject.com/en/dev/topics/auth/#messages
From the documentation:
A message is associated with a User.
There's no concept of expiration or
timestamps.
Messages are used by the Django admin
after successful actions. For example,
"The poll Foo was created
successfully." is a message.
|
Python string prints as [u'String']
|
This will surely be an easy one but it is really bugging me.
I have a script that reads in a webpage and uses Beautiful Soup to parse it. From the soup I extract all the links as my final goal is to print out the link.contents.
All of the text that I am parsing is ASCII. I know that Python treats strings as unicode, and I am sure this is very handy, just of no use in my wee script.
Every time I go to print out a variable that holds 'String' I get [u'String'] printed to the screen. Is there a simple way of getting this back into just ascii or should I write a regex to strip it?
|
[u'ABC'] would be a one-element list of unicode strings. Beautiful Soup always produces Unicode. So you need to convert the list to a single unicode string, and then convert that to ASCII.
I don't know exaxtly how you got the one-element lists; the contents member would be a list of strings and tags, which is apparently not what you have. Assuming that you really always get a list with a single element, and that your test is really only ASCII you would use this:
soup[0].encode("ascii")
However, please double-check that your data is really ASCII. This is pretty rare. Much more likely it's latin-1 or utf-8.
soup[0].encode("latin-1")
soup[0].encode("utf-8")
Or you ask Beautiful Soup what the original encoding was and get it back in this encoding:
soup[0].encode(soup.originalEncoding)
|
How to remove the left part of a string?
|
I have some simple python code that searches files for a string e.g. path=c:\path, whereby the c:\path may vary. The current code is:
def findPath( i_file) :
lines = open( i_file ).readlines()
for line in lines :
if line.startswith( "Path=" ) :
return # what to do here in order to get line content after "Path=" ?
What is a simple way to get a string text after Path=?
Is there a simple method, without closures, reflection or other esoteric things ?
|
If the string is fixed you can simply use:
if line.startswith("Path="):
return line[5:]
which gives you everything from position 5 on in the string (a string is also a sequence so these sequence operators work here, too).
Or you can split the line at the first =:
if "=" in line:
param, value = line.split("=",1)
Then param is "Path" and value is the rest after the first =.
|
mkdir -p functionality in Python
|
Is there a way to get functionality similar to mkdir -p on the shell from within Python. I am looking for a solution other than a system call. I am sure the code is less than 20 lines, and I am wondering if someone has already written it?
|
mkdir -p functionality as follows:
import errno
import os
def mkdir_p(path):
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
Update
For Python ⥠3.2, os.makedirs has an optional third argument exist_ok that, when true, enables the mkdir -p functionality âunless mode is provided and the existing directory has different permissions than the intended ones; in that case, OSError is raised as previously.
|
Python error when using urllib.open
|
When I run this:
import urllib
feed = urllib.urlopen("http://www.yahoo.com")
print feed
I get this output in the interactive window (PythonWin):
<addinfourl at 48213968 whose fp = <socket._fileobject object at 0x02E14070>>
I'm expecting to get the source of the above URL. I know this has worked on other computers (like the ones at school) but this is on my laptop and I'm not sure what the problem is here. Also, I don't understand this error at all. What does it mean? Addinfourl? fp? Please help.
|
Try this:
print feed.read()
See Python docs here.
|
Why does Google Search return HTTP Error 403?
|
Consider the following Python code:
30 url = "http://www.google.com/search?hl=en&safe=off&q=Monkey"
31 url_object = urllib.request.urlopen(url);
32 print(url_object.read());
When this is run, an Exception is thrown:
File "/usr/local/lib/python3.0/urllib/request.py", line 485, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 403: Forbidden
However, when this is put into a browser, the search returns as expected. What's going on here? How can I overcome this so I can search Google programmatically?
Any thoughts?
|
If you want to do Google searches "properly" through a programming interface, take a look at Google APIs. Not only are these the official way of searching Google, they are also not likely to change if Google changes their result page layout.
|
BOO Vs IronPython
|
What is the difference between IronPython and BOO? Is there a need for 2 Python-like languages?
|
IronPython is designed to be a faithful implementation of Python on the .NET platform. Version 1 targets Python 2.4 for compatibility, and version 2 targets version 2.5 (although most of the Python standard library modules implemented in C aren't supported).
Boo's stated aim is to be a "wrist-friendly [dynamic] language for the CLI." It takes a lot of inspiration from Python, but diverges on four main points:
It's designed specifically to take good advantage of the .NET platform
The designer diverges from Python syntax where he doesn't agree with the design decisions (most notably, lack of explicit self)
The language is explicitly designed to be "wrist friendly" -- that is, to minimize the need for the Shift key or other multi-key combinations to be used.
Boo is statically typed by default, but allows optional duck typing.
There are some other minor differences in implementation/performance, but the divergent design goals above should (IMO) inform your choice of languages.
Two more things to take into account are maturity and community. Python is much more mature than Boo, and has a much larger community. IronPython also has the explicit blessing of Microsoft.
|
VIM: Save and Run at the same time?
|
I do a lot of Python quick simulation stuff and I'm constantly saving (:w) and then running (:!!). I'm wondering, is there a way to combine these actions. Maybe a "save and run" command.
Thanks for your help.
|
Okay, the simplest form of what you're looking for is the pipe command. It allows you to run multiple cmdline commands on the same line. In your case, the two commands are write \w\ and execute current file \! %:p\. If you have a specific command you run for you current file, the second command becomes, e.g. \!python %:p\. So, the simplest answer to you question becomes:
:w | ! %:p
^ ^ ^
| | |--Execute current file
| |--Chain two commands
|--Save current file
One last thing to note is that not all commands can be chained. According to the Vim docs, certain commands accept a pipe as an argument, and thus break the chain...
|
Python Table engine binding for Tokyo Cabinet
|
I am looking for python bindings for Table engine of Tokyo cabinet. I tried Pytc but can only find Hash and B-tree engine support. Is there any other bindings available?
|
Here is an implementation of search of table engine using PyTyrant:
http://github.com/ericflo/pytyrant/tree/master
|
How to write meaningful docstrings?
|
What, in Your opinion is a meaningful docstring? What do You expect to be described there?
For example, consider this Python class's __init__:
def __init__(self, name, value, displayName=None, matchingRule="strict"):
"""
name - field name
value - field value
displayName - nice display name, if empty will be set to field name
matchingRule - I have no idea what this does, set to strict by default
"""
Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted).
|
I agree with "Anything that you can't tell from the method's signature". It might also mean to explain what a method/function returns.
You might also want to use Sphinx (and reStructuredText syntax) for documentation purposes inside your docstrings. That way you can include this in your documentation easily. For an example check out e.g. repoze.bfg which uses this extensively (example file, documentation example).
Another thing one can put in docstrings is also doctests. This might make sense esp. for module or class docstrings as you can also show that way how to use it and have this testable at the same time.
|
Do many Python libraries have relatively low code quality?
|
Edit: Since this question was asked a lot of improvement has happened in the standard Python scientific libraries (which was the targeted area). For example the numpy project has made a big effort to improve the docstrings. One can still argue if it would have been possible to address these issues continuously right from the start.
I have this somewhat heretic question: Why do so many Python libraries have messy code and don't follow standard best practices? Or do you think that this observation is absolutely not true? How does the situation compare to other languages? I am interested in your take on this.
Some reasons why I have the impression that quality is lacking:
The docstrings are often completely missing or incomplete, even for the public API. It is painful when a method takes *args and **kwargs but does not document which values can be given.
Bad Python coding practices, like adding new attributes outside of __init__. Things like this make the code hard to read (or to maintain).
Hardly any libraries follow the PEP8 coding conventions. Sometimes the conventions are not even consistent in a single file.
The overall design is messy, with no clear API. It seems that not nearly enough refactoring is done.
Poor unittest coverage.
Don't get me wrong, I absolutely love Python and its ecosystem. And even though I struggled with these libraries they generally get the job done and I am grateful for that. But I also think that in the end tons of developer time are wasted because of these issues. Maybe that is because Python gives you so much freedom that it is very easy to write bad code.
|
Regarding documentation, it's not just Python. If there is one single factor that is preventing the wider adoption of OSS it is, IMHO, the truly dreadful level of documentation of most OSS projects. This starts at the code level and extends to the user docs. Can I just say to anyone working on OSS:
a) Comment your code! There is no such thing as self documenting code!
b) Spend at least 25% of the project time budget on end-user documentation.
And I do know vaguely what I'm talking about - I have a couple of OSS projects of my own, I've contributed to several others and I use OSS almost exclusively. And yesterday I spent over 4 hours trying to build a major OSS project (no names, no pack drill), and failing because of the crappy, self-contradictory documentation.
|
How can I use C++ class in Python?
|
I have implemented a class in C++. I want to use it with Python.
Please suggest step by step method and elaborate each step.
Somthing like this...
class Test{
private:
int n;
public:
Test(int k){
n=k;
}
void setInt(int k){
n = k;
}
int getInt(){
return n;
}
};
Now, in Python
>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32
Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.
|
Look into Boost.Python. It's a library to write python modules with C++.
Also look into SWIG which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them within python. Works great.
You can do it manually by using the Python/C API, writing the interface yourself. It's pretty lowlevel, but you will gain a lot of additional knowledge of how Python works behind the scene (And you will need it when you use SWIG anyway).
|
How can I access the current executing module or class name in Python?
|
I would like to be able to dynamically retrieve the current executing module or class name from within an imported module. Here is some code:
foo.py:
def f():
print __name__
bar.py:
from foo import f
def b(): f()
This obviously does not work as __name__ is the name of the module that contains the function. What I would like to be access inside the foo module is the name of the current executing module that is using foo. So in the case above it would be bar but if any other module imported foo I would like foo to dynamically have access to the name of that module.
Edit: The inspect module looks quite promising but it is not exactly what I was looking for. What I was hoping for was some sort of global or environment-level variable that I could access that would contain the name of the current executing module. Not that I am unwilling to traverse the stack to find that information - I just thought that Python may have exposed that data already.
Edit: Here is how I am trying to use this. I have two different Django applications that both need to log errors to file. Lets say that they are called "AppOne" and "AppTwo". I also have a place to which I would like to log these files: "/home/hare/app_logs". In each application at any given point I would like to be able to import my logger module and call the log function which writes the log string to file. However what I would like to do is create a directory under app_logs that is the name of the current application ("AppOne" or "AppTwo") so that each application's log files will go in their respective logging directories.
In order to do this I thought that the best way would be for the logger module to have access to some sort of global variable that denotes the current application's name as it is responsible for knowing the location of the parent logging directory and creating the application's logging directory if it does not yet exist.
|
From the comment -- not the question.
"I am simply curious to see if what I am trying to do is possible."
The answer to "is it possible" is always "yes". Always. Unless your question involves time travel, anti-gravity or perpetual motion.
Since the answer is always "yes", your question is ill-formed. The real question is "what's a good way to have my logging module know the name of the client?" or something like that.
The answer is "Accept it as a parameter." Don't mess around with inspecting or looking for mysterious globals or other tricks.
Just follow the design pattern of logging.getLogger() and use explicitly-named loggers. A common idiom is the following
logger= logging.getLogger( __name__ )
That handles almost all log naming perfectly.
|
Need python lxml syntax help for parsing html
|
I am brand new to python, and I need some help with the syntax for finding and iterating through html tags using lxml. Here are the use-cases I am dealing with:
HTML file is fairly well formed (but not perfect). Has multiple tables on screen, one containing a set of search results, and one each for a header and footer. Each result row contains a link for the search result detail.
I need to find the middle table with the search result rows (this one I was able to figure out):
self.mySearchTables = self.mySearchTree.findall(".//table")
self.myResultRows = self.mySearchTables[1].findall(".//tr")
I need to find the links contained in this table (this is where I'm getting stuck):
for searchRow in self.myResultRows:
searchLink = patentRow.findall(".//a")
It doesn't seem to actually locate the link elements.
I need the plain text of the link. I imagine it would be something like searchLink.text if I actually got the link elements in the first place.
Finally, in the actual API reference for lxml, I wasn't able to find information on the find and the findall calls. I gleaned these from bits of code I found on google. Am I missing something about how to effectively find and iterate over HTML tags using lxml?
|
Okay, first, in regards to parsing the HTML: if you follow the recommendation of zweiterlinde and S.Lott at least use the version of beautifulsoup included with lxml. That way you will also reap the benefit of a nice xpath or css selector interface.
However, I personally prefer Ian Bicking's HTML parser included in lxml.
Secondly, .find() and .findall() come from lxml trying to be compatible with ElementTree, and those two methods are described in XPath Support in ElementTree.
Those two functions are fairly easy to use but they are very limited XPath. I recommend trying to use either the full lxml xpath() method or, if you are already familiar with CSS, using the cssselect() method.
Here are some examples, with an HTML string parsed like this:
from lxml.html import fromstring
mySearchTree = fromstring(your_input_string)
Using the css selector class your program would roughly look something like this:
# Find all 'a' elements inside 'tr' table rows with css selector
for a in mySearchTree.cssselect('tr a'):
print 'found "%s" link to href "%s"' % (a.text, a.get('href'))
The equivalent using xpath method would be:
# Find all 'a' elements inside 'tr' table rows with xpath
for a in mySearchTree.xpath('.//tr/*/a'):
print 'found "%s" link to href "%s"' % (a.text, a.get('href'))
|
Multicast in Python
|
How do you send and receive UDP Multicast in Python? Is there a standard library to do so?
|
This works for me:
Receive
import socket
import struct
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', MCAST_PORT)) # use MCAST_GRP instead of '' to listen only
# to MCAST_GRP, not all groups on MCAST_PORT
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
while True:
print sock.recv(10240)
Send
import socket
MCAST_GRP = '224.1.1.1'
MCAST_PORT = 5007
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
sock.sendto("robot", (MCAST_GRP, MCAST_PORT))
It is based off the examples from http://wiki.python.org/moin/UdpCommunication which didn't work.
My system is...
Linux 2.6.31-15-generic #50-Ubuntu SMP Tue Nov 10 14:54:29 UTC 2009 i686 GNU/Linux
Python 2.6.4
|
How do you get default headers in a urllib2 Request?
|
I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.
However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the full set of HTTP headers), and can't figure out how.
any pointers?
in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?
|
If you want to see the literal HTTP request that is sent out, and therefore see every last header exactly as it is represented on the wire, then you can tell urllib2 to use your own version of an HTTPHandler that prints out (or saves, or whatever) the outgoing HTTP request.
import httplib, urllib2
class MyHTTPConnection(httplib.HTTPConnection):
def send(self, s):
print s # or save them, or whatever!
httplib.HTTPConnection.send(self, s)
class MyHTTPHandler(urllib2.HTTPHandler):
def http_open(self, req):
return self.do_open(MyHTTPConnection, req)
opener = urllib2.build_opener(MyHTTPHandler)
response = opener.open('http://www.google.com/')
The result of running this code is:
GET / HTTP/1.1
Accept-Encoding: identity
Host: www.google.com
Connection: close
User-Agent: Python-urllib/2.6
|
Django set default form values
|
I have a Model as follows
class TankJournal(models.Model):
user = models.ForeignKey(User)
tank = models.ForeignKey(TankProfile)
ts = models.IntegerField(max_length=15)
title = models.CharField(max_length=50)
body = models.TextField()
I have a modelform as follows for that model
class JournalForm(ModelForm):
tank = forms.IntegerField(widget=forms.HiddenInput())
class Meta:
model = TankJournal
exclude = ('user','ts')
I want to know how to set the default value for that tank hidden field.. Here is my function to show/save the form so far
def addJournal(request, id=0):
if not request.user.is_authenticated():
return HttpResponseRedirect('/')
#
# checking if they own the tank
#
from django.contrib.auth.models import User
user = User.objects.get(pk=request.session['id'])
if request.method == 'POST':
form = JournalForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
#
# setting the user and ts
#
from time import time
obj.ts = int(time())
obj.user = user
obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id'])
#
# saving the test
#
obj.save()
else:
form = JournalForm()
try:
tank = TankProfile.objects.get(user=user, id=id)
except TankProfile.DoesNotExist:
return HttpResponseRedirect('/error/')
form.tank = id
return render_to_response('ajax/tank_addJournal.html', {'form': form}, context_instance=RequestContext(request))
thanks!
|
You can use initial which is explained here
You have two options either populate the value when calling form constructor:
form = JournalForm(initial={'tank': 123})
or set the value in the form definition:
tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123)
|
Analyze audio using Fast Fourier Transform
|
I am trying to create a graphical spectrum analyzer in python.
I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module like numpy, and use the result to create the graphical spectrum analyzer, which, to start will just be 32 bars.
I have read the wikipedia articles on Fast Fourier Transform and Discrete Fourier Transform but I am still unclear of what the resulting array represents. This is what the array looks like after I preform an fft on my array using numpy:
[ -3.37260500e+05 +0.00000000e+00j 7.11787022e+05 +1.70667403e+04j
4.10040193e+05 +3.28653370e+05j 9.90933073e+04 +1.60555003e+05j
2.28787050e+05 +3.24141951e+05j 2.09781047e+04 +2.31063376e+05j
-2.15941453e+05 +1.63773851e+05j -7.07833051e+04 +1.52467334e+05j
-1.37440802e+05 +6.28107674e+04j -7.07536614e+03 +5.55634993e+03j
-4.31009964e+04 -1.74891657e+05j 1.39384348e+05 +1.95956947e+04j
1.73613033e+05 +1.16883207e+05j 1.15610357e+05 -2.62619884e+04j
-2.05469722e+05 +1.71343186e+05j -1.56779748e+04 +1.51258101e+05j
-2.08639913e+05 +6.07372799e+04j -2.90623668e+05 -2.79550838e+05j
-1.68112214e+05 +4.47877871e+04j -1.21289916e+03 +1.18397979e+05j
-1.55779104e+05 +5.06852464e+04j 1.95309737e+05 +1.93876325e+04j
-2.80400414e+05 +6.90079265e+04j 1.25892113e+04 -1.39293422e+05j
3.10709174e+04 -1.35248953e+05j 1.31003438e+05 +1.90799303e+05j...
I am wondering what exactly these numbers represent and how I would convert these numbers into a percentage of a height for each of the 32 bars. Also, should I be averaging the 2 channels together?
|
The array you are showing is the Fourier Transform coefficients of the audio signal. These coefficients can be used to get the frequency content of the audio. The FFT is defined for complex valued input functions, so the coefficients you get out will be imaginary numbers even though your input is all real values. In order to get the amount of power in each frequency, you need to calculate the magnitude of the FFT coefficient for each frequency. This is not just the real component of the coefficient, you need to calculate the square root of the sum of the square of its real and imaginary components. That is, if your coefficient is a + b*j, then its magnitude is sqrt(a^2 + b^2).
Once you have calculated the magnitude of each FFT coefficient, you need to figure out which audio frequency each FFT coefficient belongs to. An N point FFT will give you the frequency content of your signal at N equally spaced frequencies, starting at 0. Because your sampling frequency is 44100 samples / sec. and the number of points in your FFT is 256, your frequency spacing is 44100 / 256 = 172 Hz (approximately)
The first coefficient in your array will be the 0 frequency coefficient. That is basically the average power level for all frequencies. The rest of your coefficients will count up from 0 in multiples of 172 Hz until you get to 128. In an FFT, you only can measure frequencies up to half your sample points. Read these links on the Nyquist Frequency and Nyquist-Shannon Sampling Theorem if you are a glutton for punishment and need to know why, but the basic result is that your lower frequencies are going to be replicated or aliased in the higher frequency buckets. So the frequencies will start from 0, increase by 172 Hz for each coefficient up to the N/2 coefficient, then decrease by 172 Hz until the N - 1 coefficient.
That should be enough information to get you started. If you would like a much more approachable introduction to FFTs than is given on Wikipedia, you could try Understanding Digital Signal Processing: 2nd Ed.. It was very helpful for me.
So that is what those numbers represent. Converting to a percentage of height could be done by scaling each frequency component magnitude by the sum of all component magnitudes. Although, that would only give you a representation of the relative frequency distribution, and not the actual power for each frequency. You could try scaling by the maximum magnitude possible for a frequency component, but I'm not sure that that would display very well. The quickest way to find a workable scaling factor would be to experiment on loud and soft audio signals to find the right setting.
Finally, you should be averaging the two channels together if you want to show the frequency content of the entire audio signal as a whole. You are mixing the stereo audio into mono audio and showing the combined frequencies. If you want two separate displays for right and left frequencies, than you need to perform the Fourier analysis on each channel separately.
|
How would you translate this from Perl to Python?
|
I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:
sub uniqify($) {
my $timestamp = shift;
state $last_ts = -1;
state $next_letter = 'A';
if ($timestamp == $last_ts) {
$timestamp .= $next_letter++;
} else {
$last_ts = $timestamp;
$next_letter = 'A';
}
return $timestamp;
}
So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.
Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.
Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.
Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.
I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?
|
Look at this answer for a robust method to convert a number to an alphanumeric id
The code I present doesn't go from 'Z' to 'AA', instead goes to 'BA', but I suppose that doesn't matter, it still produces a unique id
from string import uppercase as up
import itertools
def to_base(q, alphabet):
if q < 0: raise ValueError( "must supply a positive integer" )
l = len(alphabet)
converted = []
while q != 0:
q, r = divmod(q, l)
converted.insert(0, alphabet[r])
return "".join(converted) or alphabet[0]
class TimestampUniqifier( object ):
def __init__(self):
self.last = ''
self.counter = itertools.count()
def __call__( self, str ):
if str == self.last:
suf = self.counter.next()
return str + to_base( suf, up )
else:
self.last = str
self.counter = itertools.count()
return str
timestamp_uniqify = TimestampUniqifier()
usage:
timestamp_uniqify('1')
'1'
timestamp_uniqify('1')
'1A'
timestamp_uniqify('1')
'1B'
timestamp_uniqify('1')
'1C'
timestamp_uniqify('2')
'2'
timestamp_uniqify('3')
'3'
timestamp_uniqify('3')
'3A'
timestamp_uniqify('3')
'3B'
You can call it maaaany times and it will still produce good results:
for i in range(100): print timestamp_uniqify('4')
4
4A
4B
4C
4D
4E
4F
4G
4H
4I
4J
4K
4L
4M
4N
4O
4P
4Q
4R
4S
4T
4U
4V
4W
4X
4Y
4Z
4BA
4BB
4BC
4BD
4BE
4BF
4BG
4BH
4BI
4BJ
4BK
4BL
4BM
4BN
4BO
4BP
4BQ
4BR
4BS
4BT
4BU
4BV
4BW
4BX
4BY
4BZ
4CA
4CB
4CC
4CD
4CE
4CF
4CG
4CH
4CI
4CJ
4CK
4CL
4CM
4CN
4CO
4CP
4CQ
4CR
4CS
4CT
4CU
4CV
4CW
4CX
4CY
4CZ
4DA
4DB
4DC
4DD
4DE
4DF
4DG
4DH
4DI
4DJ
4DK
4DL
4DM
4DN
4DO
4DP
4DQ
4DR
4DS
4DT
4DU
|
How do I access my webcam in Python?
|
I would like to access my webcam from Python.
I tried using the VideoCapture extension (tutorial), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns None for no apparent reason.
Is there a better way to access my webcam from Python?
|
OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work.
At the time of writing (January 2015) there is no Python 3 support yet, so you need to use Python 2.
More information on using OpenCV with Python.
An example copied from Displaying webcam feed using opencv and python:
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)
if vc.isOpened(): # try to get the first frame
rval, frame = vc.read()
else:
rval = False
while rval:
cv2.imshow("preview", frame)
rval, frame = vc.read()
key = cv2.waitKey(20)
if key == 27: # exit on ESC
break
cv2.destroyWindow("preview")
|
What's the search engine used in the new Python documentation?
|
Is it built-in in Sphinx?
|
It look like Sphinx contains own search engine for English language. See http://sphinx.pocoo.org/_static/searchtools.js and searchindex.js/.json (see Sphinx docs index 36Kb, Python docs index 857Kb, and Grok docs 37Kb).
Index is being precomputed when docs are generated.
When one searches, static page is being loaded and then _static/searchtools.js extract search terms from query string, normalizes (case, stemming, etc.) them and looks up in searchindex.js as it is being loaded.
First search attempt takes rather long time, consecutive are much faster as index is cached in your browser.
|
Python: how to dump cookies of a mechanize.Browser instance?
|
I am learning how to use mechanize, a Python module to automate interacting with websites.
One feature is the automated handling of cookies. I would to want to dump cookies from a mechanize.Browser instance for debugging purposes, but I can't seem to figure this out myself.
|
>>> from mechanize import Browser
>>> b = Browser()
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[]
>>> b.open('http://google.com')
response_seek_wrapper at 0xb7a922ccL whose wrapped object = closeable_response at 0xb7aa070cL whose fp = socket._fileobject object at 0xb7a94224
>>>
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[Cookie(version=0, name='PREF', value='ID=57d545c229b4cf3f:TM=1236081634:LM=1236081634:S=p001WJMOr-V8Rlvi', port=None, port_specified=False, domain='.google.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153634, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False), Cookie(version=0, name='PREF', value='ID=20534d80a5ccf2ea:TM=1236081635:LM=1236081635:S=jW3UotZ0dg8sv6mf', port=None, port_specified=False, domain='.google.com.ua', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153635, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)]
>>>
|
Convert bytes to a Python string
|
I'm using this code to get standard output from an external program:
>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
The communicate() method returns an array of bytes:
>>> command_stdout
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
However, I'd like to work with the output as a normal Python string. So that I could print it like this:
>>> print(command_stdout)
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1
-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2
I thought that's what the binascii.b2a_qp() method is for, but when I tried it, I got the same byte array again:
>>> binascii.b2a_qp(command_stdout)
b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n'
Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.
|
You need to decode the bytes object to produce a string:
>>> b"abcde"
b'abcde'
# utf-8 is used here because it is a very common encoding, but you
# need to use the encoding your data is actually in.
>>> b"abcde".decode("utf-8")
'abcde'
|
How to get filename of the __main__ module in Python?
|
Suppose I have two modules:
a.py:
import b
print __name__, __file__
b.py:
print __name__, __file__
I run the "a.py" file. This prints:
b C:\path\to\code\b.py
__main__ C:\path\to\code\a.py
Question: how do I obtain the path to the __main__ module ("a.py" in this case) from within the "b.py" library?
|
import __main__
print __main__.__file__
|
How does Python's "super" do the right thing?
|
I'm running Python 2.5, so this question may not apply to Python 3. When you make a diamond class hierarchy using multiple inheritance and create an object of the derived-most class, Python does the Right Thing (TM). It calls the constructor for the derived-most class, then its parent classes as listed from left to right, then the grandparent. I'm familiar with Python's MRO; that's not my question. I'm curious how the object returned from super actually manages to communicate to calls of super in the parent classes the correct order. Consider this example code:
#!/usr/bin/python
class A(object):
def __init__(self): print "A init"
class B(A):
def __init__(self):
print "B init"
super(B, self).__init__()
class C(A):
def __init__(self):
print "C init"
super(C, self).__init__()
class D(B, C):
def __init__(self):
print "D init"
super(D, self).__init__()
x = D()
The code does the intuitive thing, it prints:
D init
B init
C init
A init
However, if you comment out the call to super in B's init function, neither A nor C's init function is called. This means B's call to super is somehow aware of C's existence in the overall class hierarchy. I know that super returns a proxy object with an overloaded get operator, but how does the object returned by super in D's init definition communicate the existence of C to the object returned by super in B's init definition? Is the information that subsequent calls of super use stored on the object itself? If so, why isn't super instead self.super?
Edit: Jekke quite rightly pointed out that it's not self.super because super is an attribute of the class, not an instance of the class. Conceptually this makes sense, but in practice super isn't an attribute of the class either! You can test this in the interpreter by making two classes A and B, where B inherits from A, and calling dir(B). It has no super or __super__ attributes.
|
Change your code to this and I think it'll explain things (presumably super is looking at where, say, B is in the __mro__?):
class A(object):
def __init__(self):
print "A init"
print self.__class__.__mro__
class B(A):
def __init__(self):
print "B init"
print self.__class__.__mro__
super(B, self).__init__()
class C(A):
def __init__(self):
print "C init"
print self.__class__.__mro__
super(C, self).__init__()
class D(B, C):
def __init__(self):
print "D init"
print self.__class__.__mro__
super(D, self).__init__()
x = D()
If you run it you'll see:
D init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
B init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
C init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
A init
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <type 'object'>)
Also it's worth checking out Python's Super is nifty, but you can't use it.
|
Django email
|
I am using the Gmail SMTP server to send out emails from users of my website.
These are the default settings in my settings.py
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'example@example.com'
EMAIL_HOST_PASSWORD = 'pwd'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
SERVER_EMAIL = EMAIL_HOST_USER
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
If I want a user to send an email, I am overriding these settings and sending the email using Django's email sending methods. When an exception occurs in the system, I receive an email from the example@example.com. Sometimes I receive an email from some logged in user. Which could also possibly mean that when a user receives an email sent from my website it has a sent address different from the actual user.
What should be done to avoid this situation?
|
Django only uses settings.DEFAULT_FROM_EMAIL when any of the mail sending functions pass None or empty string as the sender address. This can be verified in django/core/mail.py.
When there is an unhandled exception Django calls the mail_admins() function in django/core/mail.py which always uses settings.SERVER_EMAIL and is only sent to addresses listed in settings.ADMINS. This can also be verified in django/core/mail.py.
The only other place Django itself sends e-mails is if settings.SEND_BROKEN_LINK_EMAILS is True, then CommonMiddleware will send mail to all addresses listed in settings.MANAGERS and the e-mail sender is settings.SERVER_EMAIL.
Therefore, the only time a regular user will receive e-mail from your site is when you call send_mail(). So, always pass a real address as the from_mail argument and you will avoid users receiving email from settings.SERVER_EMAIL or settings.DEFAULT_FROM_EMAIL.
Side note: django-registration is at least one example of a Django pluggable that will send mail from settings.DEFAULT_FROM_EMAIL so in cases like this you need to make sure it is a proper e-mail address such as support@yoursite.com or webmaster@yoursite.com.
|
Charts in django Web Applications
|
I want to Embed a chart in a Web Application developed using django.
I have come across Google charts API, ReportLab, PyChart, MatPlotLib and ChartDirector
I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.
Which is the best option to use, and what are the relative merits and demerits of one over the other.
|
Another choice is CairoPlot.
We picked matplotlib over the others for some serious graphing inside one of our django apps, primarily because it was the only one that gave us exactly the kind of control we needed.
Performance generating PNG's was fine for us but... it was a highly specialized app with less than 10 logins a day.
|
How to know if an object has an attribute in Python
|
Is there a way in Python to determine if an object has some attribute? For example:
>>> a = SomeClass()
>>> a.someProperty = value
>>> a.property
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'property'
How can you tell if a has the attribute property before using it?
|
Try hasattr():
if hasattr(a, 'property'):
a.property
EDIT: See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!
The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block.
|
Can you give a Django app a verbose name for use throughout the admin?
|
In the same way that you can give fields and models verbose names that appear in the Django admin, can you give an app a custom name?
|
Prior to Django 1.7
You can give your application a custom name by defining app_label in your model definition. But as django builds the admin page it will hash models by their app_label, so if you want them to appear in one application, you have to define this name in all models of your application.
class MyModel(models.Model):
pass
class Meta:
app_label = 'My APP name'
Django 1.7+
As stated by rhunwicks' comment to OP, this is now possible out of the box since Django 1.7
Taken from the docs:
# in yourapp/apps.py
from django.apps import AppConfig
class YourAppConfig(AppConfig):
name = 'yourapp'
verbose_name = 'Fancy Title'
then set the default_app_config variable to YourAppConfig
# in yourapp/__init__.py
default_app_config = 'yourapp.apps.YourAppConfig'
|
Sort a Python dictionary by value
|
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.
I can sort on the keys, but how can I sort based on the values?
Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.
|
It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a listâprobably a list of tuples.
For instance,
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.
And for those wishing to sort on keys instead of values:
import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))
|
Is there a need for a "use strict" Python compiler?
|
There exist static analysis tools for Python, but compile time checks tend to be diametrically opposed to the run-time binding philosophy that Python embraces. It's possible to wrap the standard Python interpreter with a static analysis tool to enforce some "use strict"-like constraints, but we don't see any widespread adoption of such a thing.
Is there something about Python that makes "use strict" behavior unnecessary or especially undesirable?
Alternatively, is the "use strict" behavior unnecessary in Perl, despite its widespread adoption?
Note: By "necessary" I mean "practically necessary", not strictly necessary. Obviously you can write Perl without "use strict," but (from what I've seen) most Perl programmers do use it.
Note: The Python interpreter-wrapper need not require "use strict"-like constraints -- you could use a pseudo-pragma similar to "use strict" that would be ignored by the normal interpreter. I'm not talking about adding a language-level feature.
Update: Explaining what "use strict" does in Perl per comments. (Link to official docs is in the first paragraph.)
The "use strict" directive has three distinct components, only two of which are really interesting:
use strict vars: Statically checks lexically scoped variable usage in your program. (Keep in mind that, in Python, there is basically only global scope and local scope). Many Python linters check for this sort of thing. Since it's the only static analysis that they can do, the linters assume you use straightforward lexical scoping and warn you about things that appear wrong in that sense until you tell them to shut up; i.e.
FOO = 12
foo += 3
If you're not doing anything fancy with your namespaces this can be useful to check for typos.
use strict refs: Prevents symbolic namespace dereferencing. Python's closest analog is using locals() and globals() to do symbolic binding and identifier lookup.
use strict subs: No real analog in Python.
|
Well, I'm not much of a python programmer, but I'd say that the answer is 'YES'.
Any dynamic language that lets you create a variable with any name at any time, could use a 'strict' pragma.
Strict vars (one of the options for strict in Perl, 'use strict' turns them all on at once) in Perl requires that all variables are declared before they are used. Which means that this code:
my $strict_is_good = 'foo';
$strict_iS_good .= 'COMPILE TIME FATAL ERROR';
Generates a fatal error at compile time.
I don't know of a way to get Python to reject this code at compile time:
strict_is_good = 'foo';
strict_iS_good += 'RUN TIME FATAL ERROR';
You will get a run-time exception that strict_iS_good is undefined. But only when the code is executed. If your test suite does not have 100% coverage, you can easily ship this bug.
Any time I work in a language that does not have this behavior (PHP for example), I get nervous. I am not a perfect typist. A simple, but hard to spot, typo can cause your code to fail in ways that may be hard to track down.
So, to reiterate, YES Python could use a 'strict' pragma to turn on compile time checks for things that can be checked at compile time. I can't think of any other checks to add, but a better Python programmer probably could think of some.
Note I focus on the pragmatic effect of stict vars in Perl, and am glossing over some of the details. If you really want to know all the details see the perldoc for strict.
Update: Responses to some comments
Jason Baker : Static checkers like pylint are useful. But they represent an extra step that can be and often is skipped. Building some basic checks into the compiler guarantees that these checks are performed consistently. If these checks are controllable by a pragma, even the objection relating to the cost of the checks becomes moot.
popcnt : I know that python will generate a run time exception. I said as much. I advocate compile time checking where possible. Please reread the post.
mpeters : No computer analysis of code can find all errors--this amounts to solving the halting problem. Worse, to find typos in assignments, your compiler would need to know your intentions and find places where your intentions differ from your code. This is pretty clearly impossible.
However this does not mean that no checking should be done. If there are classes of problems that are easy to detect, then it makes sense to trap them.
I'm not familiar enough with pylint and pychecker to say what classes of errors they will catch. As I said I am very inexperienced with python.
These static analysis programs are useful. However, I believe that unless they duplicate the capabilities of the compiler, the compiler will always be in a position to "know" more about the program than any static checker could. It seems wasteful not to take advantage of this to reduce errors where possible.
Update 2:
cdleary - In theory, I agree with you, a static analyzer can do any validation that the compiler can. And in the case of Python, it should be enough.
However, if your compiler is complex enough (especially if you have lots of pragmas that change how compilation occurs, or if like Perl, you can run code at compile time), then the static analyzer must approach the complexity of the compiler/interpreter to do the analysis.
Heh, all this talk of complex compilers and running code at compile time shows my Perl background.
My understanding is that Python does not have pragmas and can not run arbitrary code at compile time. So, unless I am wrong or these features are added, a relatively simple parser in the static analyzer should suffice. It certainly would be helpful to force these checks at every execution. Of course, the way I'd do this is with a pragma.
Once you add pragmas to the mix, you have started down a slippery slope and the complexity of you analyzer must grow in proportion to the power and flexibility you provide in your pragmas. If you are not careful, you can wind up like Perl, and then "only python can parse Python," a future I wouldn't want to see.
Maybe a command line switch would be a better way to add forced static analysis ;)
(In no way do intend to impugn Python's capabilities when I say that it can't futz with compile time behavior like Perl can. I have a hunch that this is a carefully considered design decision, and I can see the wisdom in it. Perl's extreme flexibility at compile time is, IMHO, a great strength and a terrible weakness of the language; I see the wisdom in this approach as well.)
|
Discovering public IP programatically
|
I'm behind a router, I need a simple command to discover my public ip (instead of googling what's my ip and clicking one the results)
Are there any standard protocols for this? I've heard about STUN but I don't know how can I use it?
P.S. I'm planning on writing a short python script to do it
|
This may be the easiest way. Parse the output of the following commands:
run a traceroute to find a router that is less than 3 hops out from your machine.
run ping with the option to record the source route and parse the output. The first IP address in the recorded route is your public one.
For example, I am on a Windows machine, but the same idea should work from unix too.
> tracert -d www.yahoo.com
Tracing route to www-real.wa1.b.yahoo.com [69.147.76.15]
over a maximum of 30 hops:
1 <1 ms <1 ms <1 ms 192.168.14.203
2 * * * Request timed out.
3 8 ms 8 ms 9 ms 68.85.228.121
4 8 ms 8 ms 9 ms 68.86.165.234
5 10 ms 9 ms 9 ms 68.86.165.237
6 11 ms 10 ms 10 ms 68.86.165.242
The 68.85.228.121 is a Comcast (my provider) router. We can ping that:
> ping -r 9 68.85.228.121 -n 1
Pinging 68.85.228.121 with 32 bytes of data:
Reply from 68.85.228.121: bytes=32 time=10ms TTL=253
Route: 66.176.38.51 ->
68.85.228.121 ->
68.85.228.121 ->
192.168.14.203
Voila! The 66.176.38.51 is my public IP.
|
How do I duplicate sys.stdout to a log file in python?
|
Edit: Since it appears that there's either no solution, or I'm doing something so non-standard that nobody knows - I'll revise my question to also ask: What is the best way to accomplish logging when a python app is making a lot of system calls?
My app has two modes. In interactive mode, I want all output to go to the screen as well as to a log file, including output from any system calls. In daemon mode, all output goes to the log. Daemon mode works great using os.dup2(). I can't find a way to "tee" all output to a log in interactive mode, without modifying each and every system call.
In other words, I want the functionality of the command line 'tee' for any output generated by a python app, including system call output.
To clarify:
To redirect all output I do something like this, and it works great:
# open our log file
so = se = open("%s.log" % self.name, 'w', 0)
# re-open stdout without buffering
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# redirect stdout and stderr to the log file opened above
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
The nice thing about this is that it requires no special print calls from the rest of the code. The code also runs some shell commands, so it's nice not having to deal with each of their output individually as well.
Simply, I want to do the same, except duplicate instead of redirect.
At first blush, I thought that simply reversing the dup2's should work. Why doesn't it? Here's my test:
import os, sys
### my broken solution:
so = se = open("a.log", 'w', 0)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
os.dup2(sys.stdout.fileno(), so.fileno())
os.dup2(sys.stderr.fileno(), se.fileno())
###
print "kljhf sdf"
os.spawnve("P_WAIT", "/bin/ls", ["/bin/ls"], {})
os.execve("/bin/ls", ["/bin/ls"], os.environ)
The file "a.log" should be identical to what was displayed on the screen.
|
I had this same issue before and found this snippet very useful:
class Tee(object):
def __init__(self, name, mode):
self.file = open(name, mode)
self.stdout = sys.stdout
sys.stdout = self
def __del__(self):
sys.stdout = self.stdout
self.file.close()
def write(self, data):
self.file.write(data)
self.stdout.write(data)
from: http://mail.python.org/pipermail/python-list/2007-May/438106.html
|
How do I detect if my appengine app is being accessed by an iphone/ipod touch?
|
I need to render the page differently if it's acessed by an iphone/ipod touch. I suppose the information is in the request object, but what would be the syntax?
|
This is the syntax I was looking for, works with iphone and ipod touch:
uastring = self.request.headers.get('user_agent')
if "Mobile" in uastring and "Safari" in uastring:
# do iphone / ipod stuff
|
How to find whether a number belongs to a particular range in Python?
|
Suppose I want to check if x belongs to range 0 to 0.5. How can I do it?
|
No, you can't do that. range() expects integer arguments. If you want to know if x is inside this range try some form of this:
print 0.0 <= x <= 0.5
Be careful with your upper limit. If you use range() it is excluded (range(0, 5) does not include 5!)
|
Django: using and POST
|
I'm using something like this in my template
<select multiple="multiple" name="services" id="services" size="5">
{% for service in services %}
<option value="{{service.id}}">{{service}}</option>
{% endfor %}
</select>
When I view the POST data in Firebug or the Django debug, I see it only sends one value. Am I doing something wrong or misunderstanding a concept?
|
request.POST.getlist('services')
|
What does PyPy have to offer over CPython, Jython, and IronPython?
|
From what I have seen and read on blogs, PyPy is a very ambitious project. What are some advantages it will bring to the table over its siblings (CPython, Jython, and IronPython)? Is it speed, cross-platform compatibility (including mobile platforms), the ability to use c-extensions without the GIL, or is this more of a technical exercise on what can be done?
|
PyPy is really two projects:
An interpreter compiler toolchain allowing you to write interpreters in RPython (a static subset of Python) and have cross-platform interpreters compiled standalone, for the JVM, for .NET (etc)
An implementation of Python in RPython
These two projects allow for many things.
Maintaining Python in Python is much easier than maintaining it in C
From a single codebase you can generate Python interpreters that run on the JVM, .NET and standalone - rather than having multiple slightly incompatible implementations
Part of the compiler toolchain includes an experimental JIT generator (now in its fifth incarnation and starting to work really well) - the goal is for a JITed PyPy to run much faster than CPython
It is much easier to experiment with fundamental language features - like removing the GIL, better garbage collection, integrating stackless and so on
So there are really a lot of reasons for PyPy to be exciting, and it is finally starting to live up to all its promises.
|
Convert Year/Month/Day to Day of Year in Python
|
I'm using the Python "datetime" module, i.e.:
>>> import datetime
>>> today = datetime.datetime.now()
>>> print today
2009-03-06 13:24:58.857946
and I would like to compute the day of year that is sensitive of leap years. e.g. oday (March 6, 2009) is the 65th day of 2009. Here's web-based DateTime calculator.
Anyway, I see a two options:
Create a number_of_days_in_month array = [31, 28, ...], decide if it's a leap year, manually sum up the days
Use datetime.timedelta to make a guess & then binary search for the correct day of year:
.
>>> import datetime
>>> YEAR = 2009
>>> DAY_OF_YEAR = 62
>>> d = datetime.date(YEAR, 1, 1) + datetime.timedelta(DAY_OF_YEAR - 1)
These both feel pretty clunky & I have a gut feeling that there's a more "Pythonic" way of calculating day of year. Any ideas/suggestions?
|
There is a very simple solution:
day_of_year = datetime.now().timetuple().tm_yday
|
How to import a Django project settings.py Python file from a sub-directory?
|
I created a sub-directory of my Django project called bin where I want to put all command-line run Python scripts. Some of these scripts need to import my Django project settings.py file that is in a parent directory of bin.
How can I import the settings.py file from a sub-directory of the project?
The code that I use in my command-line script to set into the "Django context" of the project is:
from django.core.management import setup_environ
import settings
setup_environ(settings)
This works fine if the script is in the root directory of my project.
I tried the following two hacks to import the settings.py file and then setup the project:
import os
os.chdir("..")
import sys
sys.path = [str(sys.path[0]) + "/../"] + sys.path
The cruel hack can import settings.py, but then I get the error:
project_module = __import__(project_name, {}, {}, [''])
ValueError: Empty module name
|
I think your approach may be over-complicating something that Django 1.x provides for you. As long as your project is in your python path, you can set the environment variable DJANGO_SETTINGS_MODULE at the top of your script like so:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
In your command line script where you need to read your settings, simply import the settings module from 'django.conf' as you would do in your application code:
from django.conf import settings
And presto, you have your settings and a Django-enabled environment for your script.
I personally prefer to set my DJANGO_SETTINGS_MODULE using '/usr/bin/env' in a bash script called 'proj_env' so I don't have to repeat it
#!/bin/bash
proj_env="DJANGO_SETTINGS_MODULE=myproject.settings"
/usr/bin/env $proj_env ${*}
With this, now I can run any python script with my Django application in context:
proj_env python -m 'myproject.bin.myscript'
If you use virtualenv, this also gives you a good place to source the activate script.
etc. etc.
|
How to jump to a particular line in a huge text file?
|
Are there any alternatives to the code below:
startFromLine = 141978 # or whatever line I need to jump to
urlsfile = open(filename, "rb", 0)
linesCounter = 1
for line in urlsfile:
if linesCounter > startFromLine:
DoSomethingWithThisLine(line)
linesCounter += 1
If I'm processing a huge text file (~15MB) with lines of unknown but different length, and need to jump to a particular line which number I know in advance? I feel bad by processing them one by one when I know I could ignore at least first half of the file. Looking for more elegant solution if there is any.
|
You can't jump ahead without reading in the file at least once, since you don't know where the line breaks are. You could do something like:
# Read in the file once and build a list of line offsets
line_offset = []
offset = 0
for line in file:
line_offset.append(offset)
offset += len(line)
file.seek(0)
# Now, to skip to line n (with the first line being line 0), just do
file.seek(line_offset[n])
|
SQLAlchemy Obtain Primary Key With Autoincrement Before Commit
|
When I have created a table with an auto-incrementing primary key, is there a way to obtain what the primary key would be (that is, do something like reserve the primary key) without actually committing?
I would like to place two operations inside a transaction however one of the operations will depend on what primary key was assigned in the previous operation.
|
You don't need to commit, you just need to flush. Here's some sample code. After the call to flush you can access the primary key that was assigned. Note this is with SA 0.4.8.
from sqlalchemy import *
from sqlalchemy.databases.mysql import *
import sqlalchemy.ext.declarative
Base = sqlalchemy.ext.declarative.declarative_base()
class User(Base):
__tablename__ = 'user'
user_id = Column('user_id', Integer, primary_key=True)
name = Column('name', String)
if __name__ == '__main__':
import unittest
from sqlalchemy.orm import *
import datetime
class Blah(unittest.TestCase):
def setUp(self):
self.engine = create_engine('sqlite:///:memory:', echo=True)
self.sessionmaker = scoped_session(sessionmaker(bind=self.engine))
Base.metadata.bind = self.engine
Base.metadata.create_all()
self.now = datetime.datetime.now()
def test_pkid(self):
user = User(name="Joe")
session = self.sessionmaker()
session.save(user)
session.flush()
print 'user_id', user.user_id
session.commit()
session.close()
unittest.main()
|
How to slice a list from an element n to the end in python?
|
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:
>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?
Thanks a lot for all your help!
|
You can leave one end of the slice open by not specifying the value.
test[3:] = [3, 4, 5, 6, 7, 8, 9]
test[:3] = [0, 1, 2]
|
Choosing and deploying a comet server
|
I want to push data to the browser over HTTP without killing my django/python application.
I decided to use a comet server, to proxy requests between my application and the client (though I still haven't really figured it out properly).
I've looked into the following engines:
orbited
cometd
ejabberd
jetty
Has anyone had any experience working with these servers and deploying them? Any insight and links regarding the topics would be great. Thank you.
|
I would recommend looking into Twisted, their twisted.web server, and the comet work done on top of it at Divmod. They can handle far more concurrent connections than traditional thread or process based servers, which is exactly what you need for something like this. And, yes, I've architected systems using Twisted for COMET stuff, while using other things for the more front-facing web applications beside it. It works out well with each part doing what it does best.
|
Increment Page Hit Count in Django
|
I have a table with an IntegerField (hit_count), and when a page is visited (for example, http://site/page/3) I want record ID 3's hit_count column in the database to increment by 1.
The query should be like:
update table set hit_count = hit_count + 1 where id = 3
Can I do this with the standard Django Model conventions? Or should I just write the query by hand?
|
If you use Django 1.1+, just use F expressions:
from django.db.models import F
...
MyModel.objects.filter(id=...).update(hit_count=F('hit_count')+1)
This will perform a single atomic database query.
As gerdemb says, you should consider putting this in a middleware to make it easily reusable so it doesn't clutter up all your views.
|
Unable to install Python without sudo access
|
I extracted, configured and used make for the installation package in my server.
However, I could not use make install. I get the error
[~/wepapps/python/Python-2.6.1]# make install
/usr/bin/install -c python /usr/local/bin/python2.6
/usr/bin/install: cannot create regular file `/usr/local/bin/python2.6': Permission denied
make: *** [altbininstall] Error 1
I run the folder with
chmod +x Python-2.6.1
I get still the same error.
How can I run make install without sudo access?
|
How can I install to a path under my home directory?
mkdir /home/masi/.local
cd Python-2.6.1
make clean
./configure --prefix=/home/masi/.local
make
make install
Then run using:
/home/masi/.local/bin/python
Similarly if you have scripts (eg. CGI) that require your own user version of Python you have to tell them explicitly:
#!/home/masi/.local/bin/python
instead of using the default system Python which â#!/usr/bin/env pythonâ will choose.
You can alter your PATH setting to make just typing âpythonâ from the console run that version, but it won't help for web apps being run under a different user.
If you compile something that links to Python (eg. mod_wsgi) you have to tell it where to find your Python or it will use the system one instead. This is often done something like:
./configure --prefix=/home/masi/.local --with-python=/home/masi/.local
For other setup.py-based extensions like MySQLdb you simply have to run the setup.py script with the correct version of Python:
/home/masi/.local/bin/python setup.py install
|
Django Passing Custom Form Parameters to Formset
|
This was fixed in Django 1.9 with form_kwargs.
I have a Django Form that looks like this:
class ServiceForm(forms.Form):
option = forms.ModelChoiceField(queryset=ServiceOption.objects.none())
rate = forms.DecimalField(widget=custom_widgets.SmallField())
units = forms.IntegerField(min_value=1, widget=custom_widgets.SmallField())
def __init__(self, *args, **kwargs):
affiliate = kwargs.pop('affiliate')
super(ServiceForm, self).__init__(*args, **kwargs)
self.fields["option"].queryset = ServiceOption.objects.filter(affiliate=affiliate)
I call this form with something like this:
form = ServiceForm(affiliate=request.affiliate)
Where request.affiliate is the logged in user. This works as intended.
My problem is that I now want to turn this single form into a formset. What I can't figure out is how I can pass the affiliate information to the individual forms when creating the formset. According to the docs to make a formset out of this I need to do something like this:
ServiceFormSet = forms.formsets.formset_factory(ServiceForm, extra=3)
And then I need to create it like this:
formset = ServiceFormSet()
Now how can I pass affiliate=request.affiliate to the individual forms this way?
|
I would use functools.partial and functools.wraps:
from functools import partial, wraps
from django.forms.formsets import formset_factory
ServiceFormSet = formset_factory(wraps(ServiceForm)(partial(ServiceForm, affiliate=request.affiliate)), extra=3)
I think this is the cleanest approach, and doesn't affect ServiceForm in any way (i.e. by making it difficult to subclass).
|
Why can't I directly add attributes to any python object?
|
I have this code:
>>> class G:
... def __init__(self):
... self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000
And this code:
>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'
From my Python knowledge, I would say that datetime overrides setattr/getattr, but I am not sure. Could you shed some light here?
EDIT: I'm not specifically interested in datetime. I was wondering about objects in general.
|
My guess, is that the implementation of datetime uses __slots__ for better performance.
When using __slots__, the interpreter reserves storage for just the attributes listed, nothing else. This gives better performance and uses less storage, but it also means you can't add new attributes at will.
Read more here: http://docs.python.org/reference/datamodel.html
|
how to detect whether a python variable is a function?
|
I have a variable, x, and I want to know whether it is pointing to a function or not.
I had hoped I could do something like:
>>> isinstance(x, function)
But that gives me:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
The reason I picked that is because
>>> type(x)
<type 'function'>
|
If this is for Python 2.x or for Python 3.2+, you can also use callable(). It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: http://bugs.python.org/issue10518. You can do this with:
callable(obj)
If this is for Python 3.x but before 3.2, check if the object has a __call__ attribute. You can do this with:
hasattr(obj, '__call__')
The oft-suggested types.FunctionTypes approach is not correct because it fails to cover many cases that you would presumably want it to pass, like with builtins:
>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True
The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container. Don't use types.FunctionType unless you have a very specific idea of what a function is.
|
Python __init__ and self what do they do?
|
I'm learning the Python programming language, and I've come across certain things I don't fully understand. I'm coming from a C background, but I never went far with that either.
What I'm trying to figure out is:
In a method:
def method(self, blah):
def __init__(?):
....
....
What does self do? what is it meant to be? and is it mandatory?
What does the __init__ method do? why is it necessary? etc
I think they might be oop constructs, but I don't know very much..
|
In this code:
class A(object):
def __init__(self):
self.x = 'Hello'
def method_a(self, foo):
print self.x + ' ' + foo
... the self variable represents the instance of the object itself. Most object-oriented languages pass this as a hidden parameter to the methods defined on an object; Python does not. You have to declare it explicitly. When you create an instance of the A class and call its methods, it will be passed automatically, as in ...
a = A() # We do not pass any argument to the __init__ method
a.method_a('Sailor!') # We only pass a single argument
The __init__ method is roughly what represents a constructor in Python. When you call A() Python creates an object for you, and passes it as the first parameter to the __init__ method. Any additional parameters (e.g., A(24, 'Hello')) will also get passed as arguments--in this case causing an exception to be raised, since the constructor isn't expecting them.
|
What's the difference between list and tuples?
|
What's the difference?
What are the advantages / disadvantages of tuples / lists?
|
Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.
Using this distinction makes code more explicit and understandable.
One example would be pairs of page and line number to reference locations in a book, e.g.:
my_location = (42, 11) # page number, line number
You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.
There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.
There are some interesting articles on this issue, e.g. "Python Tuples are Not Just Constant Lists" or "Understanding tuples vs. lists in Python". The official Python documentation also mentions this ("Tuples are immutable, and usually contain an heterogeneous sequence ...").
In a statically typed language like Haskell the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.
Finally there is the namedtuple in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.
|
How do I find the Windows common application data folder using Python?
|
I would like my application to store some data for access by all users. Using Python, how can I find where the data should go?
|
If you don't want to add a dependency for a third-party module like winpaths, I would recommend using the environment variables already available in Windows:
What environment variables are available in Windows?
Specifically you probably want ALLUSERSPROFILE to get the location of the common user profile folder, which is where the Application Data directory resides.
e.g.:
C:\> python -c "import os; print os.environ['ALLUSERSPROFILE']"
C:\Documents and Settings\All Users
EDIT: Looking at the winpaths module, it's using ctypes so if you wanted to just use the relevant part of the code without installing winpath, you can use this (obviously some error checking omitted for brevity).
import ctypes
from ctypes import wintypes, windll
CSIDL_COMMON_APPDATA = 35
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
ctypes.c_int,
wintypes.HANDLE,
wintypes.DWORD, wintypes.LPCWSTR]
path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH)
result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf)
print path_buf.value
Example run:
C:\> python get_common_appdata.py
C:\Documents and Settings\All Users\Application Data
|
How to remove an element from a list by index in Python?
|
How to remove an element from a list by index in Python?
I found the list.remove method, but say I want to remove the last element, how do I do this? It seems like the default remove searches the list, but I don't want any search to be performed.
|
Use del and specify the element you want to delete with the index:
In [9]: a = range(10)
In [10]: a
Out[10]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [11]: del a[-1]
In [12]: a
Out[12]: [0, 1, 2, 3, 4, 5, 6, 7, 8]
Here is the section from the tutorial.
|
Next step after PHP: Perl or Python?
|
It might seem it has been asked numerous times, but in fact it hasn't. I did my research, and now I'm eager to hear others' opinions.
I have experience with PHP 5, both with functional and object oriented programming methods. I created a few feature-minimalistic websites.
Professionals may agree about PHP not being a programming language that encourages good development habits. (I believe it's not the task of the tool, but this doesn't matter.) Furthermore, its performance is also controversial and often said to be poor compared to competitors.
In the 42nd podcast at Stack Overflow blog a developer from Poland asked what language he should learn in order to improve his skills. Jeff and Joel suggested that every one of them would help, altough there are specific ones that are better in some ways.
Despite they made some great points, it didn't help me that much.
From a beginner point of view, there are not one may not see (correction suggested by S. Lott) many differences between Perl & Python. I would like You to emphasize their strenghts and weaknesses and name a few unique services.
Of course, this wouldn't be fair as I could also check both of them. So here's my wishlist and requirements to help You help me.
First of all, I'd like to follow OOP structures and use it fundamentally. I partly planned a multiuser CMS using MySQL and XML, so the greater the implementations are, the better. Due to its foreseen nature, string manipulation will be used intensively.
If there aren't great differences, comparisons should probably mention syntax and other tiny details that don't matter in the first place.
So, here's my question: which one should I try first -- Perl || Python?
Conclusion
Both Perl and Python have their own fans, which is great. I'd like to say I'm grateful for all participation -- there is no trace of any flame war.
I accepted the most valued answer, although there are many great mini-articles below. As suggested more often, I will go with Python first. Then I'll try Perl later on. Let me see which one fits my mind better.
During the development of my special CMS, I'm going to ask more regarding programming doubts -- because developers now can count on each other! Thank you.
Edit: There were some people suggesting to choose Ruby or Java instead. Java has actually disappointed me. Maybe it has great features, maybe it hasn't. I wouldn't enjoy using it.
In addition, I was told to use Ruby. So far, most of the developers I communicate with have quite bad opinion about Ruby. I'll see it myself, but that's the last element on my priority list.
|
Perl is a very nice language and CPAN has a ton of mature modules that will save you a lot of time. Furthermore, Perl is really moving forwards nowadays with a lot of interesting projects (unlike what uninformed fanboys like to spread around). Even a Perl 6 implementation is by now releasing working Perl 6.
I you want to do OO, I would recommend Moose.
|
Python equivalent to java.util.SortedSet?
|
Does anybody know if Python has an equivalent to Java's SortedSet interface?
Heres what I'm looking for: lets say I have an object of type foo, and I know how to compare two objects of type foo to see whether foo1 is "greater than" or "less than" foo2. I want a way of storing many objects of type foo in a list L, so that whenever I traverse the list L, I get the objects in order, according to the comparison method I define.
Edit:
I guess I can use a dictionary or a list and sort() it every time I modify it, but is this the best way?
|
You can use insort from the bisect module to insert new elements efficiently in an already sorted list:
from bisect import insort
items = [1,5,7,9]
insort(items, 3)
insort(items, 10)
print items # -> [1, 3, 5, 7, 9, 10]
Note that this does not directly correspond to SortedSet, because it uses a list. If you insert the same item more than once you will have duplicates in the list.
|
Performance Advantages to Iterators?
|
What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that.
|
There's actually a very good mail on the python mailing list about this: Iterators vs Lists. It's a bit dated (from 2003), but as far as I know, it's still valid.
Here's the summary:
For small datasets, iterator and list based approaches have similar
performance.
For larger datasets, iterators save both time and space.
What I would draw from it is this: iterators are to be preferred over loading data into a list if possible. But unless you have a big dataset, don't contort your code to make something that should fit in a list to work with an iterator.
|
How to query as GROUP BY in django?
|
I query a model,
Members.objects.all()
and it returns say
Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
What i want is, to know the best Django way to fire
a group_by query to my db, as like,
Members.objects.all().group_by('designation')
Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.
|
If you mean to do aggregation and are using Django 1.1 (currently in alpha 1), you can use the new aggregation features of the ORM:
from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))
This results in a query similar to
SELECT designation, COUNT(designation) AS dcount
FROM members GROUP BY designation
and the output would be of the form
[{'designation': 'Salesman', 'dcount': 2},
{'designation': 'Manager', 'dcount': 2}]
|
Deploying Google Analytics With Django
|
We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.
There are a few ways we could deal with this:
have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <script> elements,
maintain a branch which we pull into before deploying to the production server, which we ensure includes the <script> elements,
do something with Google Analytics to block hits to 127.0.0.1 or localhost, or
something else.
The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a google_analytics variable into all of our views?
What are your thoughts?
|
First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this.
Then, create a setting, GOOGLE_ANALYTICS_KEY. In dev.py set it to the empty string. In prod.py, set it to your key, something like "UA-124465-1". Create a context processor to add this setting to all your template contexts, either as GOOGLE_ANALYTICS_KEY, or just go ahead and add your settings module. Then, in your template, use it to conditionally include your analytics code:
{% if settings.GOOGLE_ANALYTICS_KEY %}
<script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script>
{% endif %}
|
Why avoid CGI for Python with LAMP hosting?
|
I have been using PHP for years. Lately I've come across numerous forum posts stating that PHP is outdated, that modern programming languages are easier, more secure, etc. etc.
So, I decided to start learning Python. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with:
addtype text/html py
addhandler cgi-script .py
Then, my sample pages look like:
#!/usr/bin/python
print "content-type: text/html\n\n"
print "html tags, more stuff, etc."
This works fine. But, I came across a comment in a post that said that CGI isn't the best way to use Python. Of course, it didn't mention what is the best way.
Why is it that using CGI is not the best way to use Python? What is the alternative?
Is there some totally other way to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files?
Related
Pros and Cons of different approaches to web programming in Python
Whatâs a good lightweight Python MVC framework? (esp., @Kevin Dangoor's answer)
How do I use python for web development without relying on a framework?
Python Web Framework - Not App Framework or CMS Framework
Python web programming
|
Classic CGI isn't the best way to use anything at all. With classic CGI server has to spawn a new process for every request.
As for Python, you have few alternatives:
mod_wsgi
mod_python
fastcgi
standalone Python web server (built-in, CherryPy, Tracd )
standalone Python web server on non-standard port and mod_proxy in Apache
|
Interruptible thread join in Python
|
Is there any way to wait for termination of a thread, but still intercept signals?
Consider the following C program:
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
It ends after one second and prints:
Killing
Handling 10
In contrast, here's my attempt to write it in Python:
#!/usr/bin/env python
import signal, time, threading, os, sys
def handler(signum, frame):
print("Handling " + str(signum) + ", frame:" + str(frame))
exit(42)
signal.signal(signal.SIGUSR1, handler)
def server_thread():
time.sleep(10)
print("Served")
servth = threading.Thread(target=server_thread)
servth.start()
def kill_thread():
time.sleep(1) # Let the main thread join
print("Killing")
os.kill(os.getpid(), signal.SIGUSR1)
killth = threading.Thread(target=kill_thread)
killth.start()
servth.join()
print("Main thread finished")
It prints:
Killing
Served
Handling 10, frame:<frame object at 0x12649c0>
How do I make it behave like the C version?
|
Threads in Python are somewhat strange beasts given the global interpreter lock. You may not be able to achieve what you want without resorting to a join timeout and isAlive as eliben suggests.
There are two spots in the docs that give the reason for this (and possibly more).
The first:
From http://docs.python.org/library/signal.html#module-signal:
Some care must be taken if both
signals and threads are used in the
same program. The fundamental thing to
remember in using signals and threads
simultaneously is: always perform
signal() operations in the main thread
of execution. Any thread can perform
an alarm(), getsignal(), pause(),
setitimer() or getitimer(); only the
main thread can set a new signal
handler, and the main thread will be
the only one to receive signals (this
is enforced by the Python signal
module, even if the underlying thread
implementation supports sending
signals to individual threads). This
means that signals canât be used as a
means of inter-thread communication.
Use locks instead.
The second, from http://docs.python.org/library/thread.html#module-thread:
Threads interact strangely with interrupts: the KeyboardInterrupt exception will be
received by an arbitrary thread. (When the signal module is available, interrupts
always go to the main thread.)
EDIT: There was a decent discussion of the mechanics of this on the python bug tracker here: http://bugs.python.org/issue1167930. Of course, it ends with Guido saying: " That's unlikely to go away, so you'll just have to live
with this. As you've discovered, specifying a timeout solves the issue
(sort of)." YMMV :-)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.