instruction
stringlengths 12
148
| input
stringlengths 16
30.2k
| output
stringlengths 11
27.3k
|
|---|---|---|
How to re import an updated package while in Python Interpreter?
|
I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.
|
"Reload is no longer a function in Python 3. Use imp.reload() instead" copied from comments
Use the reload builtin function:
https://docs.python.org/2/library/functions.html#reload
When reload(module) is executed:
Python modulesâ code is recompiled and the module-level code reexecuted, defining a new set of objects which are bound to names in the moduleâs dictionary. The init function of extension modules is not called a second time.
As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero.
The names in the module namespace are updated to point to any new or changed objects.
Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired.
Example:
# Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' > mymodule.py
# Run the module
shell2$ python
>>> import mymodule
>>> mymodule.x()
version 1
# Change mymodule to print "version 2" (without exiting the python REPL)
shell2$ echo 'def x(): print "version 2"' > mymodule.py
# Back in that same python session
>>> reload(mymodule)
<module 'mymodule' from 'mymodule.pyc'>
>>> mymodule.x()
version 2
|
Is it safe to yield from within a "with" block in Python (and why)?
|
The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.
The basic question is whether or not something like this works:
def coroutine():
with open(path, 'r') as fh:
for line in fh:
yield line
Which it does. (You can test it!)
The deeper concern is that with is supposed to be something an alternative to finally, where you ensure that a resource is released at the end of the block. Coroutines can suspend and resume execution from within the with block, so how is the conflict resolved?
For example, if you open a file with read/write both inside and outside a coroutine while the coroutine hasn't yet returned:
def coroutine():
with open('test.txt', 'rw+') as fh:
for line in fh:
yield line
a = coroutine()
assert a.next() # Open the filehandle inside the coroutine first.
with open('test.txt', 'rw+') as fh: # Then open it outside.
for line in fh:
print 'Outside coroutine: %r' % repr(line)
assert a.next() # Can we still use it?
Update
I was going for write-locked file handle contention in the previous example, but since most OSes allocate filehandles per-process there will be no contention there. (Kudos to @Miles for pointing out the example didn't make too much sense.) Here's my revised example, which shows a real deadlock condition:
import threading
lock = threading.Lock()
def coroutine():
with lock:
yield 'spam'
yield 'eggs'
generator = coroutine()
assert generator.next()
with lock: # Deadlock!
print 'Outside the coroutine got the lock'
assert generator.next()
|
I don't really understand what conflict you're asking about, nor the problem with the example: it's fine to have two coexisting, independent handles to the same file.
One thing I didn't know that I learned in response to your question it that there is a new close() method on generators:
close() raises a new GeneratorExit exception inside the generator to terminate the iteration. On receiving this exception, the generatorâs code must either raise GeneratorExit or StopIteration.
close() is called when a generator is garbage-collected, so this means the generatorâs code gets one last chance to run before the generator is destroyed. This last chance means that try...finally statements in generators can now be guaranteed to work; the finally clause will now always get a chance to run. This seems like a minor bit of language trivia, but using generators and try...finally is actually necessary in order to implement the with statement described by PEP 343.
http://docs.python.org/whatsnew/2.5.html#pep-342-new-generator-features
So that handles the situation where a with statement is used in a generator, but it yields in the middle but never returnsâthe context manager's __exit__ method will be called when the generator is garbage-collected.
Edit:
With regards to the file handle issue: I sometimes forget that there exist platforms that aren't POSIX-like. :)
As far as locks go, I think RafaÅ Dowgird hits the head on the nail when he says "You just have to be aware that the generator is just like any other object that holds resources." I don't think the with statement is really that relevant here, since this function suffers from the same deadlock issues:
def coroutine():
lock.acquire()
yield 'spam'
yield 'eggs'
lock.release()
generator = coroutine()
generator.next()
lock.acquire() # whoops!
|
python convert microsoft office docs to plain text on linux
|
Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office.
|
You can access OpenOffice via Python API.
Try using this as a base: http://wiki.services.openoffice.org/wiki/Odt2txt.py
|
Pythonic ways to use 'else' in a for loop
|
I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statement. I'd rather set the looping condition complex. Would I be able to get any benefit out of it, if I don't like to use break statement anyway.
Worth noting that for loop has an else since the language inception, the first ever version.
|
What could be more pythonic than PyPy?
Look at what I discovered starting at line 284 in ctypes_configure/configure.py:
for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
else:
raise AssertionError("unenforceable alignment %d" % (
info['align'],))
And here, from line 425 in pypy/annotation/annrpython.py (clicky)
if cell.is_constant():
return Constant(cell.const)
else:
for v in known_variables:
if self.bindings[v] is cell:
return v
else:
raise CannotSimplify
In pypy/annotation/binaryop.py, starting at line 751:
def is_((pbc1, pbc2)):
thistype = pairtype(SomePBC, SomePBC)
s = super(thistype, pair(pbc1, pbc2)).is_()
if not s.is_constant():
if not pbc1.can_be_None or not pbc2.can_be_None:
for desc in pbc1.descriptions:
if desc in pbc2.descriptions:
break
else:
s.const = False # no common desc in the two sets
return s
A non-one-liner in pypy/annotation/classdef.py, starting at line 176:
def add_source_for_attribute(self, attr, source):
"""Adds information about a constant source for an attribute.
"""
for cdef in self.getmro():
if attr in cdef.attrs:
# the Attribute() exists already for this class (or a parent)
attrdef = cdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
# we should reflow from all the reader's position,
# but as an optimization we try to see if the attribute
# has really been generalized
if attrdef.s_value != s_prev_value:
attrdef.mutated(cdef) # reflow from all read positions
return
else:
# remember the source in self.attr_sources
sources = self.attr_sources.setdefault(attr, [])
sources.append(source)
# register the source in any Attribute found in subclasses,
# to restore invariant (III)
# NB. add_constant_source() may discover new subdefs but the
# right thing will happen to them because self.attr_sources
# was already updated
if not source.instance_level:
for subdef in self.getallsubdefs():
if attr in subdef.attrs:
attrdef = subdef.attrs[attr]
s_prev_value = attrdef.s_value
attrdef.add_constant_source(self, source)
if attrdef.s_value != s_prev_value:
attrdef.mutated(subdef) # reflow from all read positions
Later in the same file, starting at line 307, an example with an illuminating comment:
def generalize_attr(self, attr, s_value=None):
# if the attribute exists in a superclass, generalize there,
# as imposed by invariant (I)
for clsdef in self.getmro():
if attr in clsdef.attrs:
clsdef._generalize_attr(attr, s_value)
break
else:
self._generalize_attr(attr, s_value)
|
Is there a function in Python to list the attributes and methods of a particular object?
|
Is there a function in Python to list the attributes and methods of a particular object?
Something like:
ShowAttributes ( myObject )
-> .count
-> .size
ShowMethods ( myObject )
-> len
-> parse
|
You want to look at the dir() function:
>>> li = []
>>> dir(li)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
li is a list, so dir(li) returns a list of all the methods of a list. Note that the returned list contains the names of the methods as strings, not the methods themselves.
Edit in response to comment:
No this will show all inherited methods as well. Consider this example:
test.py:
class Foo:
def foo(): pass
class Bar(Foo):
def bar(): pass
Python interpreter:
>>> from test import Foo, Bar
>>> dir(Foo)
['__doc__', '__module__', 'foo']
>>> dir(Bar)
['__doc__', '__module__', 'bar', 'foo']
You should note that Python's documentation states:
Note: Because dir() is supplied
primarily as a convenience for use at
an interactive prompt, it tries to
supply an interesting set of names
more than it tries to supply a
rigorously or consistently defined set
of names, and its detailed behavior
may change across releases. For
example, metaclass attributes are not
in the result list when the argument
is a class.
Therefore it's not safe to use in your code. Use vars() instead. Vars() doesn't include information about the superclasses, you'd have to collect them yourself.
If you're using dir() to find information in an interactive interpreter, consider the use of help().
|
How do I do a not equal in Django queryset filtering?
|
In Django model QuerySets, I see that there is a __gt and __lt for comparitive values, but is there a __ne/!=/<> (not equals?)
I want to filter out using a not equals:
Example:
Model:
bool a;
int x;
I want
results = Model.objects.exclude(a=true, x!=5)
The != is not correct syntax. I tried __ne, <>.
I ended up using:
results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5)
|
Maybe Q objects could be of help for this problem. I've never used them but it seems they can be negated and combined much like normal python expressions.
Update: I Just tried it out, it seems to work pretty well:
>>> from myapp.models import Entry
>>> from django.db.models import Q
>>> Entry.objects.filter(~Q(id = 3))
[<Entry: Entry object>, <Entry: Entry object>, <Entry: Entry object>, ...]
|
Is there a better Python bundle for textmate than the one in the bundle repository?
|
At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete?
EDIT:
I am fully aware that there are editors and environments that are better suited to Python development, but I am really just interested to see if there is a third party Textmate bundle available.
|
I took a look and noticed that there has been a lot of work on Python-related bundles recently. Also, it seems I missed the memo on the best new way to get bundles:
Install GetBundles
|
How do I make a command line text editor?
|
I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries to do command-line applications?
|
try python curses module , it is a command-line graphic operation library.
|
What's a standard way to do a no-op in python?
|
I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the code you can see what happens as a result of each option. How do I code the no-op? Currently, I'm doing it like this:
no_op = 0
if x == 0:
y = 2 * a
elif x == 1:
z = 3 * b
elif x == 3:
no_op
(The code is actually quite a bit longer than that, and more complicated. This is just to illustrate the structure).
I don't like using a variable as a no-op, but it's the neatest way I could think of. Is there a better way?
|
Use pass for no-op:
if x == 0:
pass
else:
print "x not equal 0"
And here's another example:
def f():
pass
Or:
class c:
pass
|
Log all errors to console or file on Django site
|
How can I get Django 1.0 to write all errors to the console or a log file when running runserver in debug mode?
I've tried using a middleware class with process_exception function as described in the accepted answer to this question:
http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-django-sites
The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors? But then I would expect runserver to complain if it was a compile-time error and it doesn't.
I've watched Simon Willison's fantastic presentation on Django debugging (http://simonwillison.net/2008/May/22/debugging/) but I didn't see an option that would work well for me.
In case it's relevant, I'm writing a Facebook app and Facebook masks HTTP 500 errors with their own message rather than showing Django's awesomely informative 500 page. So I need a way for all types of errors to be written to the console or file.
Edit: I guess my expectation is that if Django can return a 500 error page with lots of detail when I have a bad import (ImportError) in urls.py, it should be able to write the same detail to the console or a file without having to add any additional exception handling to the code. I've never seen exception handling around import statements.
Thanks,
Jeff
|
It's a bit extreme, but for debugging purposes, you can turn on the DEBUG_PROPAGATE_EXCEPTIONS setting. This will allow you to set up your own error handling. The easiest way to set up said error handling would be to override sys.excepthook. This will terminate your application, but it will work. There may be things you can do to make this not kill your app, but this will depend on what platform you're deploying this for. At any rate, never use this in production!
For production, you're pretty much going to have to have extensive error handling in place. One technique I've used is something like this:
>>> def log_error(func):
... def _call_func(*args, **argd):
... try:
... func(*args, **argd)
... except:
... print "error" #substitute your own error handling
... return _call_func
...
>>> @log_error
... def foo(a):
... raise AttributeError
...
>>> foo(1)
error
If you use log_error as a decorator on your view, it will automatically handle whatever errors happened within it.
The process_exception function is called for some exceptions (eg: assert(False) in views.py) but process_exception is not getting called for other errors like ImportErrors (eg: import thisclassdoesnotexist in urs.py). I'm new to Django/Python. Is this because of some distinction between run-time and compile-time errors?
In Python, all errors are run-time errors. The reason why this is causing problems is because these errors occur immediately when the module is imported before your view is ever called. The first method I posted will catch errors like these for debugging. You might be able to figure something out for production, but I'd argue that you have worse problems if you're getting ImportErrors in a production app (and you're not doing any dynamic importing).
A tool like pylint can help you eliminate these kinds of problems though.
|
How do you determine if an IP address is private, in Python?
|
In Python, what is the best way to determine if an IP address (e.g., '127.0.0.1' or '10.98.76.6') is on a private network? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?
|
Check out the IPy module. If has a function iptype() that seems to do what you want:
>>> from IPy import IP
>>> ip = IP('127.0.0.0/30')
>>> ip.iptype()
'PRIVATE'
|
Pythonic way to implement a tokenizer
|
I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?
I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.
Listing Token Types:
In Java, for example, I would have a list of fields like so:
public static final int TOKEN_INTEGER = 0
But, obviously, there's no way (I think) to declare a constant variable in Python, so I could just replace this with normal variable declarations but that doesn't strike me as a great solution since the declarations could be altered.
Returning Tokens From The Tokenizer:
Is there a better alternative to just simply returning a list of tuples e.g.
[ (TOKEN_INTEGER, 17), (TOKEN_STRING, "Sixteen")]?
Cheers,
Pete
|
There's an undocumented class in the re module called re.Scanner. It's very straightforward to use for a tokenizer:
import re
scanner=re.Scanner([
(r"[0-9]+", lambda scanner,token:("INTEGER", token)),
(r"[a-z_]+", lambda scanner,token:("IDENTIFIER", token)),
(r"[,.]+", lambda scanner,token:("PUNCTUATION", token)),
(r"\s+", None), # None == skip token.
])
results, remainder=scanner.scan("45 pigeons, 23 cows, 11 spiders.")
print results
will result in
[('INTEGER', '45'),
('IDENTIFIER', 'pigeons'),
('PUNCTUATION', ','),
('INTEGER', '23'),
('IDENTIFIER', 'cows'),
('PUNCTUATION', ','),
('INTEGER', '11'),
('IDENTIFIER', 'spiders'),
('PUNCTUATION', '.')]
I used re.Scanner to write a pretty nifty configuration/structured data format parser in only a couple hundred lines.
|
Is it bad form to call a classmethod as a method from an instance?
|
Ex.
If I have something like this:
class C(object):
@classmethod
def f(cls, x):
return x + x
This will work:
c = C()
c.f(2)
4
But is that bad form?
Should I only call
C.f()
or
c.__class__.f()
Obviously, this would only make sense in cases where f doesn't interact with self/cls expecting it to be class.
?
|
If you are tempted to call a class method from an instance you probably don't need a class method.
In the example you gave a static method would be more appropriate precisely because of your last remark (no self/cls interaction).
class C(object):
@staticmethod
def f(x):
return x + x
this way it's "good form" to do both
c = C()
c.f(2)
and
C.f(2)
|
How can you find unused functions in Python code?
|
So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?
I've seen these two references: Find unused code and Tool to find unused functions in php project, but they seem specific to C# and PHP, respectively.
Is there a Python tool that'll help you find functions that aren't referenced anywhere else in the source code (notwithstanding reflection/etc.)?
|
In python you can find unused code by using dynamic or static code analyzers. Two examples for dynamic analyzers are coverage and figleaf. They have the drawback that you have to run all possible branches of your code in order to find unused parts, but they also have the advantage that you get very reliable results.
Alternatively, you can use static code analyzers, that just look at your code, but don't actually run it. This has the advantage that they run much faster, but due to python's dynamic nature the results are not 100% percent accurate and you might want to double-check them.
Two tools that come to mind here are pyflakes and vulture. They are complementary: Pyflakes finds unused imports and unused local variables while vulture finds unused functions, methods, classes, variables and attributes.
The tools are all available at the Python Package Index http://pypi.python.org/pypi.
|
Detect in python which keys are pressed
|
I need to know which key is being pressed right now. I'm not looking to capture some specific keys to trigger an event or anything like that,
I want to know which keys are pressed now and display a list of them.
I also need to capture special keys like F1 ... F12, shift, alt, home, windows, etc. Basically all keys on the keyboard.
How do I do this in python? How do I capture keyboard events?
Related
Cross platform keylogger
Is there a cross-platform python low-level API to capture or generate keyboard events?
EDIT
Just so you know I'm not trying to make a keylogger. I'm trying to make a diagnoses tool (I split water on my laptop and the keyboard is starting to get crazy sometime!!)
|
PyKeylogger mentioned in the related question might do the job.
|
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x?
|
Google is sponsoring an Open Source project to increase the speed of Python by 5x.
Unladen-Swallow seems to have a good project plan
Why is concurrency such a hard problem?
Is LLVM going to solve the concurrency problem?
Are there solutions other than Multi-core for Hardware advancement?
|
LLVM is several things together - kind of a virtual machine/optimizing compiler, combined with different frontends that take the input in a particular language and output the result in an intermediate language. This intermediate output can be run with the virtual machine, or can be used to generate a standalone executable.
The problem with concurrency is that, although it was used for a long time in scientific computing, it has just recently has become common in consumer apps. So while it's widely known how to program a scientific calculation program to achieve great performance, it is completely different thing to write a mail user agent/word processor that can be good at concurrency. Also, most of the current OS's were being designed with a single processor in mind, and they may not be fully prepared for multicore processors.
The benefit of LLVM with respect to concurrency is that you have an intermediate output, and if in the future there are advances in concurrency, then by updating your interpreter you instantly gain those benefits in all LLVM-compiled programs. This is not so easy if you had compiled to a standalone executable. So LLVM doesn't solve the concurrency problem per se but it leaves an open door for future enhancements.
Sure there are more possible advances for the hardware like quantum computers, genetics computers, etc. But we have to wait for them to become a reality.
|
Re-raise exception with a different type and message, preserving existing information
|
I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a FooError abstract class for all the foo module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many of the exceptions raised from the module are raised because of some other exception; e.g. failing at some task because of an OSError on a file.
What I need is to âwrapâ the exception caught such that it has a different type and message, so that information is available further up the propagation hierarchy by whatever catches the exception. But I don't want to lose the existing type, message, and stack trace; that's all useful information for someone trying to debug the problem. A top-level exception handler is no good, since I'm trying to decorate the exception before it makes its way further up the propagation stack, and the top-level handler is too late.
This is partly solved by deriving my module foo's specific exception types from the existing type (e.g. class FooPermissionError(OSError, FooError)), but that doesn't make it any easier to wrap the existing exception instance in a new type, nor modify the message.
Python's PEP 3134 âException Chaining and Embedded Tracebacksâ discusses a change accepted in Python 3.0 for âchainingâ exception objects, to indicate that a new exception was raised during the handling of an existing exception.
What I'm trying to do is related: I need it also working in earlier Python versions, and I need it not for chaining, but only for polymorphism. What is the right way to do this?
|
Python 3 introduced exception chaining (as described in PEP 3134). This allows raising an exception, citing an existing exception as the âcauseâ:
try:
frobnicate()
except KeyError as exc:
raise ValueError("Bad grape") from exc
In Python 2, it appears this use case has no good answer (as described by Ian Bicking and Ned Batchelder). Bummer.
|
How do I configure Eclipse to launch a browser when Run or Debug is selected using Pydev plugin
|
I'm learning Python and Django using the Eclipse Pydev plugin. I want the internal or external browser to launch or refresh with the URL http:/127.0.0.1 when I press Run or Debug. I've seen it done with the PHP plugins but not Pydev.
|
Here are the steps to set up an external launch configuration to launch IE:
Select Run->External Tools->External Tools Configurations...
In the left hand pane, select Program then the new icon (left-most icon above the pane).
In the right hand pane, select the Main tab.
Enter launch_ie in the Name: field.
Enter ${system_path:explorer.exe} in the Location: field.
Enter http:/127.0.0.1 in the Arguments field.
To run the external configuration, select Run.
If you want to share the configuration you can use these optional steps:
Select the Common tab
Select the Shared file: option in the Save As section.
Select a location to save the configuration (saving it to an otherwise empty project might be a good idea, as you can import that to another workspace)
To rerun the configuration you have a few choices:
Select the External Tools icon from the menu bar http://help.eclipse.org/ganymede/topic/org.eclipse.cdt.doc.user/images/icon%5Fext%5Ftools.png" alt="external tools icon" /> then click launch_ie
Select Run->External Tools->launch ie
Hit Alt+R, E, 1 (assuming launch_ie is the first item in the list, otherwise pick the appropriate number)
|
How do I get the filepath for a class in Python?
|
Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.
The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that uses a Django template to render itself as HTML. The base implementation should infer the filename for the template based on the filename that the class is defined in.
Say I put a class LocationArtifact in the file "base/artifacts.py", then I want the default behaviour to be that the template name is "base/LocationArtifact.html".
|
You can use the inspect module, like this:
import inspect
inspect.getfile(C.__class__)
|
abstracting the conversion between id3 tags, m4a tags, flac tags
|
I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".
Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library that handles all the fiddly bits and knows fieldname equivalences. For things not all tag systems can express, I'm okay with information being lost or best-guessed.
(Use case: I encode lossless files to mp3, then go use the mp3s for listening. Every month or so, I want to be able to update the 'master' lossless files with whatever tag changes I've made to the mp3s. I'm tired of stubbing my toes on implementation differences among formats.)
|
I needed this exact thing, and I, too, realized quickly that mutagen is not a distant enough abstraction to do this kind of thing. Fortunately, the authors of mutagen needed it for their media player QuodLibet.
I had to dig through the QuodLibet source to find out how to use it, but once I understood it, I wrote a utility called sequitur which is intended to be a command line equivalent to ExFalso (QuodLibet's tagging component). It uses this abstraction mechanism and provides some added abstraction and functionality.
If you want to check out the source, here's a link to the latest tarball. The package is actually a set of three command line scripts and a module for interfacing with QL. If you want to install the whole thing, you can use:
easy_install QLCLI
One thing to keep in mind about exfalso/quodlibet (and consequently sequitur) is that they actually implement audio metadata properly, which means that all tags support multiple values (unless the file type prohibits it, which there aren't many that do). So, doing something like:
print qllib.AudioFile('foo.mp3')['artist']
Will not output a single string, but will output a list of strings like:
[u'The First Artist', u'The Second Artist']
The way you might use it to copy tags would be something like:
import os.path
import qllib # this is the module that comes with QLCLI
def update_tags(mp3_fn, flac_fn):
mp3 = qllib.AudioFile(mp3_fn)
flac = qllib.AudioFile(flac_fn)
# you can iterate over the tag names
# they will be the same for all file types
for tag_name in mp3:
flac[tag_name] = mp3[tag_name]
flac.write()
mp3_filenames = ['foo.mp3', 'bar.mp3', 'baz.mp3']
for mp3_fn in mp3_filenames:
flac_fn = os.path.splitext(mp3_fn)[0] + '.flac'
if os.path.getmtime(mp3_fn) != os.path.getmtime(flac_fn):
update_tags(mp3_fn, flac_fn)
|
How can I parse a time string containing milliseconds in it with python?
|
I am able to parse strings containing date/time with time.strptime
>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)
How can I parse a time string that contains milliseconds?
>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/_strptime.py", line 333, in strptime
data_string[found.end():])
ValueError: unconverted data remains: .123
|
Python 2.6 added a new strftime/strptime macro %f, which does microseconds. Not sure if this is documented anywhere. But if you're using 2.6 or 3.0, you can do this:
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
Edit: I never really work with the time module, so I didn't notice this at first, but it appears that time.struct_time doesn't actually store milliseconds/microseconds. You may be better off using datetime, like this:
>>> from datetime import datetime
>>> a = datetime.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
>>> a.microsecond
123000
|
Python: Do Python Lists keep a count for len() or does it count for each call?
|
If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background?
|
Don't worry: Of course it saves the count and thus len() on lists is a pretty cheap operation. Same is true for strings, dictionaries and sets, by the way!
|
Suppress output in Python calls to executables
|
I have a binary named A that generates output when called. If I call it from a Bash shell, most of the output is suppressed by A > /dev/null. All of the output is suppressed by A &> /dev/null
I have a python script named B that needs to call A. I want to be able to generate output from B, while suppressing all the output from A.
From within B, I've tried os.system('A'), os.system('A > /dev/null'), and os.system('A &> /dev/null'), os.execvp('...'), etc. but none of those suppress all the output from A.
I could run B &> /dev/null, but that suppresses all of B's output too and I don't want that.
Anyone have suggestions?
|
import os
import subprocess
command = ["executable", "argument_1", "argument_2"]
with open(os.devnull, "w") as fnull:
result = subprocess.call(command, stdout = fnull, stderr = fnull)
If the command doesn't have any arguments, you can just provide it as a simple string.
If your command relies on shell features like wildcards, pipes, or environment variables, you'll need to provide the whole command as a string, and also specify shell = True. This should be avoided, though, since it represents a security hazard if the contents of the string aren't carefully validated.
|
What's the best way to tell if a Python program has anything to read from stdin?
|
I want a program to do one thing if executed like this:
cat something | my_program.py
and do another thing if run like this
my_program.py
But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read before trying to read from stdin.
|
If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:
$ python -c 'import sys; print sys.stdin.isatty()'
True
$ echo | python -c 'import sys; print sys.stdin.isatty()'
False
|
Python/Django: Creating a simpler list from values_list()
|
Consider:
>>>jr.operators.values_list('id')
[(1,), (2,), (3,)]
How does one simplify further to:
['1', '2', '3']
The purpose:
class ActivityForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
if self.initial['job_record']:
jr = JobRecord.objects.get(pk=self.initial['job_record'])
# Operators
self.fields['operators'].queryset = jr.operators
# select all operators by default
self.initial['operators'] = jr.operators.values_list('id') # refined as above.
|
Use the flat=True construct of the django queryset: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list
From the example in the docs:
>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]
|
Python HTML sanitizer / scrubber / filter
|
I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist.
|
Use lxml.html.clean! It's VERY easy!
from lxml.html.clean import clean_html
print clean_html(html)
Suppose the following html:
html = '''\
<html>
<head>
<script type="text/javascript" src="evil-site"></script>
<link rel="alternate" type="text/rss" src="evil-rss">
<style>
body {background-image: url(javascript:do_evil)};
div {color: expression(evil)};
</style>
</head>
<body onload="evil_function()">
<!-- I am interpreted for EVIL! -->
<a href="javascript:evil_function()">a link</a>
<a href="#" onclick="evil_function()">another link</a>
<p onclick="evil_function()">a paragraph</p>
<div style="display: none">secret EVIL!</div>
<object> of EVIL! </object>
<iframe src="evil-site"></iframe>
<form action="evil-site">
Password: <input type="password" name="password">
</form>
<blink>annoying EVIL!</blink>
<a href="evil-site">spam spam SPAM!</a>
<image src="evil!">
</body>
</html>'''
The results...
<html>
<body>
<div>
<style>/* deleted */</style>
<a href="">a link</a>
<a href="#">another link</a>
<p>a paragraph</p>
<div>secret EVIL!</div>
of EVIL!
Password:
annoying EVIL!
<a href="evil-site">spam spam SPAM!</a>
<img src="evil!">
</div>
</body>
</html>
You can customize the elements you want to clean and whatnot.
|
Python int to binary?
|
Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.
|
Python's string format method can take a format spec.
>>> "{0:b}".format(10)
'1010'
Format spec docs for Python 2
Format spec docs for Python 3
|
Nested try statements in python?
|
Is there a nicer way of doing the following:
try:
a.method1()
except AttributeError:
try:
a.method2()
except AttributeError:
try:
a.method3()
except AttributeError:
raise
It looks pretty nasty and I'd rather not do:
if hasattr(a, 'method1'):
a.method1()
else if hasattr(a, 'method2'):
a.method2()
else if hasattr(a, 'method3'):
a.method3()
else:
raise AttributeError
to maintain maximum efficiency.
|
Perhaps you could try something like this:
def call_attrs(obj, attrs_list, *args):
for attr in attrs_list:
if hasattr(obj, attr):
bound_method = getattr(obj, attr)
return bound_method(*args)
raise AttributeError
You would call it like this:
call_attrs(a, ['method1', 'method2', 'method3'])
This will try to call the methods in the order they are in in the list. If you wanted to pass any arguments, you could just pass them along after the list like so:
call_attrs(a, ['method1', 'method2', 'method3'], arg1, arg2)
|
Convert HTML entities to Unicode and vice versa
|
Possible duplicates:
Convert XML/HTML Entities into Unicode String in Python
HTML Entity Codes to Text
How do you convert HTML entities to Unicode and vice versa in Python?
|
As to the "vice versa" (which I needed myself, leading me to find this question, which didn't help, and subsequently another site which had the answer):
u'some string'.encode('ascii', 'xmlcharrefreplace')
will return a plain string with any non-ascii characters turned into XML (HTML) entities.
|
How do I execute a string containing Python code in Python?
|
How do I execute a string containing Python code in Python?
|
For statements, use exec(string) (Python 2/3) or exec string (Python 2):
>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world
When you need the value of an expression, use eval(string):
>>> x = eval("2+2")
>>> x
4
However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.
|
Django vs other Python web frameworks?
|
I've pretty much tried every Python web framework that exists, and it took me a long time to realize there wasn't a silver bullet framework, each had its own advantages and disadvantages. I started out with Snakelets and heartily enjoyed being able to control almost everything at a lower level without much fuss, but then I discovered TurboGears and I have been using it (1.x) ever since. Tools like Catwalk and the web console are invaluable to me.
But with TurboGears 2 coming out which brings WSGI support, and after reading up on the religious debates between the Django and WSGI camps, I'm really torn between "doing it the right way", e.g., learning WSGI, spending valuable time writing functionality that already exists in Django and other full-stack frameworks, as opposed to using Django or some high-level framework that does everything for me. The downsides with the latter that I can see are pretty obvious:
I'm not learning anything in the process
If I ever need to do anything lower level it's going to be a pain
The overhead required for just a basic site which uses authentication is insane. (IMO)
So, I guess my question is, which is the better choice, or is it just a matter of opinion, and should I suck it up and use Django if it achieves what I want with minimal fuss (I want authentication and a CRUD interface to my database)? I tried Werkzeug, Glashammer, and friends, but AuthKit and Repoze scared me off, as well as the number of steps involved to just setup basic authentication. I looked at Pylons, but the documentation seems lacking, and when referencing simple features like authentication or a CRUD interface, various wiki pages and documentation seemed to contradict each other, with different hacks for versions and such.
Thanks to S. Lott for pointing out that I wasn't clear enough. My question is: which of the following is worthwhile in the long run, but not painful in the short (e.g., some sort of middle ground, anyone?) - Learn WSGI, or stick with a "batteries-included" framework? If the latter, I would appreciate a suggestion as to whether I should give Django another try, stick with TurboGears 1.x, or venture into some other framework.
Also, I have tried CherryPy, but couldn't seem to find a good enough CRUD application that I could plop in and use right away.
|
the religious debates between the Django and WSGI camps
It would seem as though you're a tad bit confused about what WSGI is and what Django is. Saying that Django and WSGI are competing is a bit like saying that C and SQL are competing: you're comparing apples and oranges.
Django is a framework, WSGI is a protocol (which is supported by Django) for how the server interacts with the framework. Most importantly, learning to use WSGI directly is a bit like learning assembly. It's a great learning experience, but it's not really something you should do for production code (nor was it intended to be).
At any rate, my advice is to figure it out for yourself. Most frameworks have a "make a wiki/blog/poll in an hour" type exercise. Spend a little time with each one and figure out which one you like best. After all, how can you decide between different frameworks if you're not willing to try them out?
|
How to make Django slugify work properly with Unicode strings?
|
What can I do to prevent slugify filter from stripping out non-ASCII alphanumeric characters? (I'm using Django 1.0.2)
cnprog.com has Chinese characters in question URLs, so I looked in their code. They are not using slugify in templates, instead they're calling this method in Question model to get permalinks
def get_absolute_url(self):
return '%s%s' % (reverse('question', args=[self.id]), self.title)
Are they slugifying the URLs or not?
|
There is a python package called unidecode that I've adopted for the askbot Q&A forum, it works well for the latin-based alphabets and even looks reasonable for greek:
>>> import unidecode
>>> from unidecode import unidecode
>>> unidecode(u'διακÏιÏικÏÏ')
'diakritikos'
It does something weird with asian languages:
>>> unidecode(u'影師å')
'Ying Shi Ma '
>>>
Does this make sense?
In askbot we compute slugs like so:
from unidecode import unidecode
from django.template import defaultfilters
slug = defaultfilters.slugify(unidecode(input_text))
|
How to get number of affected rows in sqlalchemy?
|
I have one question concerning Python and the sqlalchemy module. What is the equivalent for cursor.rowcount in the sqlalchemy Python?
|
Although it isn't really stated in the docs, a ResultProxy object does have a rowcount property as well.
|
How to limit I/O consumption of Python processes (possibly using ionice)?
|
I would like a particular set of Python subprocesses to be as low-impact as possible. I'm already using nice to help limit CPU consumption. But ideally I/O would be limited as well. (If skeptical, please humor me and assume there is value in doing this; it doesn't matter how long they take to run, there can be a lot of them, and there is higher-priority stuff (usually) going on on the same machine, etc.)
One possibility appears to be ionice. Are there any existing Python packages for invoking ionice (Google didn't turn up anything)? It wouldn't be difficult to write code to simply run the ionice command; but I'd prefer to avoid writing code that someone else has written/tested; sometimes there are subtle edge cases, etc. And, is there just a better way to limit I/O consumption?
The man page for ionice suggests that the ionice value can be affected by the nice value, but running this Python 2.6 script appears to disprove that, even for child processes where the nice value is inherited:
#!/usr/bin/env python
import os
import multiprocessing
def print_ionice(name):
print '*** ', name, ' ***'
os.system("echo -n 'nice: '; nice")
os.system("echo -n 'ionice: '; ionice -p%d" % os.getpid())
for niced in (None, 19):
if niced: os.nice(niced)
print '**** niced to: ', niced, ' ****'
print_ionice('parent')
subproc = multiprocessing.Process(target=print_ionice, args=['child'])
subproc.start()
subproc.join()
Which has the following output:
$ uname -as
Linux x.fake.org 2.6.27-11-server #1 SMP Thu Jan 29 20:13:12 UTC 2009 x86_64 GNU/Linux
$ ./foo.py
**** niced to: None ****
*** parent ***
nice: 0
ionice: none: prio 4
*** child ***
nice: 0
ionice: none: prio 4
**** niced to: 19 ****
*** parent ***
nice: 19
ionice: none: prio 4
*** child ***
nice: 19
ionice: none: prio 4
|
psutil exposes this functionality (python 2.4 -> 3.2):
import psutil, os
p = psutil.Process(os.getpid())
p.ionice(psutil.IOPRIO_CLASS_IDLE)
Also, starting from Python 3.3 this will be available in python stdlib as well:
http://bugs.python.org/issue10784
|
Django admin - inline inlines (or, three model editing at once)
|
I've got a set of models that look like this:
class Page(models.Model):
title = models.CharField(max_length=255)
class LinkSection(models.Model):
page = models.ForeignKey(Page)
title = models.CharField(max_length=255)
class Link(models.Model):
linksection = models.ForeignKey(LinkSection)
text = models.CharField(max_length=255)
url = models.URLField()
and an admin.py that looks like this:
class LinkInline(admin.TabularInline):
model = Link
class LinkSectionInline(admin.TabularInline):
model = LinkSection
inlines = [ LinkInline, ]
class PageAdmin(admin.ModelAdmin):
inlines = [ LinkSectionInline, ]
My goal is to get an admin interface that lets me edit everything on one page. The end result of this model structure is that things are generated into a view+template that looks more or less like:
<h1>{{page.title}}</h1>
{% for ls in page.linksection_set.objects.all %}
<div>
<h2>{{ls.title}}</h2>
<ul>
{% for l in ls.link_set.objects.all %}
<li><a href="{{l.url}}">{{l.title}}</a></li>
{% endfor %}
</ul>
</div>
{% endfor %}
I know that the inline-in-an-inline trick fails in the Django admin, as I expected. Does anyone know of a way to allow this kind of three level model editing? Thanks in advance.
|
You need to create a custom form and template for the LinkSectionInline.
Something like this should work for the form:
LinkFormset = forms.modelformset_factory(Link)
class LinkSectionForm(forms.ModelForm):
def __init__(self, **kwargs):
super(LinkSectionForm, self).__init__(**kwargs)
self.link_formset = LinkFormset(instance=self.instance,
data=self.data or None,
prefix=self.prefix)
def is_valid(self):
return (super(LinkSectionForm, self).is_valid() and
self.link_formset.is_valid())
def save(self, commit=True):
# Supporting commit=False is another can of worms. No use dealing
# it before it's needed. (YAGNI)
assert commit == True
res = super(LinkSectionForm, self).save(commit=commit)
self.link_formset.save()
return res
(That just came off the top of my head and isn't tested, but it should get you going in the right direction.)
Your template just needs to render the form and form.link_formset appropriately.
|
URL encode a non-value pair in Python
|
I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable.
query = "string that needs to be encoded"
params = urllib.urlencode(query) # THIS FAILS
# http://code.google.com/apis/ajaxsearch/documentation/reference.html
url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&%s" % (params, GOOGLE_API_KEY)
request = urllib2.Request(url)
request.add_header('Referer', GOOGLE_REFERER)
search_results = urllib2.urlopen(request)
raw_results = search_results.read()
json = simplejson.loads(raw_results)
estimatedResultCount = json['responseData']['cursor']['estimatedResultCount']
if estimatedResultCount != 0:
print "Google: %s hits" % estimatedResultCount
How do I urlencode my search terms?
|
I think you're looking for urllib.quote instead.
|
Anything like SciPy in Ruby?
|
Looking further into the differences between Python and Ruby, is there a Ruby equivalent to SciPy, or what other scientific math gems are available for Ruby?
|
There's nothing quite as mature or well done as SciPy, but check out SciRuby and Numerical Ruby.
|
How would I compute exactly 30 days into the past with Python (down to the minute)?
|
In Python, I'm attempting to retrieve the date/time that is exactly 30 days (30*24hrs) into the past. At present, I'm simply doing:
>>> import datetime
>>> start_date = datetime.date.today() + datetime.timedelta(-30)
Which returns a datetime object, but with no time data:
>>> start_date.year
2009
>>> start_date.hour
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'hour'
|
You want to use a datetime object instead of just a date object:
start_date = datetime.datetime.now() + datetime.timedelta(-30)
date just stores a date and time just a time. datetime is a date with a time.
|
Using pydev with Eclipse on OSX
|
I setup PyDev with this path for the python interpreter
/System/Library/Frameworks/Python.framework/Versions/2.5/Python
since the one under /usr/bin were alias and Eclipse won't select it. I can run my python script now but cannot run the shell as an external tool. The message I get is
variable references empty selection ${resource_loc}
Same if I use {container_loc}
Any thoughts ?
Sunit
|
I installed the Python.org version as well, this is a must.
I finally got PyDev working in Eclipse by pointing the interpreter to:
/Library/Frameworks/Python.framework/Versions/2.6/bin/python
manually. If you don't do it manually (by using the Autoconfig) it seems to not find the right version.
|
Can I transpose a file in Vim?
|
I know I can use AWK but I am on a Windows box. I am making a function for others that may not have AWK. I also know I can write a C program but I would love not have to create maintain and compile something for a little Vim utility I am making.
The original file might be
THE DAY WAS LONG
THE WAY WAS FAST
and it would become
TT
HH
EE
DW
AA
YY
WW
AA
SS
LF
OA
NS
GT
UPDATE: Golf rules apply to selecting correct answer.
UPDATE: Python fans should check out Mr. Duffy's answer below.
|
Here is a command in Vim language. So you don't have to compile Vim with +python support.
function! s:transpose()
let maxcol = 0
let lines = getline(1, line('$'))
for line in lines
let len = len(line)
if len > maxcol
let maxcol = len
endif
endfor
let newlines = []
for col in range(0, maxcol - 1)
let newline = ''
for line in lines
let line_with_extra_spaces = printf('%-'.maxcol.'s', line)
let newline .= line_with_extra_spaces[col]
endfor
call add(newlines, newline)
endfor
1,$"_d
call setline(1, newlines)
endfunction
command! TransposeBuffer call s:transpose()
Put this in newly created .vim file inside vim/plugin dir or put this to your [._]vimrc.
Execute :TransposeBuffer to transpose current buffer
|
How can I convert a character to a integer in Python, and viceversa?
|
I want to get, given a character, its ASCII value.
For example, for the character a, I want to get 97, and vice versa.
|
Use chr() and ord():
>>> chr(97)
'a'
>>> ord('a')
97
|
Does anyone know about workflow frameworks/libraries in Python?
|
I'm searching for a workflow library/framework for Python. I'm astonished that there I cannot find anything which is simple and not attached to Zope/Plone.
Does anyone know of an open-source, simple workflow library/framework. It's preferred to support Django, but not required.
|
Try GoFlow, a workflow engine for Django.
|
Python JSON decoding performance
|
I'm using the json module in Python 2.6 to load and decode JSON files. However I'm currently getting slower than expected performance. I'm using a test case which is 6MB in size and json.loads() is taking 20 seconds.
I thought the json module had some native code to speed up the decoding?
How do I check if this is being used?
As a comparison, I downloaded and installed the python-cjson module, and cjson.decode() is taking 1 second for the same test case.
I'd rather use the JSON module provided with Python 2.6 so that users of my code aren't required to install additional modules.
(I'm developing on Mac OS X, but I getting a similar result on Windows XP.)
|
The new Yajl - Yet Another JSON Library is very fast.
yajl serialize: 0.180 deserialize: 0.182 total: 0.362
simplejson serialize: 0.840 deserialize: 0.490 total: 1.331
stdlib json serialize: 2.812 deserialize: 8.725 total: 11.537
You can compare the libraries yourself.
Update: UltraJSON is even faster.
|
Can you define aliases for imported modules in Python?
|
In Python, is it possible to define an alias for an imported module?
For instance:
import a_ridiculously_long_module_name
...so that is has an alias of 'short_name'.
|
import a_ridiculously_long_module_name as short_name
also works for
import module.submodule.subsubmodule as short_name
|
How do I pass a method as a parameter in python
|
Is it possible to pass a method as a parameter to a method?
self.method2(self.method1)
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun.call()
return result
|
Yes it is, just use the name of the method, as you have written. Methods/functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
FYI, there is no call method - I think it's called __call__, but you don't have to invoke it explicitly:
def method1():
return 'hello world'
def method2(methodToRun):
result = methodToRun()
return result
method2(method1)
|
How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?
|
I have a simple table in mysql with the following fields:
id -- Primary key, int, autoincrement
name -- varchar(50)
description -- varchar(256)
Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id.
In pseudocode:
db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"
db.execute(queryString);
newID = ???
|
I think it might be
newID = db.insert_id()
Edit by Original Poster
Turns out, in the version of MySQLdb that I am using (1.2.2)
You would do the following:
conn = MySQLdb(host...)
c = conn.cursor()
c.execute("INSERT INTO...")
newID = c.lastrowid
I am leaving this as the correct answer, since it got me pointed in the right direction.
|
How to call an external program in python and retrieve the output and return code?
|
How can I call an external program with a python script and retrieve the output and return code?
|
Look at the subprocess module: a simple example follows...
from subprocess import Popen, PIPE
process = Popen(["ls", "-la", "."], stdout=PIPE)
(output, err) = process.communicate()
exit_code = process.wait()
|
Is there a Perl equivalent to Python's `if __name__ == '__main__'`?
|
Is there a way to determine if the current file is the one being executed in Perl source? In Python we do this with the following construct:
if __name__ == '__main__':
# This file is being executed.
raise NotImplementedError
I can hack something together using FindBin and __FILE__, but I'm hoping there's a canonical way of doing this. Thanks!
|
unless (caller) {
print "This is the script being executed\n";
}
See caller. It returns undef in the main script. Note that that doesn't work inside a subroutine, only in top-level code.
|
Create a standalone windows exe which does not require pythonXX.dll
|
is there a way to create a standalone .exe from a python script.
Executables generated with py2exe can run only with pythonXX.dll.
I'd like to obtain a fully standalone .exe which does not require to install the python runtime library.
It looks like a linking problem but using static library instead the dynamic one and it would be also useful to apply a strip in order to remove the unused symbols.
Any idea ?
Thanks.
Alessandro
|
You can do this in the latest version of py2exe... Just add something like the code below in your setup.py file (key part is 'bundle_files': 1).
To include your TkInter package in the install, use the 'includes' key.
distutils.core.setup(
windows=[
{'script': 'yourmodule.py',
'icon_resources': [(1, 'moduleicon.ico')]
}
],
zipfile=None,
options={'py2exe':{
'includes': ['tkinter'],
'bundle_files': 1
}
}
)
|
In Python how can I access "static" class variables within class methods
|
If I have the following python code:
class Foo(object):
bar = 1
def bah(self):
print bar
f = Foo()
f.bah()
It complains
NameError: global name 'bar' is not defined
How can I access class/static variable 'bar' within method 'bah'?
|
Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.
|
questions re: current state of GUI programming with Python
|
I recently did some work modifying a Python gui app that was using wxPython widgets. I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui. I was pretty disappointed at what seems to be the current state of gui programming with Python. I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks. I'd like to move to Python for everything.
But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms. While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL. For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to. Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember. All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.
My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction lower than the gui tools available for Delphi. Net result: gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured. It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.
I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython. I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better. But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL. Some quick investigating into suggested python gui-dev solutions ( http://wiki.python.org/moin/GuiProgramming ) is honestly somewhat depressing for someone used to Delphi or .NET.
Finally, I've got a couple of questions.
First, am I missing something? Is there some gui-development solution for Python that can compare with VCL or WinForms programming? I don't necessarily care if it doesn't quite measure up to Delphi's VCL. I'm just looking for something that's in the same league.
Second, could IronPython be the direction to go? I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in. Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net? It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building). Does VS.NET fully integrate IronPython with gui-building?
It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python. Only this time with Python we'd have a whole new paradigm of fast, cross platform, and open source gui programming. Wouldn't corporations eat that up? Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did. But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.
|
seems your complains are about wxPython, not about Python itself. try pyQt (or is it qtPython?)
but, both wxPython and pyQt are just Python bindings to a C / C++ (respectively) library, it's just as (conceptually) low level as the originals.
but, Qt is far superior to wx
|
How to compare type of an object in Python?
|
Basically I want to do this:
obj = 'str'
type ( obj ) == string
I tried:
type ( obj ) == type ( string )
and it didn't work.
Also, what about the other types? For example, I couldn't replicate NoneType.
|
isinstance()
In your case, isinstance("this is a string", str) will return True.
You may also want to read this: http://www.canonical.org/~kragen/isinstance/
|
Which Python Bayesian text classification modules are similar to dbacl?
|
A quick Google search reveals that there are a good number of Bayesian classifiers implemented as Python modules. If I want wrapped, high-level functionality similar to dbacl, which of those modules is right for me?
Training
% dbacl -l one sample1.txt
% dbacl -l two sample2.txt
Classification
% dbacl -c one -c two sample3.txt -v
one
|
I think you'll find the nltk helpful. Specifically, the classify module.
|
Debugging a running python process
|
Is there a way to see a stacktrace of what various threads are doing inside a python process?
Let's suppose I have a thread which allows me some sort of remote access to the process.
|
Winpdb is a platform independent graphical GPL Python debugger with support for remote debugging over a network, multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb.
Features:
GPL license. Winpdb is Free Software.
Compatible with CPython 2.3 through 2.6 and Python 3000
Compatible with wxPython 2.6 through 2.8
Platform independent, and tested on Ubuntu Gutsy and Windows XP.
User Interfaces: rpdb2 is console based, while winpdb requires wxPython 2.6 or later.
|
Python comments: # vs strings
|
I have a question regarding the "standard" way to put comments inside Python source code:
def func():
"Func doc"
... <code>
'TODO: fix this'
#badFunc()
... <more code>
def func():
"Func doc"
... <code>
#TODO: fix this
#badFunc()
... <more code>
I prefer to write general comments as strings instead of prefixing #'s.
The official python style guide doesn't mention using strings as comments (If I didn't miss it while reading it)
I like it that way mainly because I think the # character looks ugly with comment blocks. As far as I know these strings don't do anything.
The question is: Are there disadvantages in doing this?
|
Don't misuse strings (no-op statements) as comments. Docstrings, e.g. the first string in a module, class or function, are special and definitely recommended.
Note that docstrings are documentation, and documentation and comments are two different things!
Documentation is important to understand what the code does.
Comments explain how the code does it.
Documentation is read by people who use your code, comments by people who want to understand your code, e.g. in order to maintain it.
Using strings for commentation has the following (potential) disadvantages:
It confuses people who don't know that the string does nothing.
Comments and string literals are highlighted differently in code editors, so your style may make your code harder to read.
It might effect performance and/or memory usage (if the strings are not removed during bytecode compilation, removing comments is done on the scanner level so its definitively cheaper)
Most important for Python programmers: It is not pythonic:
There should be one-- and preferably only one --obvious way to do it.
Stick to the standards, use comments.
|
Why do languages like Java use hierarchical package names, while Python does not?
|
I haven't done enterprise work in Java, but I often see the reverse-domain-name package naming convention. For example, for a Stack Overflow Java package you'd put your code underneath package com.stackoverflow.
I just ran across a Python package that uses the Java-like convention, and I wasn't sure what the arguments for and against it are, or whether they apply to Python in the same way as Java. What are the reasons you'd prefer one over the other? Do those reasons apply across the languages?
|
Python doesn't do this because you end up with a problem -- who owns the "com" package that almost everything else is a subpackage of? Python's method of establishing package heirarchy (through the filesystem heirarchy) does not play well with this convention at all. Java can get away with it because package heirarchy is defined by the structure of the string literals fed to the 'package' statement, so there doesn't need to be an explicit "com" package anywhere.
There's also the question of what to do if you want to publicly release a package but don't own a domain name that's suitable for bodging into the package name, or if you end up changing (or losing) your domain name for some reason. (Do later updates need a different package name? How do you know that com.nifty_consultants.nifty_utility is a newer version of com.joe_blow_software.nifty_utility? Or, conversely, how do you know that it's not a newer version? If you miss your domain renewal and the name gets snatched by a domain camper, and someone else buys the name from them, and they want to publicly release software packages, should they then use the same name that you had already used?)
Domain names and software package names, it seems to me, address two entirely different problems, and have entirely different complicating factors. I personally dislike Java's convention because (IMHO) it violates separation of concerns. Avoiding namespace collisions is nice and all, but I hate the thought of my software's namespace being defined by (and dependent on) the marketing department's interaction with some third-party bureaucracy.
To clarify my point further, in response to JeeBee's comment: In Python, a package is a directory containing an __init__.py file (and presumably one or more module files). A package hierarchy requires that each higher-level package be a full, legitimate package. If two packages (especially from different vendors, but even not-directly-related packages from the same vendor) share a top-level package name, whether that name is 'com' or 'web' or 'utils' or whatever, each one must provide an __init__.py for that top-level package. We must also assume that these packages are likely to be installed in the same place in the directory tree, i.e. site-packages/[pkg]/[subpkg]. The filesystem thus enforces that there is only one [pkg]/__init__.py -- so which one wins? There is not (and cannot be) a general-case correct answer to that question. Nor can we reasonably merge the two files together. Since we can't know what another package might need to do in that __init__.py, subpackages sharing a top-level package cannot be assumed to work when both are installed unless they are specifically written to be compatible with each other (at least in this one file). This would be a distribution nightmare and would pretty much invalidate the entire point of nesting packages. This is not specific to reverse-domain-name package hierarchies, though they provide the most obvious bad example and (IMO) are philosophically questionable -- it's really the practical issue of shared top-level packages, rather than the philosophical questions, that are my main concern here.
(On the other hand, a single large package using subpackages to better organize itself is a great idea, since those subpackages are specifically designed to work and live together. This is not so common in Python, though, because a single conceptual package doesn't tend to require a large enough number of files to need the extra layer of organization.)
|
'import module' or 'from module import'
|
I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.
Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any gotchas down the road.
|
The difference between import module and from module import foo is mainly subjective. Pick the one you like best and be consistent in your use of it. Here are some points to help you decide.
import module
Pros:
Less maintenance of your import statements. Don't need to add any additional imports to start using another item from the module
Cons:
Typing module.foo in your code can be tedious and redundant (tedium can be minimized by using import module as mo then typing mo.foo)
from module import foo
Pros:
Less typing to use foo
More control over which items of a module can be accessed
Cons:
To use a new item from the module you have to update your import statement
You lose context about foo. For example, it's less clear what ceil() does compared to math.ceil()
Either method is acceptable, but don't use from module import *.
For any reasonable large set of code, if you import * you will likely be cementing it into the module, unable to be removed. This is because it is difficult to determine what items used in the code are coming from 'module', making it easy to get to the point where you think you don't use the import any more but it's extremely difficult to be sure.
|
Checking a Python module version at runtime
|
Many third-party Python modules have an attribute which holds the version information for the module (usually something like module.VERSION or module.__version__), however some do not.
Particular examples of such modules are libxslt and libxml2.
I need to check that the correct version of these modules are being used at runtime. Is there a way to do this?
A potential solution wold be to read in the source at runtime, hash it, and then compare it to the hash of the known version, but that's nasty.
Is there a better solutions?
|
Use pkg_resources. Anything installed from PyPI at least should have a version number.
>>> import pkg_resources
>>> pkg_resources.get_distribution("blogofile").version
'0.7.1'
|
Python naming conventions for modules
|
I have a module whose purpose is to define a class called "nib". (and a few related classes too.) How should I call the module itself? "nib"? "nibmodule"? Anything else?
|
Just nib. Name the class Nib, with a capital N. For more on naming conventions and other style advice, see PEP 8, the Python style guide.
|
List all Tests Found by Nosetest
|
I use nosetests to run my unittests and it works well. I want to get a list of all the tests nostests finds without actually running them. Is there a way to do that?
|
Version 0.11.1 is currently available. You can get a list of tests without running them as follows:
nosetests -v --collect-only
|
What are the differences between json and simplejson Python modules?
|
I have seen many projects using simplejson module instead of json module from the Standard Library. Also, there are many different simplejson modules. Why would use these alternatives, instead of the one in the Standard Library?
|
json is simplejson, added to the stdlib. But since json was added in 2.6, simplejson has the advantage of working on more Python versions (2.4+).
simplejson is also updated more frequently than Python, so if you need (or want) the latest version, it's best to use simplejson itself, if possible.
A good practice, in my opinion, is to use one or the other as a fallback.
try: import simplejson as json
except ImportError: import json
|
Getting the docstring from a function
|
I have the following function:
def my_func():
"""My docstring is both funny and informative"""
pass
How do I get access to the docstring?
|
Interactively, you can display it with
help(my_func)
Or from code you can retrieve it with
my_func.__doc__
|
Catching an exception while using a Python 'with' statement
|
To my shame, I can't figure out how to handle exception for python 'with' statement. If I have a code:
with open("a.txt") as f:
print f.readlines()
I really want to handle 'file not found exception' in order to do somehing. But I can't write
with open("a.txt") as f:
print f.readlines()
except:
print 'oops'
and can't write
with open("a.txt") as f:
print f.readlines()
else:
print 'oops'
enclosing 'with' in a try/except statement doesn't work else: exception is not raised. What can I do in order to process failure inside 'with' statement in a Pythonic way?
|
from __future__ import with_statement
try:
with open( "a.txt" ) as f :
print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
print 'oops'
If you want different handling for errors from the open call vs the working code you could do:
try:
f = open('foo.txt')
except IOError:
print('error')
else:
with f:
print f.readlines()
|
How can I generate a screenshot of a webpage using a server-side script?
|
I need a server-side script (PHP, Python) to capture a webpage to a PNG, JPG, Tiff, GIF image and resize them to a thumbnail.
What is the best way to accomplish this?
See also:
Web Page Screenshots with PHP?
How can I take a screenshot of a website with PHP and GD?
How might I obtain a Snapshot or Thumbnail of a web page using PHP?
|
You can probably write something similar to webkit2png, unless your server already runs Mac OS X.
UPDATE: I just saw the link to its Linux equivalent: khtml2png
See also:
Create screenshots of a web page using Python and QtWebKit
Taking automated webpage screenshots with embedded Mozilla
|
Importing modules from parent folder
|
I am running Python 2.5.
This is my folder tree:
ptdraft/
nib.py
simulations/
life/
life.py
(I also have __init__.py in each folder, omitted here for readability)
How do I import the nib module from inside the life module? I am hoping it is possible to do without tinkering with sys.path.
Note: The main module being run is in the ptdraft folder.
|
You could use relative imports (python >= 2.5):
from ... import nib
(Whatâs New in Python 2.5) PEP 328: Absolute and Relative Imports
EDIT: added another dot '.' to go up two packages
|
What is a maximum number of arguments in a Python function?
|
It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to *args and **kwargs when they're unrolled in the following manner:
items = [1,2,3,4,5,6]
def do_something(*items):
pass
I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of *args or **kwargs.
|
The limit is due to how the compiled bytecode treats calling a function with position arguments and/or keyword arguments.
The bytecode op of concern is CALL_FUNCTION which carries an op_arg that is 4 bytes in length, but on the two least significant bytes are used. Of those, the most significant byte represent the number of keyword arguments on the stack and the least significant byte the number of positional arguments on the stack. Therefore, you can have at most 0xFF == 255 keyword arguments or 0xFF == 255 positional arguments.
This limit does not apply to *args and **kwargs because calls with that grammar use the bytecode ops CALL_FUNCTION_VAR, CALL_FUNCTION_KW, and CALL_FUNCTION_VAR_KW depending on the signature. For these opcodes, the stack consists of an iterable for the *args and a dict for the **kwargs. These items get passed directly to the receiver which unrolls them as needed.
|
How to include external Python code to use in other files?
|
If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?
So if I have:
[Math.py]
def Calculate ( num )
How do I call it like this:
[Tool.py]
using Math.py
for i in range ( 5 ) :
Calculate ( i )
|
You will need to import the other file as a module like this:
import Math
If you don't want to prefix your Calculate function with the module name then do this:
from Math import Calculate
If you want to import all members of a module then do this:
from Math import *
Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.
|
How do I iterate over all lines of files passed on the command line?
|
I usually do this in Perl:
whatever.pl
while(<>) {
#do whatever;
}
then cat foo.txt | whatever.pl
Now, I want to do this in Python. I tried sys.stdin but I have no idea how to do as I have done in Perl. How can I read the input?
|
Try this:
import fileinput
for line in fileinput.input():
process(line)
|
Converting from a string to boolean in Python?
|
Does anyone know how to do convert from a string to a boolean in Python? I found this link. But it doesn't look like a proper way to do it. I.e. using a built in functionality, etc.
EDIT: The reason I asked this is because I learned int("string"), from here. I tried bool ("string") but always got True.
|
Really, you just compare the string to whatever you expect to accept as representing true, so you can do this:
s == 'True'
Or to checks against a whole bunch of values:
s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']
Be cautious when using the following:
>>> bool("foo")
True
>>> bool("")
False
Empty strings evaluate to False, but everything else evaluates to True. So this should not be used for any kind of parsing purposes.
|
Best way to encode tuples with json
|
In python I have a dictionary that maps tuples to a list of tuples. e.g.
{(1,2): [(2,3),(1,7)]}
I want to be able to encode this data use it with javascript, so I looked into json but it appears keys must be strings so my tuple does not work as a key.
Is the best way to handle this is encode it as "1,2" and then parse it into something I want on the javascript? Or is there a more clever way to handle this.
|
You might consider saying
{"[1,2]": [(2,3),(1,7)]}
and then when you need to get the value out, you can just parse the keys themselves as JSON objects, which all modern browsers can do with the built-in JSON.parse method (I'm using jQuery.each to iterate here but you could use anything):
var myjson = JSON.parse('{"[1,2]": [[2,3],[1,7]]}');
$.each(myjson, function(keystr,val){
var key = JSON.parse(keystr);
// do something with key and val
});
On the other hand, you might want to just structure your object differently, e.g.
{1: {2: [(2,3),(1,7)]}}
so that instead of saying
myjson[1,2] // doesn't work
which is invalid Javascript syntax, you could say
myjson[1][2] // returns [[2,3],[1,7]]
|
Why can't environmental variables set in python persist?
|
I was hoping to write a python script to create some appropriate environmental variables by running the script in whatever directory I'll be executing some simulation code, and I've read that I can't write a script to make these env vars persist in the mac os terminal. So two things:
Is this true?
and
It seems like it would be a useful things to do; why isn't it possible in general?
|
You can't do it from python, but some clever bash tricks can do something similar. The basic reasoning is this: environment variables exist in a per-process memory space. When a new process is created with fork() it inherits its parent's environment variables. When you set an environment variable in your shell (e.g. bash) like this:
export VAR="foo"
What you're doing is telling bash to set the variable VAR in its process space to "foo". When you run a program, bash uses fork() and then exec() to run the program, so anything you run from bash inherits the bash environment variables.
Now, suppose you want to create a bash command that sets some environment variable DATA with content from a file in your current directory called ".data". First, you need to have a command to get the data out of the file:
cat .data
That prints the data. Now, we want to create a bash command to set that data in an environment variable:
export DATA=`cat .data`
That command takes the contents of .data and puts it in the environment variable DATA. Now, if you put that inside an alias command, you have a bash command that sets your environment variable:
alias set-data="export DATA=`cat .data`"
You can put that alias command inside the .bashrc or .bash_profile files in your home directory to have that command available in any new bash shell you start.
|
Queue.Queue vs. collections.deque
|
I need a queue which multiple threads can put stuff into, and multiple threads may read from.
Python has at least two queue classes, Queue.Queue and collections.deque, with the former seemingly using the latter internally. Both claim to be thread-safe in the documentation.
However, the Queue docs also state:
collections.deque is an alternative
implementation of unbounded queues
with fast atomic append() and
popleft() operations that do not
require locking.
Which I guess I don't quite unterstand: Does this mean deque isn't fully thread-safe after all?
If it is, I may not fully understand the difference between the two classes. I can see that Queue adds blocking functionality. On the other hand, it loses some deque features like support for the in-operator.
Accessing the internal deque object directly, is
x in Queue().deque
thread-safe?
Also, why does Queue employ a mutex for it's operations when deque is thread-safe already?
|
Queue.Queue and collections.deque serve different purposes. Queue.Queue is intended for allowing different threads to communicate using queued messages/data, whereas collections.deque is simply intended as a datastructure. That's why Queue.Queue has methods like put_nowait(), get_nowait(), and join(), whereas collections.deque doesn't. Queue.Queue isn't intended to be used as a collection, which is why it lacks the likes of the in operator.
It boils down to this: if you have multiple threads and you want them to be able to communicate without the need for locks, you're looking for Queue.Queue; if you just want a queue or a double-ended queue as a datastructure, use collections.deque.
Finally, accessing and manipulating the internal deque of a Queue.Queue is playing with fire - you really don't want to be doing that.
|
If monkey patching is permitted in both Ruby and Python, why is it more controversial in Ruby?
|
In many discussions I have heard about Ruby in which people have expressed their reservations about the language, the issue of monkey patching comes up as one of their primary concerns.
However, I rarely hear the same arguments made in the context of Python although it is also permitted in the Python language.
Why this distinction?
Does Python include different types of safeguards to minimize the risks of this feature?
|
It's a technique less practised in Python, in part because "core" classes in Python (those implemented in C) are not really modifiable. In Ruby, on the other hand, because of the way it's implemented internally (not better, just different) just about anything can be modified dynamically.
Philosophically, it's something that tends to be frowned on within the Python community, distinctly less so in the Ruby world. I don't know why you assert that it's more controversial (can you link to an authoritative reference?) - my experience has been that monkey-patching is an accepted technique if one where the user should be aware of possible consequences.
|
How to install SimpleJson Package for Python
|
http://pypi.python.org/pypi/simplejson
I am just diving into the Python world and want to make a simple twitter application which requires the installation of simplejson but not sure how I can set it up and get it working..
I am on a Windows System
|
I would recommend EasyInstall, a package management application for Python.
Once you've installed EasyInstall, you should be able to go to a command window and type:
easy_install simplejson
This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like C:\Python25\Scripts).
|
Django Template - New Variable Declaration
|
Let me preface by I am just starting Python so if this is really a simple question ^_^
I have a html file with the following content:
{%for d in results%}
<div class="twt">
<img src="{{ d.profile_image_url }}" width="48px" height="48px" /> <span> {{ d.text }} </span>
<span class="date">{{ d.created_at }}</span>
</div>
{% endfor %}
which works well but I also would like to declare a variable on this page. Let's say for this example, we can it RowNumber which will increment for each d displayed, spitting out the current RowNumber.
I tried doing:
{{ RowNumber = 0}}
{{ RowNumber ++ }}
But it doesn't seem to allow me to declare RowNumber.
|
Check out the documentation on the for loop.
It automatically creates a variable called forloop.counter that holds the current iteration index.
As far as the greater question on how to declare variables, there is no out-of-the-box way of doing this with Django, and it is not considered a missing feature but a feature. If you really wanted to do this it is possible with custom tags but for the most part the philosophy you want to follow is that mostly anything you want to do that would require this should be done in the view and the template should be reserved for very simple logic. For your example of summing up a total, for example, you could use the add filter. Likewise, you can create your own filters just like with tags.
|
How can you make a vote-up-down button like in Stackoverflow?
|
Problems
how to make an Ajax buttons (upward and downward arrows) such that the number can increase or decrease
how to save the action af an user to an variable NumberOfVotesOfQuestionID
I am not sure whether I should use database or not for the variable. However, I know that there is an easier way too to save the number of votes.
How can you solve those problems?
[edit]
The server-side programming language is Python.
|
This is a dirty/untested theoretical implementation using jQuery/Django.
We're going to assume the voting up and down is for questions/answers like on this site, but that can obviously be adjusted to your real life use case.
The template
<div id="answer_595" class="answer">
<img src="vote_up.png" class="vote up">
<div class="score">0</div>
<img src="vote_down.png" class="vote down">
Blah blah blah this is my answer.
</div>
<div id="answer_596" class="answer">
<img src="vote_up.png" class="vote up">
<div class="score">0</div>
<img src="vote_down.png" class="vote down">
Blah blah blah this is my other answer.
</div>
Javascript
$(function() {
$('div.answer img.vote').click(function() {
var id = $(this).parents('div.answer').attr('id').split('_')[1];
var vote_type = $(this).hasClass('up') ? 'up' : 'down';
if($(this).hasClass('selected')) {
$.post('/vote/', {id: id, type: vote_type}, function(json) {
if(json.success == 'success') {
$('#answer_' + id)
.find('img.' + vote_type);
.attr('src', 'vote_' + vote_type + '_selected.png')
.addClass('selected');
$('div.score', '#answer_' + id).html(json.score);
}
});
} else {
$.post('/remove_vote/', {id: id, type: vote_type}, function(json) {
if(json.success == 'success') {
$('#answer_' + id)
.find('img.' + vote_type);
.attr('src', 'vote_' + vote_type + '.png')
.removeClass('selected');
$('div.score', '#answer_' + id).html(json.score);
}
});
}
});
});
Django views
def vote(request):
if request.method == 'POST':
try:
answer = Answer.objects.get(pk=request.POST['id'])
except Answer.DoesNotExist:
return HttpResponse("{'success': 'false'}")
try:
vote = Vote.objects.get(answer=answer, user=request.user)
except Vote.DoesNotExist:
pass
else:
return HttpResponse("{'success': 'false'}")
if request.POST['type'] == 'up':
answer.score = answer.score + 1
else:
answer.score = answer.score - 1
answer.save()
Vote.objects.create(answer=answer,
user=request.user,
type=request.POST['type'])
return HttpResponse("{'success':'true', 'score':" + answer.score + "}")
else:
raise Http404('What are you doing here?')
def remove_vote(request):
if request.method == 'POST':
try:
answer = Answer.objects.get(pk=request.POST['id'])
except Answer.DoesNotExist:
return HttpResponse("{'success': 'false'}")
try:
vote = Vote.objects.get(answer=answer, user=request.user)
except Vote.DoesNotExist:
return HttpResponse("{'success': 'false'}")
else:
vote.delete()
if request.POST['type'] == 'up':
answer.score = answer.score - 1
else:
answer.score = answer.score + 1
answer.save()
return HttpResponse("{'success':'true', 'score':" + answer.score + "}")
else:
raise Http404('What are you doing here?')
Yikes. When I started answering this question I didn't mean to write this much but I got carried away a little bit. You're still missing an initial request to get all the votes when the page is first loaded and such, but I'll leave that as an exercise to the reader. Anyhow, if you are in fact using Django and are interested in a more tested/real implemention of the Stackoverflow voting, I suggest you check out the source code for cnprog.com, a Chinese clone of Stackoverflow written in Python/Django. They released their code and it is pretty decent.
|
What is the purpose of python's inner classes?
|
Python's inner/nested classes confuse me. Is there something that can't be accomplished without them? If so, what is that thing?
|
Quoted from http://www.geekinterview.com/question_details/64739:
Advantages of inner class:
Logical grouping of classes: If a class is useful to only one other class then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
Increased encapsulation: Consider two top-level classes A and B where B needs access to members of A that would otherwise be declared private. By hiding class B within class A A's members can be declared private and B can access them. In addition B itself can be hidden from the outside world.
More readable, maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.
The main advantage is organization. Anything that can be accomplished with inner classes can be accomplished without them.
|
Find Hyperlinks in Text using Python (twitter related)
|
How can I parse text and find all instances of hyperlinks with a string? The hyperlink will not be in the html format of <a href="http://test.com">test</a> but just http://test.com
Secondly, I would like to then convert the original string and replace all instances of hyperlinks into clickable html hyperlinks.
I found an example in this thread:
Easiest way to convert a URL to a hyperlink in a C# string?
but was unable to reproduce it in python :(
|
Here's a Python port of http://stackoverflow.com/questions/32637/easiest-way-to-convert-a-url-to-a-hyperlink-in-a-c-string/32648#32648:
import re
myString = "This is my tweet check it out http://tinyurl.com/blah"
r = re.compile(r"(http://[^ ]+)")
print r.sub(r'<a href="\1">\1</a>', myString)
Output:
This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/blah</a>
|
HTTP Authentication in Python
|
Whats is the python urllib equivallent of
curl -u username:password status="abcd" http://example.com/update.json
I did this:
handle = urllib2.Request(url)
authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password))
handle.add_header("Authorization", authheader)
Is there a better / simpler way?
|
The trick is to create a password manager, and then tell urllib about it. Usually, you won't care about the realm of the authentication, just the host/url part. For example, the following:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/"
password_mgr.add_password(None, top_level_url, 'user', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(urllib2.HTTPHandler, handler)
request = urllib2.Request(url)
Will set the user name and password to every URL starting with top_level_url. Other options are to specify a host name or more complete URL here.
A good document describing this and more is at http://www.voidspace.org.uk/python/articles/urllib2.shtml#id6.
|
Django templates stripping spaces?
|
I'm having trouble with Django templates and CharField models.
So I have a model with a CharField that creates a slug that replaces spaces with underscores. If I create an object, Somename Somesurname, this creates slug Somename_Somesurname and gets displayed as expected on the template.
However, if I create an object, Somename Somesurname (notice the second space), slug Somename__Somesurname is created, and although on the Django console I see this as <Object: Somename Somesurname>, on the template it is displayed as Somename Somesurname.
So do Django templates somehow strip spaces? Is there a filter I can use to get the name with its spaces?
|
Let me preface this by saying @DNS's answer is correct as to why the spaces are not showing.
With that in mind, this template filter will replace any spaces in the string with
Usage:
{{ "hey there world"|spacify }}
Output would be hey there world
Here is the code:
from django.template import Library
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import re
register = Library()
@stringfilter
def spacify(value, autoescape=None):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
return mark_safe(re.sub('\s', '&'+'nbsp;', esc(value)))
spacify.needs_autoescape = True
register.filter(spacify)
For notes on how template filters work and how to install them, check out the docs.
|
Django GROUP BY strftime date format
|
I would like to do a SUM on rows in a database and group by date.
I am trying to run this SQL query using Django aggregates and annotations:
select strftime('%m/%d/%Y', time_stamp) as the_date, sum(numbers_data)
from my_model
group by the_date;
I tried the following:
data = My_Model.objects.values("strftime('%m/%d/%Y',
time_stamp)").annotate(Sum("numbers_data")).order_by()
but it seems like you can only use column names in the values() function; it doesn't like the use of strftime().
How should I go about this?
|
This works for me:
select_data = {"d": """strftime('%%m/%%d/%%Y', time_stamp)"""}
data = My_Model.objects.extra(select=select_data).values('d').annotate(Sum("numbers_data")).order_by()
Took a bit to figure out I had to escape the % signs.
|
Python distutils, how to get a compiler that is going to be used?
|
For example, I may use python setup.py build --compiler=msvc or python setup.py build --compiler=mingw32 or just python setup.py build, in which case the default compiler (say, bcpp) will be used. How can I get the compiler name inside my setup.py (e. g. msvc, mingw32 and bcpp, respectively)?
UPD.: I don't need the default compiler, I need the one that is actually going to be used, which is not necessarily the default one. So far I haven't found a better way than to parse sys.argv to see if there's a --compiler... string there.
|
This is an expanded version of Luper Rouch's answer that worked for me to get an openmp extension to compile using both mingw and msvc on windows. After subclassing build_ext you need to pass it to setup.py in the cmdclass arg. By subclassing build_extensions instead of finalize_options you'll have the actual compiler object to look into, so you can then get more detailed version information. You could eventually set compiler flags on a per-compiler, per-extension basis:
from distutils.core import setup, Extension
from distutils.command.build_ext import build_ext
copt = {'msvc': ['/openmp', '/Ox', '/fp:fast','/favor:INTEL64','/Og'] ,
'mingw32' : ['-fopenmp','-O3','-ffast-math','-march=native'] }
lopt = {'mingw32' : ['-fopenmp'] }
class build_ext_subclass( build_ext ):
def build_extensions(self):
c = self.compiler.compiler_type
if copt.has_key(c):
for e in self.extensions:
e.extra_compile_args = copt[ c ]
if lopt.has_key(c):
for e in self.extensions:
e.extra_link_args = lopt[ c ]
build_ext.build_extensions(self)
mod = Extension('_wripaca',
sources=['../wripaca_wrap.c',
'../../src/wripaca.c'],
include_dirs=['../../include']
)
setup (name = 'wripaca',
ext_modules = [mod],
py_modules = ["wripaca"],
cmdclass = {'build_ext': build_ext_subclass } )
|
In Python, what is the difference between ".append()" and "+= []"?
|
What is the difference between:
some_list1 = []
some_list1.append("something")
and
some_list2 = []
some_list2 += ["something"]
|
For your case the only difference is performance: append is twice as fast.
Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.20177424499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.41192320500000079
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.23079359499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.44208112500000141
In general case append will add one item to the list, while += will copy all elements of right-hand-side list into the left-hand-side list.
Update: perf analysis
Comparing bytecodes we can assume that append version wastes cycles in LOAD_ATTR + CALL_FUNCTION, and += version -- in BUILD_LIST. Apparently BUILD_LIST outweighs LOAD_ATTR + CALL_FUNCTION.
>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_ATTR 1 (append)
12 LOAD_CONST 0 ('spam')
15 CALL_FUNCTION 1
18 POP_TOP
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_CONST 0 ('spam')
12 BUILD_LIST 1
15 INPLACE_ADD
16 STORE_NAME 0 (s)
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
We can improve performance even more by removing LOAD_ATTR overhead:
>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566
|
Installing ipython with readline on the mac
|
I am using ipython on Mac OS 10.5 with python 2.5.1 (I would actually like to use ipython for 2.6.1, but it doesn't seem to be available?)
I installed ipython via easy_install. It works but is missing gnu readline (needed for nice searching of command line history with ctrl-R, etc.)
I found a blog post and other sources saying this could be fixed by
sudo easy_install -f http://ipython.scipy.org/dist/ readline
However, this leads to build errors in readline.c , particularly undeclared functions like rl_compentry_func_t and rl_catch_signals.
Has anyone seen these errors? Is there another way to get ipython installed with readline?
|
To install ipython on Snow Leopard or Lion without using MacPorts, you can simply do:
sudo easy_install readline ipython
(Note that if you use the "pip" to install readline, then ipython won't see the readline library, not sure why).
Edit:
If you had ipython installed remove it with
sudo pip uninstall ipython
or
pip uninstall ipython #for virtualenvs
Then make sure you have installed readline first and reinstall iptyhon
pip install readline ipython
For some reasons, if readline wasn't present during the installation, it will install itself without support for readline or it use the default mac readline.
|
How do I write to the console in Google App Engine?
|
Often when I am coding I just like to print little things (mostly the current value of variables) out to console. I don't see anything like this for Google App Engine, although I note that the Google App Engine Launcher does have a Log terminal. Is there any way to write to said Terminal, or to some other terminal, using Google App Engine?
|
You'll want to use the Python's standard logging module.
import logging
logging.info("hello")
logging.debug("hi") # this won't show up by default
To see calls to logging.debug() in the GoogleAppEngineLauncher Logs console, you have to first add the flag --dev_appserver_log_level=debug to your app. However, beware that you're going to see a lot of debug noise from the App Engine SDK itself. The full set of levels are:
debug
info
warning
error
critical
You can add the flag by double clicking the app and then dropping it into the Extra Flags field.
|
How can I convert Unicode to uppercase to print it?
|
I have this:
>>> print 'example'
example
>>> print 'exámple'
exámple
>>> print 'exámple'.upper()
EXáMPLE
What I need to do to print:
EXÃMPLE
(Where the 'a' gets its accute accent, but in uppercase.)
I'm using Python 2.6.
|
I think it's as simple as not converting to ASCII first.
>>> print u'exámple'.upper()
EXÃMPLE
|
Python __str__ and lists
|
In Java, if I call List.toString(), it will automatically call the toString() method on each object inside the List. For example, if my list contains objects o1, o2, and o3, list.toString() would look something like this:
"[" + o1.toString() + ", " + o2.toString() + ", " + o3.toString() + "]"
Is there a way to get similar behavior in Python? I implemented a __str__() method in my class, but when I print out a list of objects, using:
print 'my list is %s'%(list)
it looks something like this:
[<__main__.cell instance at 0x2a955e95f0>, <__main__.cell instance at 0x2a955e9638>, <__main__.cell instance at 0x2a955e9680>]
how can I get python to call my __str__ automatically for each element inside the list (or dict for that matter)?
|
Calling string on a python list calls the __repr__ method on each element inside. For some items, __str__ and __repr__ are the same. If you want that behavior, do:
def __str__(self):
...
def __repr__(self):
return self.__str__()
|
Display some free text in between Django Form fields
|
I have a form like the following:
class MyForm(Form):
#personal data
firstname = CharField()
lastname = CharField()
#education data
university = CharField()
major = CharField()
#foobar data
foobar = ChoiceField()
Since some fields (like foobar) are populated from the database i can't use another method other than letting Django render it for me with form.as_ul
Also i wish i don't have to split the form in multiple forms for ease of mantainance
Is there a way to tell Django to display a help text in between these form sections so that i can put in some instructions on how to fill the form?
I'd like the form to render something like this:
<form>
<p>Here you enter your personal data...</p>
<input name='firstname'>
<input name='lastname'>
<p>Here you enter your education data...</p>
<input name='university'>
<input name='major'>
</form>
Would i need to create my own widget to be able to display those <P> tags, or is there an easier way?
Thanks
|
One way to do this without displaying your form in the template using form.as_ul, is with django-uni-form. First you'll have to download it here and install it. Then the code for setting up your form could looks something like this:
from uni_form.helpers import FormHelper, Submit, Layout, Fieldset
class MyForm(Form):
#personal data
firstname = CharField()
lastname = CharField()
#education data
university = CharField()
major = CharField()
#foobar data
foobar = ChoiceField()
# now attach a uni_form helper to display the form
helper = FormHelper()
# create the layout
layout = Layout(
# first fieldset
Fieldset("Here you enter your personal data...",
'firstname', 'lastname'),
Fieldset("Here you enter your education data...",
'university', 'major'),
Fieldset('foobar')
# and add a submit button
sumbit = Submit('add', 'Submit information')
helper.add_input(submit)
Now, to display this in your template you would do this:
{% load uni_form %}
{% with form.helper as helper %}
{% uni_form form helper %}
{% endwith %}
This would output HTML (roughly) like this:
<form>
<fieldset><legend>Here you enter your personal data...</legend>
<input name='firstname'>
<input name='lastname'>
</fieldset>
<fieldset><legend>Here you enter your education data...</legend>
<input name='university'>
<input name='major'>
</fieldset>
<fieldset>
<input name='foobar'>
</fieldset>
</form>
For more info on uni_form, read their docs (see the link above).
PS: I realize this reply is late, and I'm sure you already solved this problem, but I think this should be helpful for anyone just coming across this now.
|
Securely Erasing Password in Memory (Python)
|
How do you store a password entered by the user in memory and erase it securely after it is no longer need?
To elaborate, currently we have the following code:
username = raw_input('User name: ')
password = getpass.getpass()
mail = imaplib.IMAP4(MAIL_HOST)
mail.login(username, password)
After calling the login method, what do we need to do to fill the area of memory that contains password with garbled characters so that someone cannot recover the password by doing a core dump?
There is a similar question, however it is in Java and the solution uses character arrays:
http://stackoverflow.com/questions/646224/how-does-one-store-password-hashes-securely-in-memory-when-creating-accounts
Can this be done in Python?
|
Python doesn't have that low of a level of control over memory. Accept it, and move on. The best you can do is to del password after calling mail.login so that no references to the password string object remain. Any solution that purports to be able to do more than that is only giving you a false sense of security.
Python string objects are immutable; there's no direct way to change the contents of a string after it is created. Even if you were able to somehow overwrite the contents of the string referred to by password (which is technically possible with stupid ctypes tricks), there would still be other copies of the password that have been created in various string operations:
by the getpass module when it strips the trailing newline off of the inputted password
by the imaplib module when it quotes the password and then creates the complete IMAP command before passing it off to the socket
You would somehow have to get references to all of those strings and overwrite their memory as well.
|
Is there a way to overload += in python?
|
I know about the __add__ method to override plus, but when I use that to override +=, I end up with one of two problems:
(1) if __add__ mutates self, then
z = x + y
will mutate x when I don't really want x to be mutated there.
(2) if __add__ returns a new object, then
tmp = z
z += x
z += y
tmp += w
return z
will return something without w since z and tmp point to different objects after z += x is executed.
I can make some sort of .append() method, but I'd prefer to overload += if it is possible.
|
Yes. Just override the object's __iadd__ method, which takes the same parameters as add. You can find more information here.
|
Correct way to define Python source code encoding
|
PEP 263 defines how to define Python source code encoding.
Normally, the first 2 lines of a Python file should start with:
#!/usr/bin/python
# -*- coding: <encoding name> -*-
But I have seen a lot of files starting with:
#!/usr/bin/python
# -*- encoding: <encoding name> -*-
-> encoding instead of coding.
So what is the correct way of declaring the file encoding ?
Is encoding permitted because the regex used is lazy ? Or is it just another form of declaring the file encoding ?
I'm asking this question because the PEP does not talk about encoding, it just talks about coding.
|
Check the docs here:
"If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+), this comment is processed as an encoding declaration"
"The recommended forms of this expression are
# -*- coding: <encoding-name> -*-
which is recognized also by GNU Emacs, and
# vim:fileencoding=<encoding-name>
which is recognized by Bram Moolenaarâs VIM."
So, you can put pretty much anything before the "coding" part, but stick to "coding" (with no prefix) if you want to be 100% python-docs-recommendation-compatible.
More specifically, you need to use whatever is recognized by Python and the specific editing software you use (if it needs/accepts anything at all). E.g. the coding form is recognized (out of the box) by GNU Emacs but not Vim (yes, without a universal agreement, it's essentially a turf war).
|
Getting file path of imported module
|
How can I get the file path of a module imported in python. I am using Linux (if it matters).
Eg: if I am in my home dir and import a module, it should return back the full path of my home directory.
|
Modules and packages have a __file__ attribute that has its path information. If the module was imported relative to current working directory, you'll probably want to get its absolute path.
import os.path
import my_module
print os.path.abspath(my_module.__file__)
|
How to I get scons to invoke an external script?
|
I'm trying to use scons to build a latex document. In particular, I want to get scons to invoke a python program that generates a file containing a table that is \input{} into the main document. I've looked over the scons documentation but it is not immediately clear to me what I need to do.
What I wish to achieve is essentially what you would get with this makefile:
document.pdf: table.tex
pdflatex document.tex
table.tex:
python table_generator.py
How can I express this in scons?
|
Something along these lines should do -
env.Command ('document.tex', '', 'python table_generator.py')
env.PDF ('document.pdf', 'document.tex')
It declares that 'document.tex' is generated by calling the Python script, and requests a PDF document to be created from this generatd 'document.tex' file.
Note that this is in spirit only. It may require some tweaking. In particular, I'm not certain what kind of semantics you would want for the generation of 'document.tex' - should it be generated every time? Only when it doesn't exist? When some other file changes? (you would want to add this dependency as the second argument to Command() that case).
In addition, the output of Command() can be used as input to PDF() if desired. For clarity, I didn't do that.
|
Django Model set foreign key to a field of another Model
|
Is there any way to set a foreign key in django to a field of another model?
For example, imagine I have a ValidationRule object. And I want the rule to define what field in another model is to be validated (as well as some other information, such as whether it can be null, a data-type, range, etc.)
Is there a way to store this field-level mapping in django?
|
I haven't tried this, but it seems that since Django 1.0 you can do something like:
class Foo(models.Model):
foo = models.ForeignKey(Bar, to_field='bar')
Documentation for this is here.
|
Replace html entities with the corresponding utf-8 characters in Python 2.6
|
I have a html text like this:
<xml ... >
and I want to convert it to something readable:
<xml ...>
Any easy (and fast) way to do it in Python?
|
http://docs.python.org/library/htmlparser.html
>>> import HTMLParser
>>> pars = HTMLParser.HTMLParser()
>>> pars.unescape('© €')
u'\xa9 \u20ac'
>>> print _
© â¬
|
django to send AND receive email?
|
I have gotten quite familiar with django's email sending abilities, but I havn't seen anything about it receiving and processing emails from users. Is this functionality available?
A few google searches have not turned up very promising results. Though I did find this: http://stackoverflow.com/questions/348392/receive-and-send-emails-in-python
Am I going to have to roll my own? if so, I'll be posting that app faster than you can say... whatever you say.
thanks,
Jim
update: I'm not trying to make an email server, I just need to add some functionality where you can email an image to the site and have it pop up in your account.
|
There's an app called jutda-helpdesk that uses Python's poplib and imaplib to process incoming emails. You just have to have an account somewhere with POP3 or IMAP access.
This is adapted from their get_email.py:
def process_mail(mb):
print "Processing: %s" % q
if mb.email_box_type == 'pop3':
if mb.email_box_ssl:
if not mb.email_box_port: mb.email_box_port = 995
server = poplib.POP3_SSL(mb.email_box_host, int(mb.email_box_port))
else:
if not mb.email_box_port: mb.email_box_port = 110
server = poplib.POP3(mb.email_box_host, int(mb.email_box_port))
server.getwelcome()
server.user(mb.email_box_user)
server.pass_(mb.email_box_pass)
messagesInfo = server.list()[1]
for msg in messagesInfo:
msgNum = msg.split(" ")[0]
msgSize = msg.split(" ")[1]
full_message = "\n".join(server.retr(msgNum)[1])
# Do something with the message
server.dele(msgNum)
server.quit()
elif mb.email_box_type == 'imap':
if mb.email_box_ssl:
if not mb.email_box_port: mb.email_box_port = 993
server = imaplib.IMAP4_SSL(mb.email_box_host, int(mb.email_box_port))
else:
if not mb.email_box_port: mb.email_box_port = 143
server = imaplib.IMAP4(mb.email_box_host, int(mb.email_box_port))
server.login(mb.email_box_user, mb.email_box_pass)
server.select(mb.email_box_imap_folder)
status, data = server.search(None, 'ALL')
for num in data[0].split():
status, data = server.fetch(num, '(RFC822)')
full_message = data[0][1]
# Do something with the message
server.store(num, '+FLAGS', '\\Deleted')
server.expunge()
server.close()
server.logout()
mb is just some object to store all the mail server info, the rest should be pretty clear.
You'll probably need to check the docs on poplib and imaplib to get specific parts of the message, but hopefully this is enough to get you going.
|
Python/wxPython: Doing work continuously in the background
|
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.
When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.
How should I run the rendering function?
|
I would use a threading.Thread to run the code in the background and wx.CallAfter to post updates to my window thread to render them to the user.
thread = threading.Thread(target=self.do_work)
thread.setDaemon(True)
thread.start()
...
def do_work(self):
# processing code here
while processing:
# do stuff
wx.CallAfter(self.update_view, args, kwargs)
def update_view(self, args):
# do stuff with args
# since wx.CallAfter was used, it's safe to do GUI stuff here
|
Try/Except in Python: How do you properly ignore Exceptions?
|
When you just want to do a try-except without handling the exception, how do you do it in Python?
Is the following the right way to do it?
try :
shutil.rmtree ( path )
except :
pass
|
try:
doSomething()
except:
pass
or
try:
doSomething()
except Exception:
pass
The difference is, that the first one will also catch KeyboardInterrupt, SystemExit and stuff like that, which are derived directly from exceptions.BaseException, not exceptions.Exception. See documentation for details:
try statement — http://docs.python.org/reference/compound_stmts.html#try
exceptions — http://docs.python.org/library/exceptions
|
Multiprocessing or Multithreading?
|
I'm making a program for running simulations in Python, with a wxPython interface. In the program, you can create a simulation, and the program renders (=calculates) it for you. Rendering can be very time-consuming sometimes.
When the user starts a simulation, and defines an initial state, I want the program to render the simulation continuously in the background, while the user may be doing different things in the program. Sort of like a YouTube-style bar that fills up: You can play the simulation only up to the point that was rendered.
Should I use multiple processes or multiple threads or what? People told me to use the multiprocessing package, I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information (and I think my program will need to share a lot of information.) Additionally I also heard about Stackless Python: Is it a separate option? I have no idea.
Please advise.
|
"I checked it out and it looks good, but I also heard that processes, unlike threads, can't share a lot of information..."
This is only partially true.
Threads are part of a process -- threads share memory trivially. Which is as much of a problem as a help -- two threads with casual disregard for each other can overwrite memory and create serious problems.
Processes, however, share information through a lot of mechanisms. A Posix pipeline (a | b) means that process a and process b share information -- a writes it and b reads it. This works out really well for a lot things.
The operating system will assign your processes to every available core as quickly as you create them. This works out really well for a lot of things.
Stackless Python is unrelated to this discussion -- it's faster and has different thread scheduling. But I don't think threads are the best route for this.
"I think my program will need to share a lot of information."
You should resolve this first. Then, determine how to structure processes around the flow of information. A "pipeline" is very easy and natural to do; any shell will create the pipeline trivially.
A "server" is another architecture where multiple client processes get and/or put information into a central server. This is a great way to share information. You can use the WSGI reference implementation as a way to build a simple, reliable server.
|
Get Primary Key after Saving a ModelForm in Django
|
How do I get the primary key after saving a ModelForm? After the form has been validated and saved, I would like to redirect the user to the contact_details view which requires the primary key of the contact.
def contact_create(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse(contact_details, args=(form.pk,)))
else:
form = ContactForm()
|
The ModelForm's save method returns the saved object.
Try this:
def contact_create(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
new_contact = form.save()
return HttpResponseRedirect(reverse(contact_details, args=(new_contact.pk,)))
else:
form = ContactForm()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.