instruction
stringlengths 12
148
| input
stringlengths 16
30.2k
| output
stringlengths 11
27.3k
|
---|---|---|
How do I send a custom header with urllib2 in a HTTP Request?
|
I want to send a custom "Accept" header in my request when using urllib2.urlopen(..). How do I do that?
|
Not quite. Creating a Request object does not actually send the request, and Request objects have no Read() method. (Also: read() is lowercase.) All you need to do is pass the Request as the first argument to urlopen() and that will give you your response.
import urllib2
request = urllib2.Request("http://www.google.com", headers={"Accept" : "text/html"})
contents = urllib2.urlopen(request).read()
|
dropping trailing '.0' from floats
|
I'm looking for a way to convert numbers to string format, dropping any redundant '.0'
The input data is a mix of floats and strings. Desired output:
0 --> '0'
0.0 --> '0'
0.1 --> '0.1'
1.0 --> '1'
I've come up with the following generator expression, but I wonder if there's a faster way:
(str(i).rstrip('.0') if i else '0' for i in lst)
The truth check is there to prevent 0 from becoming an empty string.
EDIT: The more or less acceptable solution I have for now is this:
('%d'%i if i == int(i) else '%s'%i for i in lst)
It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.
|
See PEP 3101:
'g' - General format. This prints the number as a fixed-point
number, unless the number is too large, in which case
it switches to 'e' exponent notation.
Old style:
>>> "%g" % float(10)
'10'
New style (recommended):
>>> '{0:g}'.format(float(21))
'21'
|
Extract float/double value
|
How do I extract a double value from a string using regex.
import re
pattr = re.compile(???)
x = pattr.match("4.5")
|
A regexp from the perldoc perlretut:
import re
re_float = re.compile("""(?x)
^
[+-]?\ * # first, match an optional sign *and space*
( # then match integers or f.p. mantissas:
\d+ # start out with a ...
(
\.\d* # mantissa of the form a.b or a.
)? # ? takes care of integers of the form a
|\.\d+ # mantissa of the form .b
)
([eE][+-]?\d+)? # finally, optionally match an exponent
$""")
m = re_float.match("4.5")
print m.group(0)
# -> 4.5
To extract numbers from a bigger string:
s = """4.5 abc -4.5 abc - 4.5 abc + .1e10 abc . abc 1.01e-2 abc
1.01e-.2 abc 123 abc .123"""
print re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", s)
# -> ['4.5', '-4.5', '- 4.5', '+ .1e10', ' 1.01e-2',
# ' 1.01', '-.2', ' 123', ' .123']
|
Typecasting in Python
|
I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.
How can I do this?
|
You can convert a string to a 32-bit signed integer with the int function:
str = "1234"
i = int(str) // i is a 32-bit integer
If the string does not represent an integer, you'll get a ValueError exception. Note, however, that if the string does represent an integer, but that integer does not fit into a 32-bit signed int, then you'll actually get an object of type long instead.
You can then convert it to other widths and signednesses with some simple math:
s8 = (i + 2**7) % 2**8 - 2**7 // convert to signed 8-bit
u8 = i % 2**8 // convert to unsigned 8-bit
s16 = (i + 2**15) % 2**16 - 2**15 // convert to signed 16-bit
u16 = i % 2**16 // convert to unsigned 16-bit
s32 = (i + 2**31) % 2**32 - 2**31 // convert to signed 32-bit
u32 = i % 2**32 // convert to unsigned 32-bit
s64 = (i + 2**63) % 2**64 - 2**63 // convert to signed 64-bit
u64 = i % 2**64 // convert to unsigned 64-bit
You can convert strings to floating point with the float function:
f = float("3.14159")
Python floats are what other languages refer to as double, i.e. they are 64-bits. There are no 32-bit floats in Python.
|
Python Performance - have you ever had to rewrite in something else?
|
Has anyone ever had code in Python, that turned out not to perform fast enough?
I mean, you were forced to choose another language because of it?
We are investigating using Python for a couple of larger projects, and my feeling is that in most cases, Python is plenty fast enough for most scenarios (compared to say, Java) because it relies on optimized C routines.
I wanted to see if people had instances where they started out in Python, but ended up having to go with something else because of performance.
Thanks.
|
Yes, I have. I wrote a row-count program for a binary (length-prefixed rather than delimited) bcp output file once and ended up having to redo it in C because the python one was too slow. This program was quite small (it only took a couple of days to re-write it in C), so I didn't bother to try and build a hybrid application (python glue with central routines written in C) but this would also have been a viable route.
A larger application with performance critical bits can be written in a combination of C and a higher level language. You can write the performance-critical parts in C with an interface to Python for the rest of the system. SWIG, Pyrex or Boost.Python (if you're using C++) all provide good mechanisms to do the plumbing for your Python interface. The C API for python is more complex than that for Tcl or Lua, but isn't infeasible to build by hand. For an example of a hand-built Python/C API, check out cx_Oracle.
This approach has been used on quite a number of successful applications going back as far as the 1970s (that I am aware of). Mozilla was substantially written in Javascript around a core engine written in C. Several CAD packages, Interleaf (a technical document publishing system) and of course EMACS are substantially written in LISP with a central C, assembly language or other core. Quite a few commercial and open-source applications (e.g. Chandler or Sungard Front Arena) use embedded Python interpreters and implement substantial parts of the application in Python.
EDIT: In rsponse to Dutch Masters' comment, keeping someone with C or C++ programming skills on the team for a Python project gives you the option of writing some of the application for speed. The areas where you can expect to get a significant performance gain are where the application does something highly iterative over a large data structure or large volume of data. In the case of the row-counter above it had to inhale a series of files totalling several gigabytes and go through a process where it read a varying length prefix and used that to determine the length of the data field. Most of the fields were short (just a few bytes long). This was somewhat bit-twiddly and very low level and iterative, which made it a natural fit for C.
Many of the python libraries such as numpy, cElementTree or cStringIO make use of an optimised C core with a python API that facilitates working with data in aggregate. For example, numpy has matrix data structures and operations written in C which do all the hard work and a Python API that provides services at the aggregate level.
|
Evaluate environment variables into a string
|
I have a string representing a path. Because this application is used on Windows, OSX and Linux, we've defined environment variables to properly map volumes from the different file systems. The result is:
"$C/test/testing"
What I want to do is evaluate the environment variables in the string so that they're replaced by their respective volume names. Is there a specific command I'm missing, or do I have to take os.environ.keys() and manually replace the strings?
|
Use os.path.expandvars to expand the environment variables in the string, for example:
>>> os.path.expandvars('$C/test/testing')
'/stackoverflow/test/testing'
|
What are the steps to make a ModelForm work with a ManyToMany relationship with an intermediary model in Django?
|
I have a Client and Groupe Model.
A Client can be part of multiple groups.
Clients that are part of a group can use its group's free rental rate at anytime but only once. That is where the intermediary model (ClientGroupe) comes in with that extra data.
For now, when I try to save the m2m data, it just dies and says I should use the ClientGroupe Manager...so what's missing?
Here are my models:
class Groupe(models.Model):
nom = models.CharField(max_length=1500, blank=True)
class Client(models.Model):
nom = models.CharField(max_length=450, blank=True)
prenom = models.CharField(max_length=450, blank=True)
groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe')
class ClientGroupe(models.Model):
client = models.ForeignKey(Client)
groupe = models.ForeignKey(Groupe)
dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate
class Meta:
db_table = u'clients_groupes'
and here's my view:
def modifier(request, id):
client = Client.objects.get(id=id)
form = ClientForm(instance = client)
dict = {
"form": form
, "instance" : client
}
if request.method == "POST":
form = ClientForm(request.POST, instance = client)
if form.is_valid():
client_mod = form.save()
id = client_mod.id
return HttpResponseRedirect(
"/client/%(id)s/?err=success" % {"id" : id}
)
else:
return HttpResponseRedirect(
"/client/%(id)s/?err=warning" % {"id" : id}
)
return render_to_response(
"client/modifier.html"
, dict
, context_instance=RequestContext(request)
)
EDIT:
and here's the ClientForm code:
class ClientForm(ModelForm):
class Meta:
model = Client
EDIT #2:
here's the error message:
AttributeError at /client/445/
Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead.
Request Method: POST
Request URL: http://localhost/client/445/
Exception Type: AttributeError
Exception Value: Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead.
Exception Location: C:\Python25\lib\site-packages\django\db\models\fields\related.py in __set__, line 574
Python Executable: C:\xampp\apache\bin\apache.exe
Python Version: 2.5.2
|
If you use the save method right now, Django will try to save using the manager (which Django doesn't allow). Unfortunately, the behavior you want is a little bit trickier than what ModelForm does by default. What you need to do is create a formset.
First of all, you will need to change the options of your ClientForm so that it doesn't display the groupes attribute.
class ClientForm(ModelForm):
class Meta:
model = Client
exclude = ('groupes',)
Next, you must change the view to display the formset:
from django.forms.models import inlineformset_factory
def modifier(request, id):
client = Client.objects.get(id=id)
form = ClientForm(instance = client)
# Create the formset class
GroupeFormset = inlineformset_factory(Client, Groupe)
# Create the formset
formset = GroupeFormset(instance = client)
dict = {
"form": form
, "formset" : formset
, "instance" : client
}
if request.method == "POST":
form = ClientForm(request.POST, instance = client)
formset = GroupeFormset(request.POST, instance = client)
if form.is_valid() and formset.is_valid():
client_mod = form.save()
formset.save()
id = client_mod.id
return HttpResponseRedirect(
"/client/%(id)s/?err=success" % {"id" : id}
)
else:
return HttpResponseRedirect(
"/client/%(id)s/?err=warning" % {"id" : id}
)
return render_to_response(
"client/modifier.html"
, dict
, context_instance=RequestContext(request)
)
And obviously, you must also tweak your template to render the formset.
If you need any other advice on formsets, see these articles:
Model formsets
Formsets
|
How to gracefully deal with failed future feature (__future__) imports due to old interpreter version?
|
How do you gracefully handle failed future feature imports? If a user is running using Python 2.5 and the first statement in my module is:
from __future__ import print_function
Compiling this module for Python 2.5 will fail with a:
File "__init__.py", line 1
from __future__ import print_function
SyntaxError: future feature print_function is not defined
I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so. However, to quote PEP 236:
The only lines that can appear before
a future_statement are:
The module docstring (if any).
Comments.
Blank lines.
Other future_statements.
So I can't do something like:
import __future__
if hasattr(__future__, 'print_function'):
from __future__ import print_function
else:
raise ImportError('Python >= 2.6 is required')
Because it yields:
File "__init__.py", line 4
from __future__ import print_function
SyntaxError: from __future__ imports must occur at the beginning of the file
This snippet from the PEP seems to give hope of doing it inline:
Q: I want to wrap future_statements
in try/except blocks, so I can use
different code depending on which
version of Python I'm running. Why
can't I?
A: Sorry! try/except is a runtime
feature; future_statements are
primarily compile-time gimmicks, and
your try/except happens long after the
compiler is done. That is, by the
time you do try/except, the semantics
in effect for the module are already a
done deal. Since the try/except
wouldn't accomplish what it looks
like it should accomplish, it's simply
not allowed. We also want to keep
these special statements very easy to
find and to recognize.
Note that you can import __future__
directly, and use the information in
it, along with sys.version_info, to
figure out where the release you're
running under stands in relation to a
given feature's status.
Ideas?
|
"I'd like to inform the user that they need to rerun the program with Python >= 2.6 and maybe provide some instructions on how to do so."
Isn't that what a README file is for?
Here's your alternative. A "wrapper": a little blob of Python that checks the environment before running your target aop.
File: appwrapper.py
import sys
major, minor, micro, releaselevel, serial = sys.version_info
if (major,minor) <= (2,5):
# provide advice on getting version 2.6 or higher.
sys.exit(2)
import app
app.main()
What "direct import" means. You can examine the contents of __future__. You're still bound by the fact the a from __future__ import print_function is information to the compiler, but you can poke around before importing the module that does the real work.
import __future__, sys
if hasattr(__future__, 'print_function'):
# Could also check sys.version_info >= __future__. print_function.optional
import app
app.main()
else:
print "instructions for upgrading"
|
How do I use the built in password reset/change views with my own templates
|
For example I can point the url '^/accounts/password/reset/$' to django.contrib.auth.views.password_reset with my template filename in the context but I think need to send more context details.
I need to know exactly what context to add for each of the password reset and change views.
|
If you take a look at the sources for django.contrib.auth.views.password_reset you'll see that it uses RequestContext. The upshot is, you can use Context Processors to modify the context which may allow you to inject the information that you need.
The b-list has a good introduction to context processors.
Edit (I seem to have been confused about what the actual question was):
You'll notice that password_reset takes a named parameter called template_name:
def password_reset(request, is_admin_site=False,
template_name='registration/password_reset_form.html',
email_template_name='registration/password_reset_email.html',
password_reset_form=PasswordResetForm,
token_generator=default_token_generator,
post_reset_redirect=None):
Check password_reset for more information.
... thus, with a urls.py like:
from django.conf.urls.defaults import *
from django.contrib.auth.views import password_reset
urlpatterns = patterns('',
(r'^/accounts/password/reset/$', password_reset, {'template_name': 'my_templates/password_reset.html'}),
...
)
django.contrib.auth.views.password_reset will be called for URLs matching '/accounts/password/reset' with the keyword argument template_name = 'my_templates/password_reset.html'.
Otherwise, you don't need to provide any context as the password_reset view takes care of itself. If you want to see what context you have available, you can trigger a TemplateSyntax error and look through the stack trace find the frame with a local variable named context. If you want to modify the context then what I said above about context processors is probably the way to go.
In summary: what do you need to do to use your own template? Provide a template_name keyword argument to the view when it is called. You can supply keyword arguments to views by including a dictionary as the third member of a URL pattern tuple.
|
Producing documentation for Python classes
|
I'm about to start a project where I will be the only one doing actual code and two less experienced programmers (scary to think of myself as experienced!) will be watching and making suggestions on the program in general.
Is there a good (free) system that I can use to provide documentation for classes and functions based on the code I've written? It'd likely help them a lot in getting to grips with the structure of the data.
|
I have used epydoc to generate documentation for Python modules from embedded docstrings. It's pretty easy to use and generates nice looking output in multiple formats.
|
Elegant ways to support equivalence ("equality") in Python classes
|
When writing custom classes it is often important to allow equivalence by means of the == and != operators. In Python, this is made possible by implementing the __eq__ and __ne__ special methods, respectively. The easiest way I've found to do this is the following method:
class Foo:
def __init__(self, item):
self.item = item
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing __dict__s?
Note: A bit of clarification--when __eq__ and __ne__ are undefined, you'll find this behavior:
>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
False
That is, a == b evaluates to False because it really runs a is b, a test of identity (i.e., "Is a the same object as b?").
When __eq__ and __ne__ are defined, you'll find this behavior (which is the one we're after):
>>> a = Foo(1)
>>> b = Foo(1)
>>> a is b
False
>>> a == b
True
|
You need to be careful with inheritance:
>>> class Foo:
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
>>> class Bar(Foo):pass
>>> b = Bar()
>>> f = Foo()
>>> f == b
True
>>> b == f
False
Check types more strictly, like this:
def __eq__(self, other):
if type(other) is type(self):
return self.__dict__ == other.__dict__
return False
Besides that, your approach will work fine, that's what special methods are there for.
|
How do you debug Mako templates?
|
So far I've found it impossible to produce usable tracebacks when Mako templates aren't coded correctly.
Is there any way to debug templates besides iterating for every line of code?
|
Mako actually provides a VERY nice way to track down errors in a template:
from mako import exceptions
try:
template = lookup.get_template(uri)
print template.render()
except:
print exceptions.html_error_template().render()
|
Is there any built-in way to get the length of an iterable in python?
|
For example, files, in Python, are iterable - they iterate over the lines in the file. I want to count the number of lines.
One quick way is to do this:
lines = len(list(open(fname)))
However, this loads the whole file into memory (at once). This rather defeats the purpose of an iterator (which only needs to keep the current line in memory).
This doesn't work:
lines = len(line for line in open(fname))
as generators don't have a length.
Is there any way to do this short of defining a count function?
def count(i):
c = 0
for el in i: c += 1
return c
EDIT: To clarify, I understand that the whole file will have to be read! I just don't want it in memory all at once =).
|
Short of iterating through the iterable and counting the number of iterations, no. That's what makes it an iterable and not a list. This isn't really even a python-specific problem. Look at the classic linked-list data structure. Finding the length is an O(n) operation that involves iterating the whole list to find the number of elements.
As mcrute mentioned above, you can probably reduce your function to:
def count_iterable(i):
return sum(1 for e in i)
Of course, if you're defining your own iterable object you can always implement __len__ yourself and keep an element count somewhere.
|
Organising my Python project
|
I'm starting a Python project and expect to have 20 or more classes in it. As is good practice I want to put them in a separate file each. However, the project directory quickly becomes swamped with files (or will when I do this).
If I put a file to import in a folder I can no longer import it. How do I import a file from another folder and will I need to reference to the class it contains differently now that it's in a folder?
Thanks in advance
|
Create an __init__.py file in your projects folder, and it will be treated like a module by Python.
Classes in your package directory can then be imported using syntax like:
from package import class
import package.class
Within __init__.py, you may create an __all__ array that defines from package import * behavior:
# name1 and name2 will be available in calling module's namespace
# when using "from package import *" syntax
__all__ = ['name1', 'name2']
And here is way more information than you even want to know about packages in Python
Generally speaking, a good way to learn about how to organize a lot of code is to pick a popular Python package and see how they did it. I'd check out Django and Twisted, for starters.
|
Python Optparse list
|
I'm using the python optparse module in my program, and I'm having trouble finding an easy way to parse an option that contains a list of values.
For example:
--groups one,two,three.
I'd like to be able to access these values in a list format as options.groups[]. Is there an optparse option to convert comma separated values into a list? Or do I have to do this manually?
|
S.Lott's answer has already been accepted, but here's a code sample for the archives:
def foo_callback(option, opt, value, parser):
setattr(parser.values, option.dest, value.split(','))
parser = OptionParser()
parser.add_option('-f', '--foo',
type='string',
action='callback',
callback=foo_callback)
|
What are your (concrete) use-cases for metaclasses in Python?
|
I have a friend who likes to use metaclasses, and regularly offers them as a solution.
I am of the mind that you almost never need to use metaclasses. Why? because I figure if you are doing something like that to a class, you should probably be doing it to an object. And a small redesign/refactor is in order.
Being able to use metaclasses has caused a lot of people in a lot of places to use classes as some kind of second rate object, which just seems disastrous to me. Is programming to be replaced by meta-programming? The addition of class decorators has unfortunately made it even more acceptable.
So please, I am desperate to know your valid (concrete) use-cases for metaclasses in Python. Or to be enlightened as to why mutating classes is better than mutating objects, sometimes.
I will start:
Sometimes when using a third-party
library it is useful to be able to
mutate the class in a certain way.
(this is the only case I can think of, and it's not concrete)
|
The purpose of metaclasses isn't to replace the class/object distinction with metaclass/class - it's to change the behaviour of class definitions (and thus their instances) in some way. Effectively it's to alter the behaviour of the class statement in ways that may be more useful for your particular domain than the default. The things I have used them for are:
Tracking subclasses, usually to register handlers. This is handy when using a plugin style setup, where you wish to register a handler for a particular thing simply by subclassing and setting up a few class attributes. eg. suppose you write a handler for various music formats, where each class implements appropriate methods (play / get tags etc) for its type. Adding a handler for a new type becomes:
class Mp3File(MusicFile):
extensions = ['.mp3'] # Register this type as a handler for mp3 files
...
# Implementation of mp3 methods go here
The metaclass then maintains a dictionary of {'.mp3' : MP3File, ... } etc, and constructs an object of the appropriate type when you request a handler through a factory function.
Changing behaviour. You may want to attach a special meaning to certain attributes, resulting in altered behaviour when they are present. For example, you may want to look for methods with the name _get_foo and _set_foo and transparently convert them to properties. As a real-world example, here's a recipe I wrote to give more C-like struct definitions. The metaclass is used to convert the declared items into a struct format string, handling inheritance etc, and produce a class capable of dealing with it.
For other real-world examples, take a look at various ORMs, like sqlalchemy's ORM or sqlobject. Again, the purpose is to interpret defintions (here SQL column definitions) with a particular meaning.
|
Modify bound variables of a closure in Python
|
Is there any way to modify the bound value of one of the variables inside a closure? Look at the example to understand it better.
def foo():
var_a = 2
var_b = 3
def _closure(x):
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
# ...but what magic? Is this even possible?
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
|
It is quite possible in python 3 thanks to the magic of nonlocal.
def foo():
var_a = 2
var_b = 3
def _closure(x, magic = None):
nonlocal var_a
if magic is not None:
var_a = magic
return var_a + var_b + x
return _closure
localClosure = foo()
# Local closure is now "return 2 + 3 + x"
a = localClosure(1) # 2 + 3 + 1 == 6
print(a)
# DO SOME MAGIC HERE TO TURN "var_a" of the closure into 0
localClosure(0, 0)
# Local closure is now "return 0 + 3 + x"
b = localClosure(1) # 0 + 3 +1 == 4
print(b)
|
Good language to develop a game server in?
|
I was just wondering what language would be a good choice for developing a game server to support a large (thousands) number of users? I dabbled in python, but realized that it would just be too much trouble since it doesn't spawn threads across cores (meaning an 8 core server=1 core server). I also didn't really like the language (that "self" stuff grossed me out).
I know that C++ is the language for the job in terms of performance, but I hate it. I don't want to deal with its sloppy syntax and I like my hand to be held by managed languages. This brings me to C# and Java, but I am open to other languages. I love the simplicity of .NET, but I was wondering if, speed wise, this would be good for the job. Keep in mind since this will be deployed on a Linux server, it would be running on the Mono framework - not sure if that matters. I know that Java is syntax-wise very similar to .Net, but my experience with it is limited. Are there any frameworks out there for it or anthing to ease in the development?
Please help me and my picky self arrive on a solution.
UPDATE: I didn't mean to sound so picky, and I really don't think I was. The only language I really excluded was C++, Python I don't like because of the scalability problem. I know that there are ways of communicating between processes, but if I have an 8 core server, why should I need to make 8 processes? Is there a more elegant solution?
|
I hate to say it, and I know I'm risking a down mod here, but it doesn't sound like there's a language out there for you. All programming languages have their quirks and programmers simply have to adapt to them. It's completely possible to write a working server in Python without classes (eliminating the "self" variable class references) and likewise just as easy to write C++ with clean syntax.
If you're looking to deploy cross-platform and want to develop cross-platform as well, your best bet would probably be Java. It shorter development cycles than compiled languages like C and C++, but is higher performance (arguable, but I've always been anti-Java =P) than interpreted languages like Python and Perl and you don't have to work with unofficial implementations like Mono that may from time to time not support all of a language's features.
|
Length of generator output
|
Python provides a nice method for getting length of an eager iterable, len(x) that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:
def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
But I can't get rid of a feeling that I'm reimplementing a bicycle.
(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).
P.S.: concerning the first answers - yes, something like len(list(x)) would work too, but that drastically increases the usage of memory.
P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.
|
The easiest way is probably just sum(1 for _ in gen) where gen is your generator.
|
Python sqlite3 and concurrency
|
I have a Python program that uses the "threading" module. Once every second, my program starts a new thread that fetches some data from the web, and stores this data to my hard drive. I would like to use sqlite3 to store these results, but I can't get it to work. The issue seems to be about the following line:
conn = sqlite3.connect("mydatabase.db")
If I put this line of code inside each thread, I get an OperationalError telling me that the database file is locked. I guess this means that another thread has mydatabase.db open through a sqlite3 connection and has locked it.
If I put this line of code in the main program and pass the connection object (conn) to each thread, I get a ProgrammingError, saying that SQLite objects created in a thread can only be used in that same thread.
Previously I was storing all my results in CSV files, and did not have any of these file-locking issues. Hopefully this will be possible with sqlite. Any ideas?
|
Contrary to popular belief, newer versions of sqlite3 do support access from multiple threads.
This can be enabled via optional keyword argument check_same_thread:
sqlite.connect(":memory:", check_same_thread=False)
|
python and regular expression with unicode
|
I need to delete some unicode symbols from the string 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù'
I know they exist here for sure. I try:
re.sub('([\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+)', '', 'Ø¨ÙØ³ÙÙ
٠اÙÙÙÙÙÙ Ø§ÙØ±ÙÙØÙÙ
ÙÙ°ÙÙ Ø§ÙØ±ÙÙØÙÙÙ
Ù')
but it doesn't work. String stays the same. ant suggestion what i do wrong?
|
Are you using python 2.x or 3.0?
If you're using 2.x, try making the regex string a unicode-escape string, with 'u'. Since it's regex it's good practice to make your regex string a raw string, with 'r'. Also, putting your entire pattern in parentheses is superfluous.
re.sub(ur'[\u064B-\u0652\u06D4\u0670\u0674\u06D5-\u06ED]+', '', ...)
http://docs.python.org/tutorial/introduction.html#unicode-strings
Edit:
It's also good practice to use the re.UNICODE/re.U/(?u) flag for unicode regexes, but it only affects character class aliases like \w or \b, of which this pattern does not use any and so would not be affected by.
|
Python POST data using mod_wsgi
|
This must be a very simple question, but I don't seem to be able to figure out.
I'm using apache + mod_wsgi to host my python application, and I'd like to get the post content submitted in one of the forms -however, neither the environment values, nor sys.stdin contains any of this data. Mind giving me a quick hand?
Edit:
Tried already:
environ["CONTENT_TYPE"] = 'application/x-www-form-urlencoded' (no data)
environ["wsgi.input"] seems a plausible way, however, both environ["wsgi.input"].read(), and environ["wsgi.input"].read(-1) returns an empty string (yes, content has been posted, and environ["request_method"] = "post"
|
PEP 333 says you must read environ['wsgi.input'].
I just saved the following code and made apache's mod_wsgi run it. It works.
You must be doing something wrong.
from pprint import pformat
def application(environ, start_response):
# show the environment:
output = ['<pre>']
output.append(pformat(environ))
output.append('</pre>')
#create a simple form:
output.append('<form method="post">')
output.append('<input type="text" name="test">')
output.append('<input type="submit">')
output.append('</form>')
if environ['REQUEST_METHOD'] == 'POST':
# show form data as received by POST:
output.append('<h1>FORM DATA</h1>')
output.append(pformat(environ['wsgi.input'].read()))
# send results
output_len = sum(len(line) for line in output)
start_response('200 OK', [('Content-type', 'text/html'),
('Content-Length', str(output_len))])
return output
|
Override a method at instance level
|
Is there a way in Python to override a class method at instance level?
For example:
class Dog:
def bark(self):
print "WOOF"
boby = Dog()
boby.bark() # WOOF
# METHOD OVERRIDE
boby.bark() # WoOoOoF!!
|
Yes, it's possible:
class Dog:
def bark(self):
print "Woof"
def new_bark(self):
print "Woof Woof"
foo = Dog()
funcType = type(Dog.bark)
# "Woof"
foo.bark()
# replace bark with new_bark for this object only
foo.bark = funcType(new_bark, foo, Dog)
foo.bark()
# "Woof Woof"
|
Does Python have a ternary conditional operator?
|
If Python does not have a ternary conditional operator, is it possible to simulate one using other language constructs?
|
Yes, it was added in version 2.5.
The syntax is:
a if condition else b
First condition is evaluated, then either a or b is returned based on the Boolean value of condition
If condition evaluates to True a is returned, else b is returned.
For example:
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
Keep in mind that it's frowned upon by some Pythonistas for several reasons:
The order of the arguments is different from many other languages (such as C, Ruby, Java, etc.), which may lead to bugs when people unfamiliar with Python's "surprising" behaviour use it (they may reverse the order).
Some find it "unwieldy", since it goes contrary to the normal flow of thought (thinking of the condition first and then the effects).
Stylistic reasons.
If you're having trouble remembering the order, then remember that if you read it out loud, you (almost) say what you mean. For example, x = 4 if b > 8 else 9 is read aloud as x will be 4 if b is greater than 8 otherwise 9.
Official documentation:
Conditional expressions
Is there an equivalent of Câs â?:â ternary operator?
|
Can I use a ForeignKey in __unicode__ return?
|
I have the following classes: Ingredients, Recipe and RecipeContent...
class Ingredient(models.Model):
name = models.CharField(max_length=30, primary_key=True)
qty_on_stock = models.IntegerField()
def __unicode__(self):
return self.name
class Recipe(models.Model):
name = models.CharField(max_length=30, primary_key=True)
comments = models.TextField(blank=True)
ingredient = models.ManyToManyField(Ingredient)
def __unicode__(self):
return self.name
class RecipeContent(models.Model):
recipe = models.ForeignKey(Recipe)
ingredients = models.ForeignKey(Ingredient)
qty_used = models.IntegerField()
but for __unicode__() in RecipeContent I would like to use the Recipe name to which this RecipeContent belongs to... is there a way to do it?
|
class RecipeContent(models.Model):
...
def __unicode__(self):
# You can access ForeignKey properties through the field name!
return self.recipe.name
|
How to check whether a variable is a class or not?
|
I was wondering how to check whether a variable is a class (not an instance!) or not.
I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type would a class will have.
For example, in the following code
class Foo: pass
isinstance(Foo, **???**) # i want to make this return True.
I tried to substitute "class" with ???, but I realized that class is a keyword in python.
|
Even better: use the inspect.isclass function.
>>> import inspect
>>> class X(object):
... pass
...
>>> inspect.isclass(X)
True
>>> x = X()
>>> isinstance(x, X)
True
>>> y = 25
>>> isinstance(y, X)
False
|
"MetaClass", "__new__", "cls" and "super" - what is the mechanism exactly?
|
I have read posts like these:
What is a metaclass in Python?
What are your (concrete) use-cases for metaclasses in Python?
Python's Super is nifty, but you can't use it
But somehow I got confused. Many confusions like:
When and why would I have to do something like the following?
# Refer link1
return super(MyType, cls).__new__(cls, name, bases, newattrs)
or
# Refer link2
return super(MetaSingleton, cls).__call__(*args, **kw)
or
# Refer link2
return type(self.__name__ + other.__name__, (self, other), {})
How does super work exactly?
What is class registry and unregistry in link1 and how exactly does it work? (I thought it has something to do with singleton. I may be wrong, being from C background. My coding style is still a mix of functional and OO).
What is the flow of class instantiation (subclass, metaclass, super, type) and method invocation (
metaclass->__new__, metaclass->__init__, super->__new__, subclass->__init__ inherited from metaclass
) with well-commented working code (though the first link is quite close, but it does not talk about cls keyword and super(..) and registry). Preferably an example with multiple inheritance.
P.S.: I made the last part as code because Stack Overflow formatting was converting the text metaclass->__new__
to metaclass->new
|
OK, you've thrown quite a few concepts into the mix here! I'm going to pull out a few of the specific questions you have.
In general, understanding super, the MRO and metclasses is made much more complicated because there have been lots of changes in this tricky area over the last few versions of Python.
Python's own documentation is a very good reference, and completely up to date. There is an IBM developerWorks article which is fine as an introduction and takes a more tutorial-based approach, but note that it's five years old, and spends a lot of time talking about the older-style approaches to meta-classes.
super is how you access an object's super-classes. It's more complex than (for example) Java's super keyword, mainly because of multiple inheritance in Python. As Super Considered Harmful explains, using super() can result in you implicitly using a chain of super-classes, the order of which is defined by the Method Resolution Order (MRO).
You can see the MRO for a class easily by invoking mro() on the class (not on an instance). Note that meta-classes are not in an object's super-class hierarchy.
Thomas' description of meta-classes here is excellent:
A metaclass is the class of a class.
Like a class defines how an instance
of the class behaves, a metaclass
defines how a class behaves. A class
is an instance of a metaclass.
In the examples you give, here's what's going on:
The call to __new__ is being
bubbled up to the next thing in the
MRO. In this case, super(MyType,
cls) would resolve to type;
calling type.__new__ lets Python
complete it's normal instance
creation steps.
This example is using meta-classes
to enforce a singleton. He's
overriding __call__ in the
metaclass so that whenever a class
instance is created, he intercepts
that, and can bypass instance
creation if there already is one
(stored in cls.instance). Note
that overriding __new__ in the
metaclass won't be good enough,
because that's only called when
creating the class. Overriding
__new__ on the class would work,
however.
This shows a way to dynamically
create a class. Here's he's
appending the supplied class's name
to the created class name, and
adding it to the class hierarchy
too.
I'm not exactly sure what sort of code example you're looking for, but here's a brief one showing meta-classes, inheritance and method resolution:
class MyMeta(type):
def __new__(cls, name, bases, dct):
print "meta: creating %s %s" % (name, bases)
return type.__new__(cls, name, bases, dct)
def meta_meth(cls):
print "MyMeta.meta_meth"
__repr__ = lambda c: c.__name__
class A(object):
__metaclass__ = MyMeta
def __init__(self):
super(A, self).__init__()
print "A init"
def meth(self):
print "A.meth"
class B(object):
__metaclass__ = MyMeta
def __init__(self):
super(B, self).__init__()
print "B init"
def meth(self):
print "B.meth"
class C(A, B):
__metaclass__ = MyMeta
def __init__(self):
super(C, self).__init__()
print "C init"
>>> c_obj = C()
meta: creating A (<type 'object'>,)
meta: creating B (<type 'object'>,)
meta: creating C (A, B)
B init
A init
C init
>>> c_obj.meth()
A.meth
>>> C.meta_meth()
MyMeta.meta_meth
>>> c_obj.meta_meth()
Traceback (most recent call last):
File "mro.py", line 38, in <module>
c_obj.meta_meth()
AttributeError: 'C' object has no attribute 'meta_meth'
|
Checking if two strings are permutations of each other in Python
|
I'm checking if two strings a and b are permutations of each other, and I'm wondering what the ideal way to do this is in Python. From the Zen of Python, "There should be one -- and preferably only one -- obvious way to do it," but I see there are at least two ways:
sorted(a) == sorted(b)
and
all(a.count(char) == b.count(char) for char in a)
but the first one is slower when (for example) the first char of a is nowhere in b, and the second is slower when they are actually permutations.
Is there any better (either in the sense of more Pythonic, or in the sense of faster on average) way to do it? Or should I just choose from these two depending on which situation I expect to be most common?
|
Here is a way which is O(n), asymptotically better than the two ways you suggest.
import collections
def same_permutation(a, b):
d = collections.defaultdict(int)
for x in a:
d[x] += 1
for x in b:
d[x] -= 1
return not any(d.itervalues())
## same_permutation([1,2,3],[2,3,1])
#. True
## same_permutation([1,2,3],[2,3,1,1])
#. False
|
How to instantiate a class in python
|
So, I'm trying to learn Python. It seems pretty easy, but evidently, I don't understand how classes are used. The following code gives me an error when I try to use the class.
class mystuff:
def average(a,b,c): #get the average of three numbers
result=a+b+c
result=result/3
return result
#now use the function average from the mystuff class
print mystuff.average(9,18,27)
File "class.py", line 7, in <module>
print mystuff.average(9,18,27)
TypeError: unbound method average() must be called with mystuff instance as first argument (got int instance instead)
What's wrong?
|
You can instantiate the class by declaring a variable and calling the class as if it were a function:
x = mystuff()
print x.average(9,18,27)
However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:
TypeError: average() takes exactly 3 arguments (4 given)
To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.
|
In Python, how do I find the date of the first Monday of a given week?
|
If I have a certain week number (eg 51) and a given year (eg 2008), how do I find the date of the first Monday of that same week?
Many thanks
|
>>> import time
>>> time.asctime(time.strptime('2008 50 1', '%Y %W %w'))
'Mon Dec 15 00:00:00 2008'
Assuming the first day of your week is Monday, use %U instead of %W if the first day of your week is Sunday. See the documentation for strptime for details.
Update: Fixed week number. The %W directive is 0-based so week 51 would be entered as 50, not 51.
|
Confusing [...] List in Python: What is it?
|
So I was writing up a simple binary tree in Python and came across [...]
I don't believe this to be related to the Ellipsis object, more it seems to have something to do with an infinity loop (due to Python's shallow copy?). The source of this infinity loop and why it doesn't get expanded while expanding when accessed is something I'm completely lost to, however
>>> a
[[[[[], [], 8, 3], [[], [], 3, 2], 6, 3], [], 1, 4], [[], [], -4, 2], 0, 0]
>>> Keys(a)#With a+b
[0, 1, 6, 8, 3, -4]
>>> Keys(a)#With [a,b]
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
>>> Keys(a)[1]#??
[8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...], 8, [...], [...], 3, [...], [...], 6, [...], [...], 1, [...], [...], -4, [...], [...], 0, [...], [...]]
Version using a+b
def Keys(x,y=[]):
if len(x):y+=[x[2]]+Keys(x[0],y)+Keys(x[1],y)#Though it seems I was using y=y[:]+, this actually outputs an ugly mess
return y
version using [a,b]
def Keys(x,y=[]):
if len(x):y+=[x[2],Keys(x[0],y),Keys(x[1],y)]
return y
So what exactly is [...]?
|
It can also appear if you have a circular structure with a list pointing to itself. Like this:
>>> a = [1,2]
>>> a.append(a)
>>> a
[1, 2, [...]]
>>>
Since python can't print out the structure (it would be an infinite loop) it uses the ellipsis to show that there is recursion in the structure.
I'm not quite sure if the question was what what going on or how to fix it, but I'll try to correct the functions above.
In both of them, you first make two recursive calls, which add data to the list y, and then AGAIN append the returned data to y. This means the same data will be present several times in the result.
Either just collect all the data without adding to any y, with something like
return [x[2]]+keys(x[0])+keys(x[1])
or just do the appending in the calls, with something like
y += [x[2]]
keys(x[0], y) #Add left children to y...
keys(x[1], y) #Add right children to y...
return y
(Of course, both these snippets need handling for empty lists etc)
@Abgan also noted that you really don't want y=[] in the initializer.
|
Reading the target of a .lnk file in Python?
|
I'm trying to read the target file/directory of a shortcut (.lnk) file from Python. Is there a headache-free way to do it? The .lnk spec [PDF] is way over my head.
I don't mind using Windows-only APIs.
My ultimate goal is to find the "(My) Videos" folder on Windows XP and Vista. On XP, by default, it's at %HOMEPATH%\My Documents\My Videos, and on Vista it's %HOMEPATH%\Videos. However, the user can relocate this folder. In the case, the %HOMEPATH%\Videos folder ceases to exists and is replaced by %HOMEPATH%\Videos.lnk which points to the new "My Videos" folder. And I want its absolute location.
|
Create a shortcut using Python (via WSH)
import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()
Read the Target of a Shortcut using Python (via WSH)
import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)
|
Why doesn't Python have multiline comments?
|
OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
"""Hello, I am a
multiline comment"""
and
'''Hello, I am a
multiline comment'''
But technically speaking these are strings, correct?
I've googled and read the Python style guide, but I was unable to find a technical answer to why there is no formal implementation of multiline, /* */ type of comments. I have no problem using triple quotes, but I am a little curious as to what led to this design decision.
|
I doubt you'll get a better answer than, "Guido didn't feel the need for multi-line comments".
Guido has tweeted about this,
Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)
|
Why can't I subclass datetime.date?
|
Why doesn't the following work (Python 2.5.2)?
>>> import datetime
>>> class D(datetime.date):
def __init__(self, year):
datetime.date.__init__(self, year, 1, 1)
>>> D(2008)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function takes exactly 3 arguments (1 given)
I wanted to create a class that was just like datetime.date, but with a different __init__ function. Apparently my function never gets called. Instead the original datetime.date.__init__ is called and fails because that expects 3 arguments and I am passing in one.
What's going on here? And is this a clue?
>>> datetime.date.__init__
<slot wrapper '__init__' of 'object' objects>
Thanks!
|
Regarding several other answers, this doesn't have anything to do with dates being implemented in C per se. The __init__ method does nothing because they are immutable objects, therefore the constructor (__new__) should do all the work. You would see the same behavior subclassing int, str, etc.
>>> import datetime
>>> class D(datetime.date):
def __new__(cls, year):
return datetime.date.__new__(cls, year, 1, 1)
>>> D(2008)
D(2008, 1, 1)
|
Extended slice that goes to beginning of sequence with negative stride
|
Bear with me while I explain my question. Skip down to the bold heading if you already understand extended slice list indexing.
In python, you can index lists using slice notation. Here's an example:
>>> A = list(range(10))
>>> A[0:5]
[0, 1, 2, 3, 4]
You can also include a stride, which acts like a "step":
>>> A[0:5:2]
[0, 2, 4]
The stride is also allowed to be negative, meaning the elements are retrieved in reverse order:
>>> A[5:0:-1]
[5, 4, 3, 2, 1]
But wait! I wanted to see [4, 3, 2, 1, 0]. Oh, I see, I need to decrement the start and end indices:
>>> A[4:-1:-1]
[]
What happened? It's interpreting -1 as being at the end of the array, not the beginning. I know you can achieve this as follows:
>>> A[4::-1]
[4, 3, 2, 1, 0]
But you can't use this in all cases. For example, in a method that's been passed indices.
My question is:
Is there any good pythonic way of using extended slices with negative strides and explicit start and end indices that include the first element of a sequence?
This is what I've come up with so far, but it seems unsatisfying.
>>> A[0:5][::-1]
[4, 3, 2, 1, 0]
|
It is error-prone to change the semantics of start and stop. Use None or -(len(a) + 1) instead of 0 or -1. The semantics is not arbitrary. See Edsger W. Dijkstra's article "Why numbering should start at zero".
>>> a = range(10)
>>> start, stop, step = 4, None, -1
Or
>>> start, stop, step = 4, -(len(a) + 1), -1
>>> a[start:stop:step]
[4, 3, 2, 1, 0]
Or
>>> s = slice(start, stop, step)
>>> a[s]
[4, 3, 2, 1, 0]
When s is a sequence the negative indexes in s[i:j:k] are treated specially:
If i or j is negative, the index is relative to the end of the string:
len(s) + i or len(s) + j is substituted. But note that -0 is still 0.
that is why len(range(10)[4:-1:-1]) == 0 because it is equivalent to range(10)[4:9:-1].
|
Failing to send email with the Python example
|
I've been trying (and failing) to figure out how to send email via Python.
Trying the example from here:
http://docs.python.org/library/smtplib.html#smtplib.SMTP
but added the line server = smtplib.SMTP_SSL('smtp.gmail.com', 465) after I got a bounceback about not having an SSL connection.
Now I'm getting this:
Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_EmailSendExample_NotWorkingYet.py", line 37, in <module>
server = smtplib.SMTP('smtp.gmail.com', 65)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 273, in _get_socket
return socket.create_connection((port, host), timeout)
File "C:\Python26\lib\socket.py", line 512, in create_connection
raise error, msg
error: [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
>>>
Thoughts?
server = smtplib.SMTP("smtp.google.com", 495) gives me a timeout error. just smtplib.smtp("smtp.google.com", 495) gives me "SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol" (see below).
I'm trying different ports and now I'm getting a completely new error. I'll just post the whole bit of code, I'm probably making some rookie mistake.
"
import smtplib
mailuser = 'MYEMAIL@gmail.com'
mailpasswd = 'MYPASSWORD'
fromaddr = 'MYEMAIL@gmail.com'
toaddrs = 'MYEMAIL2@gmail.com'
msg = 'Hooooorah!'
print msg
server = smtplib.SMTP_SSL('smtp.google.com')
server = smtplib.SMTP_SSL_PORT=587
server.user(mailuser)
server.pass_(mailpasswd)
server.set_debuglevel(1)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
"
and then I get this error message: "
Traceback (most recent call last):
File "C:/Python26/08_emailconnects/12_29_eMAILSendtryin_stripped.py", line 16, in <module>
server = smtplib.SMTP_SSL('smtp.google.com')
File "C:\Python26\lib\smtplib.py", line 749, in __init__
SMTP.__init__(self, host, port, local_hostname, timeout)
File "C:\Python26\lib\smtplib.py", line 239, in __init__
(code, msg) = self.connect(host, port)
File "C:\Python26\lib\smtplib.py", line 295, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Python26\lib\smtplib.py", line 755, in _get_socket
self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
File "C:\Python26\lib\ssl.py", line 350, in wrap_socket
suppress_ragged_eofs=suppress_ragged_eofs)
File "C:\Python26\lib\ssl.py", line 118, in __init__
self.do_handshake()
File "C:\Python26\lib\ssl.py", line 293, in do_handshake
self._sslobj.do_handshake()
SSLError: [Errno 1] _ssl.c:480: error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol
"
note that actually the which looks like "server = smtplib.SMTPSSLPORT=587" is actually "server = smtplib.SMTP underscore SSL underscore PORT=587", there's some sort of formatting thing going on here.
|
The following code works for me:
import smtplib
FROMADDR = "my.real.address@gmail.com"
LOGIN = FROMADDR
PASSWORD = "my.real.password"
TOADDRS = ["my.real.address@gmail.com"]
SUBJECT = "Test"
msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n"
% (FROMADDR, ", ".join(TOADDRS), SUBJECT) )
msg += "some text\r\n"
server = smtplib.SMTP('smtp.gmail.com', 587)
server.set_debuglevel(1)
server.ehlo()
server.starttls()
server.login(LOGIN, PASSWORD)
server.sendmail(FROMADDR, TOADDRS, msg)
server.quit()
I'm using Python 2.5.2.
Edit: changed port from 25 to 587 as suggested by ΤÎΩΤÎÎÎÎ¥, and dropped the second ehlo(). Now I would love to know why port 25 works perfectly from my machine (and port 465 does not).
|
How to integrate pep8.py in Eclipse?
|
A little background:
PEP 8 is the Style Guide for Python Code. It contains the conventions all python programmers should follow.
pep8.py is a (very useful) script that checks the code formating of a given python script, according to PEP 8.
Eclipse is a great IDE. With the Pydev extension, it that can be used to develop Python
I run pep8.py manually when I'm scripting, but with bigger projects I prefer to use Eclipse.
It would be really useful to integrate pep8.py in Eclipse/Pydev, so it can be run automatically in all the files in the project, and point to the lines containing the warnings.
Maybe there is an obvious way to do it, but I haven't found it yet.
Question is: How to integrate pep8.py in Eclipse?
|
As of PyDev 2.3.0, pep8 is integrated in PyDev by default, even shipping with a default version of it.
Open Window > Preferences
It must be enabled in PyDev > Editor > Code Analysis > pep8.py
Errors/Warnings should be shown as markers (as other things in the regular code analysis).
In the event a file is not analyzed, see https://stackoverflow.com/a/31001619/832230.
|
Resize image in Python without losing EXIF data
|
I need to resize jpg images with Python without losing the original image's EXIF data (metadata about date taken, camera model etc.). All google searches about python and images point to the PIL library which I'm currently using, but doesn't seem to be able to retain the metadata. The code I have so far (using PIL) is this:
img = Image.open('foo.jpg')
width,height = 800,600
if img.size[0] < img.size[1]:
width,height = height,width
resized_img = img.resize((width, height), Image.ANTIALIAS) # best down-sizing filter
resized_img.save('foo-resized.jpg')
Any ideas? Or other libraries that I could be using?
|
import jpeg
jpeg.setExif(jpeg.getExif('foo.jpg'), 'foo-resized.jpg')
http://www.emilas.com/jpeg/
|
Define css class in django Forms
|
Assume I have a form
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page?
I was hoping not to have to manually build the form.
|
Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: django-widget-tweaks. Hope somebody will find it useful.
|
Naming Python loggers
|
In Django, I've got loggers all over the place, currently with hard-coded names.
For module-level logging (i.e., in a module of view functions) I have the urge to do this.
log = logging.getLogger(__name__)
For class-level logging (i.e., in a class __init__ method) I have the urge to do this.
self.log = logging.getLogger("%s.%s" % (
self.__module__, self.__class__.__name__))
I'm looking for second opinions before I tackle several dozen occurrences of getLogger("hard.coded.name").
Will this work? Anyone else naming their loggers with the same unimaginative ways?
Further, should I break down and write a class decorator for this log definition?
|
I typically don't use or find a need for class-level loggers, but I keep my modules at a few classes at most. A simple:
import logging
LOG = logging.getLogger(__name__)
At the top of the module and subsequent:
LOG.info('Spam and eggs are tasty!')
from anywhere in the file typically gets me to where I want to be. This avoids the need for self.log all over the place, which tends to bother me from both a put-it-in-every-class perspective and makes me 5 characters closer to 79 character lines that fit.
You could always use a pseudo-class-decorator:
>>> import logging
>>> class Foo(object):
... def __init__(self):
... self.log.info('Meh')
...
>>> def logged_class(cls):
... cls.log = logging.getLogger('{0}.{1}'.format(__name__, cls.__name__))
...
>>> logged_class(Foo)
>>> logging.basicConfig(level=logging.DEBUG)
>>> f = Foo()
INFO:__main__.Foo:Meh
|
How to store a dictionary on a Django Model?
|
I need to store some data in a Django model. These data are not equal to all instances of the model.
At first I thought about subclassing the model, but Iâm trying to keep the application flexible. If I use subclasses, Iâll need to create a whole class each time I need a new kind of object, and thatâs no good. Iâll also end up with a lot of subclasses only to store a pair of extra fields.
I really feel that a dictionary would be the best approach, but thereâs nothing in the Django documentation about storing a dictionary in a Django model (or I canât find it).
Any clues?
|
If it's really dictionary like arbitrary data you're looking for you can probably use a two-level setup with one model that's a container and another model that's key-value pairs. You'd create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the container instance. Something like:
class Dicty(models.Model):
name = models.CharField(max_length=50)
class KeyVal(models.Model):
container = models.ForeignKey(Dicty, db_index=True)
key = models.CharField(max_length=240, db_index=True)
value = models.CharField(max_length=240, db_index=True)
It's not pretty, but it'll let you access/search the innards of the dictionary using the DB whereas a pickle/serialize solution will not.
|
How do you uninstall a python package that was installed using distutils?
|
Can you simply delete the directory from your python installation, or are there any lingering files that you must delete?
|
It varies based on the options that you pass to install and the contents of the distutils configuration files on the system/in the package. I don't believe that any files are modified outside of directories specified in these ways.
Notably, distutils does not have an uninstall command at this time.
It's also noteworthy that deleting a package/egg can cause dependency issues -- utilities like easy_install attempt to alleviate such problems.
|
How to determine the variable type in Python?
|
How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?
How do I view it?
|
Python doesn't have the same types as C/C++, which appears to be your question.
Try this:
>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123456789L
>>> type(i)
<type 'long'>
>>> type(i) is long
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True
The distinction between int and long goes away in Python 3.0, though.
|
How to sort a list of objects in Python, based on an attribute of the objects?
|
I've got a list of Python objects that I'd like to sort by an attribute of the objects themselves. The list looks like:
>>> ut
[<Tag: 128>, <Tag: 2008>, <Tag: <>, <Tag: actionscript>, <Tag: addresses>, <Tag: aes>, <Tag: ajax> ...]
Each object has a count:
>>> ut[1].count
1L
I need to sort the list by number of counts descending.
I've seen several methods for this, but I'm looking for best practice in Python.
|
# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)
# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)
More on sorting by keys »
|
Determining application path in a Python EXE generated by pyInstaller
|
I have an application that resides in a single .py file. I've been able to get pyInstaller to bundle it successfully into an EXE for Windows. The problem is, the application requires a .cfg file that always sits directly beside the application in the same directory.
Normally, I build the path using the following code:
import os
config_name = 'myapp.cfg'
config_path = os.path.join(sys.path[0], config_name)
However, it seems the sys.path is blank when its called from an EXE generated by pyInstaller. This same behaviour occurs when you run the python interactive command line and try to fetch sys.path[0].
Is there a more concrete way of getting the path of the currently running application so that I can find files that are relative to it?
|
I found a solution. You need to check if the application is running as a script or as a frozen exe:
import os
import sys
config_name = 'myapp.cfg'
# determine if application is a script file or frozen exe
if getattr(sys, 'frozen', False):
application_path = os.path.dirname(sys.executable)
elif __file__:
application_path = os.path.dirname(__file__)
config_path = os.path.join(application_path, config_name)
|
LBYL vs EAFP in Java?
|
I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language.
LBYL (Look Before You Leap):
def safe_divide_1(x, y):
if y == 0:
print "Divide-by-0 attempt detected"
return None
else:
return x/y
EAFP (it's Easier to Ask Forgiveness than Permission):
def safe_divide_2(x, y):
try:
return x/y
except ZeroDivisionError:
print "Divide-by-0 attempt detected"
return None
My question is this: I had never even heard of using EAFP as the primary data validation construct, coming from a Java and C++ background. Is EAFP something that is wise to use in Java? Or is there too much overhead from exceptions? I know that there is only overhead when an exception is actually thrown, so I'm unsure as to why the simpler method of EAFP is not used. Is it just preference?
|
If you are accessing files, EAFP is more reliable than LBYL, because the operations involved in LBYL are not atomic, and the file system might change between the time you look and the time you leap. Actually, the standard name is TOCTOU - Time of Check, Time of Use; bugs caused by inaccurate checking are TOCTOU bugs.
Consider creating a temporary file that must have a unique name. The best way to find out whether the chosen file name exists yet is to try creating it - making sure you use options to ensure that your operation fails if the file does already exist (in POSIX/Unix terms, the O_EXCL flag to open()). If you try to test whether the file already exists (probably using access()), then between the time when that says "No" and the time you try to create the file, someone or something else may have created the file.
Conversely, suppose that you try to read an existing file. Your check that the file exists (LBYL) may say "it is there", but when you actually open it, you find "it is not there".
In both these cases, you have to check the final operation - and the LBYL didn't automatically help.
(If you are messing with SUID or SGID programs, access() asks a different question; it may be relevant to LBYL, but the code still has to take into account the possibility of failure.)
|
Line reading chokes on 0x1A
|
I have the following file:
abcde
kwakwa
<0x1A>
line3
linllll
Where <0x1A> represents a byte with the hex value of 0x1A. When attempting to read this file in Python as:
for line in open('t.txt'):
print line,
It only reads the first two lines, and exits the loop.
The solution seems to be to open the file in binary (or universal newline mode) - 'rb' or 'rU'. Can you explain this behavior ?
|
0x1A is Ctrl-Z, and DOS historically used that as an end-of-file marker. For example, try using a command prompt, and "type"ing your file. It will only display the content up the Ctrl-Z.
Python uses the Windows CRT function _wfopen, which implements the "Ctrl-Z is EOF" semantics.
|
Please advise on Ruby vs Python, for someone who likes LISP a lot
|
I am a C++ developer, slowly getting into web development. I like LISP a lot but don't like AllegroCL and web-frameworks available for LISP. I am looking for more freedom and ability to do cool hacks on language level. I don't consider tabs as a crime against nature.
Which one is closer to LISP: Python or Ruby?
I can't seem to be able to choose from Python and Ruby: they seem very similar but apparently Ruby is more functional and object-oriented, which are good things, while Python is more like Perl: a simple scripting language. Do I have the right impression?
PS - This might seem like a flame bait but it's not really, I'm just trying not to go crazy from OCD about switching from RoR to Python/Django and back.
|
Peter Norvig, a famous and great lisper, converted to Python. He wrote the article Python for Lisp Programmers, which you might find interesting with its detailed comparison of features.
Python looks like executable pseudo-code. It's easy to pick up, and often using your intuition will just work. Python allows you to easily put your ideas into code.
Now, for web development, Python might seem like a more scattered option than Ruby, with the plethora of Python web frameworks available. Still, in general, Python is a very nice and useful language to know. As Ruby and Python's niches overlap, I agree with Kiv that it is partly a matter of personal taste which one you pick.
|
Mysql connection pooling question: is it worth it?
|
I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using a library that provides connection pooling (SQLAlchemy) won't actually help you that much if you enable the connection pool.
Does anyone have any experience with this?
I'm leery of enabling it because of the possibility that if some code does something stateful to a db connection and (perhaps mistakenly) doesn't clean up after itself, that state which would normally get cleaned up upon closing the connection will instead get propagated to subsequent code that gets a recycled connection.
|
There's no need to worry about residual state on a connection when using SQLA's connection pool, unless your application is changing connectionwide options like transaction isolation levels (which generally is not the case). SQLA's connection pool issues a connection.rollback() on the connection when its checked back in, so that any transactional state or locks are cleared.
It is possible that MySQL's connection time is pretty fast, especially if you're connecting over unix sockets on the same machine. If you do use a connection pool, you also want to ensure that connections are recycled after some period of time as MySQL's client library will shut down connections that are idle for more than 8 hours automatically (in SQLAlchemy this is the pool_recycle option).
You can quickly do some benching of connection pool vs. non with a SQLA application by changing the pool implementation from the default of QueuePool to NullPool, which is a pool implementation that doesn't actually pool anything - it connects and disconnects for real when the proxied connection is acquired and later closed.
|
Python update object from dictionary
|
Is there a built-in function/operator I could use to unpack values from a dictionary and assign it into instance variables?
This is what I intend to do:
c = MyClass()
c.foo = 123
c.bar = 123
# c.foo == 123 and c.bar == 123
d = {'bar': 456}
c.update(d)
# c.foo == 123 and c.bar == 456
Something akin to dictionary update() which load values from another dictionary but for plain object/class instance?
|
there is also another way of doing it by looping through the items in d. this doesn't have the same assuption that they will get stored in c.__dict__ which isn't always true.
d = {'bar': 456}
for key,value in d.items():
setattr(c,key,value)
or you could write a update method as part of MyClass so that c.update(d) works like you expected it to.
def update(self,newdata):
for key,value in newdata:
setattr(self,key,value)
check out the help for setattr
setattr(...)
setattr(object, name, value)
Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
''x.y = v''.
|
if all in list == something
|
Using python 2.6
is there a way to check if all the items of a sequence equals a given value, in one statement?
[pseudocode]
my_sequence = (2,5,7,82,35)
if all the values in (type(i) for i in my_sequence) == int:
do()
instead of, say:
my_sequence = (2,5,7,82,35)
all_int = True
for i in my_sequence:
if type(i) is not int:
all_int = False
break
if all_int:
do()
|
Use:
all( type(i) is int for i in lst )
Example:
In [1]: lst = range(10)
In [2]: all( type(i) is int for i in lst )
Out[2]: True
In [3]: lst.append('steve')
In [4]: all( type(i) is int for i in lst )
Out[4]: False
[Edit]. Made cleaner as per comments.
|
What is a cyclic data structure good for?
|
I was just reading through "Learning Python" by Mark Lutz and came across this code sample:
>>> L = ['grail']
>>> L.append(L)
>>> L
['grail', [...]]
It was identified as a cyclic data structure.
So I was wondering, and here is my question:
What is a 'cyclic data structure' used for in real life programming?
There seems to be a little confusion, which i think stems from the very brief code sample... here's a few more lines using the same object L
>>> L[0]
'grail'
>>> L[1][0]
'grail'
>>> L[1][1][0]
'grail'
|
Lots of things. Circular buffer, for example: you have some collection of data with a front and a back, but an arbitrary number of nodes, and the "next" item from the last should take you back to the first.
Graph structures are often cyclic; acyclicity is a special case. Consider, for example, a graph containing all the cities and roads in a traveling salesman problem.
Okay, here's a particular example for you. I set up a collection of towns here in Colorado:
V=["Boulder", "Denver", "Colorado Springs", "Pueblo", "Limon"]
I then set up pairs of cities where there is a road connecting them.
E=[["Boulder", "Denver"],
["Denver", "Colorado Springs"],
["Colorado Springs", "Pueblo"],
["Denver", "Limon"],
["Colorado Springs", "Limon"]]
This has a bunch of cycles. For example, you can drive from Colorado Springs, to Limon, to Denver, and back to Colorado Springs.
If you create a data structure that contains all the cities in V and all the roads in E, that's a graph data structure. This graph would have cycles.
|
Function and class documentation best practices for Python
|
I am looking for best practices for function/class/module documentation, i.e. comments in the code itself. Ideally I would like a comment template which is both human readable and consumable by Python documentation utilities.
I have read the Python documentation on docstrings.
I understand this part:
The first line should always be a short, concise summary of the objectâs purpose. For brevity, it should not explicitly state the objectâs name or type, since these are available by other means (except if the name happens to be a verb describing a functionâs operation). This line should begin with a capital letter and end with a period.
If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.
This sentence needs a bit more explanation:
The following lines should be one or more paragraphs describing the objectâs calling conventions, its side effects, etc.
Specifically, I am looking for examples of well-commented functions and classes.
|
You should use reStructuredText and check out the Sphinx markup constructs. All the cool kids are doing it.
You should follow docstring conventions. i.e.
It prescribes the function or method's
effect as a command ("Do this",
"Return that").
You should avoid repeating yourself unnecessarily or explaining the eminently obvious. Example of what not to do:
def do_things(verbose=False):
"""Do some things.
:param verbose: Be verbose (give additional messages).
"""
raise NotImplementedError
If you wanted to describe something non-obvious it would be a different story; for example, that verbose causes messages to occur on stdout or a logging stream. This is not specific to Python, but follows from more hand-wavy ideals such as self-documenting code and code/documentation DRY.
Try to avoid mentioning specific types if possible (abstract or interface-like types are generally okay). Mentioning protocols is typically more helpful from a duck typing perspective (i.e. "iterable" instead of set, or "mutable ordered sequence" instead of list). I've seen some code that is very literal and heavy WRT the :rtype: and the :type param: function-level documentation, which I've found to be at odds with the duck typing mentality.
|
Passing arguments with wildcards to a Python script
|
I want to do something like this:
c:\data\> python myscript.py *.csv
and pass all of the .csv files in the directory to my python script (such that sys.argv contains ["file1.csv", "file2.csv"], etc.)
But sys.argv just receives ["*.csv"] indicating that the wildcard was not expanded, so this doesn't work.
I feel like there is a simple way to do this, but can't find it on Google. Any ideas?
|
You can use the glob module, that way you won't depend on the behavior of a particular shell (well, you still depend on the shell not expanding the arguments, but at least you can get this to happen in Unix by escaping the wildcards :-) ).
from glob import glob
filelist = glob('*.csv') #You can pass the sys.argv argument
|
Python: Set Bits Count (popcount)
|
Few blob's have been duplicated in my database(oracle 11g), performed XOR operations on the blob using UTL_RAW.BIT_XOR. After that i wanted to count the number of set bits in the binary string, so wrote the code above.
During a small experiment, i wanted to see what is the hex and the integer value produced and wrote this procedure..
SQL> declare
2
3 vblob1 blob;
4
5 BEGIN
6
7 select leftiriscode INTO vblob1 FROM irisdata WHERE irisid=1;
8
9 dbms_output.put_line(rawtohex(vblob1));
10
11
12 dbms_output.put_line(UTL_RAW.CAST_TO_binary_integer(vblob1));
13
14
15 END;
16 /
OUTPUT: HEXVALUE:
0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B
INTEGER VALUE: 15
There was a variance between the hex code and the integer value produced, so used the following python code to check the actual integer value.
print int("0F0008020003030D030C1D1C3C383C330A3311373724764C54496C0A6B029B84840547A341BBA83D
BB5FB9DE4CDE5EFE96E1FC6169438344D604681D409F9F9F3BC07EE0C4E0C033A23B37791F59F84F
F94E4F664E3072B0229DA09D9F0F1FC600C2E380D6988C198B39517D157E7D66FE675237673D3D28
3A016C01411003343C76740F710F0F4F8FE976E1E882C186D316A63C0C7D7D7D7D397F016101B043
0176C37E767C7E0C7D010C8302C2D3E4F2ACE42F8D3F3F367A46F54285434ABB61BDB53CBF6C7CC0
F4C1C3F349B3F7BEB30E4A0CFE1C85180DC338C2C1C6E7A5CE3104303178724CCC5F451F573F3B24
7F24052000202003291F130F1B0E070C0E0D0F0E0F0B0B07070F1E1B330F27073F3F272E2F2F6F7B
2F2E1F2E4F7EFF7EDF3EBF253F3D2F39BF3D7F7FFED72FF39FE7773DBE9DBFBB3FE7A76E777DF55C
5F5F7ADF7FBD7F6AFE7B7D1FBE7F7F7DD7F63FBFBF2D3B7F7F5F2F7F3D7F7D3B3F3B7FFF4D676F7F
5D9FAD7DD17F7F6F6F0B6F7F3F767F1779364737370F7D3F5F377F2F3D3F7F1F2FE7709FB7BCB77B
0B77CF1DF5BF1F7F3D3E4E7F197F571F7D7E3F7F7F7D7F6F4F75FF6F7ECE2FFF793EFFEDB7BDDD1F
FF3BCE3F7F3FBF3D6C7FFF7F7F4FAF7F6FFFFF8D7777BF3AE30FAEEEEBCF5FEEFEE75FFEACFFDF0F
DFFFF77FFF677F4FFF7F7F1B5F1F5F146F1F1E1B3B1F3F273303170F370E250B",16)
Answer:
611951595100708231079693644541095422704525056339295086455197024065285448917042457
942011979060274412229909425184116963447100932992139876977824261789243946528467423
887840013630358158845039770703659333212332565531927875442166643379024991542726916
563271158141698128396823655639931773363878078933197184072343959630467756337300811
165816534945075483141582643531294791665590339000206551162697220540050652439977992
246472159627917169957822698172925680112854091876671868161705785698942483896808137
210721991100755736178634253569843464062494863175653771387230991126430841565373390
924951878267929443498220727531299945275045612499928105876210478958806304156695438
684335624641395635997624911334453040399012259638042898470872203581555352191122920
004010193837249388365999010692555403377045768493630826307316376698443166439386014
145858084176544890282148970436631175577000673079418699845203671050174181808397880
048734270748095682582556024378558289251964544327507321930196203199459115159756564
507340111030285226951393012863778670390172056906403480159339130447254293412506482
027099835944315172972281427649277354815211185293109925602315480350955479477144523
387689192243720928249121486221114300503766209279369960344185651810101969585926336
07333771272398091
To get the set-bit count I have written the following code in C:
int bitsoncount(unsigned x)
{
unsigned int b=0;
if(x > 1)
b=1;
while(x &= (x - 1))
b++;
return b;
}
When I tried the same code in python it did not work. I am new to python through curiosity I'm experimenting, excuse me if am wrong.
def bitsoncount(x):
b=0;
if(x>1):
b=1;
while(x &= (x-1)):
I get an error at the last line, need some help in resolving this and implementing the logic in python :-)
I was interested in checking out the set bits version in python after what i have seen!
Thank You,
Chaitanya
Related question: Best algorithm to count the number of set bits in a 32-bit integer?
|
Python 2.6 or 3.0:
def bitsoncount(x):
return bin(x).count('1')
Example:
>>> x = 123
>>> bin(x)
'0b1111011'
>>> bitsoncount(x)
6
Or
Matt Howells's answer in Python:
def bitsoncount(i):
assert 0 <= i < 0x100000000
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
|
A generic priority queue for Python
|
I need to use a priority queue in my Python code. Looking around for something efficient, I came upon heapq. It looks good, but seems to be specified only for integers. I suppose it works with any objects that have comparison operators, but it doesn't specify what comparison operators it needs.
Besides, heapq seems to be implemented in Python, so it's not fast.
Are you aware of any fast implementations for priority queues in Python ? Optimally, I'd like the queue to be generic (i.e. work well for any object with a specified comparison operator).
Thanks in advance
Update:
Re comparison in heapq, I can either use a (priority, object) as Charlie Martin suggests, or just implement __cmp__ for my object.
I'm still looking for something faster than heapq.
|
Um, Queue.PriorityQueue ? Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of (priority,thing) and you're set.
|
How to produce a 303 Http Response in Django?
|
Last couple of days we were discussing at another question the best to manage randomness in a RESTful way; today I went to play a little bit with some ideas in Django only to find that there is no easy standard way of returning a 303 response (nor a 300 one, btw), that is, there doesn't seem to exist an HttpResponseSeeOther inside django.HTTP or in another place.
Do you know any means for achieving this?
|
You could just override HttpResponse, like the other Responses do:
class HttpResponseSeeOther(HttpResponseRedirect):
status_code = 303
return HttpResponseSeeOther('/other-url/')
|
Python human readable object serialization
|
i need to store Python structures made of lists / dictionaries, tuples into a human readable format. The idea is like using something similar to pickle, but pickle is not human-friendly. Other options that come to my mind are YAML (through PyYAML and JSON (through simplejson) serializers.
Any other option that comes to your mind?
Thanks in advance.
|
If its just Python list, dictionary and tuple object. - JSON is the way to go. Its human readable, very easy to handle and language independent too.
Caution: Tuples will be converted to lists in simplejson.
In [109]: simplejson.loads(simplejson.dumps({'d':(12,3,4,4,5)}))
Out[109]: {u'd': [12, 3, 4, 4, 5]}
|
Sorting and Grouping Nested Lists in Python
|
I have the following data structure (a list of lists)
[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
I would like to be able to
Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together)
Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename'
so the list would look like this
[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
|
For the first question, the first thing you should do is sort the list by the second field:
x = [
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
from operator import itemgetter
x.sort(key=itemgetter(1))
Then you can use itertools' groupby function:
from itertools import groupby
y = groupby(x, itemgetter(1))
Now y is an iterator containing tuples of (element, item iterator). It's more confusing to explain these tuples than it is to show code:
for elt, items in groupby(x, itemgetter(1)):
print(elt, items)
for i in items:
print(i)
Which prints:
21 <itertools._grouper object at 0x511a0>
['4', '21', '1', '14', '2008-10-24 15:42:58']
['5', '21', '3', '19', '2008-10-24 15:45:45']
['6', '21', '1', '1somename', '2008-10-24 15:45:49']
22 <itertools._grouper object at 0x51170>
['3', '22', '4', '2somename', '2008-10-24 15:22:03']
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
For the second part, you should use list comprehensions as mentioned already here:
from pprint import pprint as pp
pp([y for y in x if y[3] == '2somename'])
Which prints:
[['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']]
|
Python: Alter elements of a list
|
I have a list of booleans where occasionally I reset them all to false. After first writing the reset as:
for b in bool_list:
b = False
I found it doesn't work. I spent a moment scratching my head, then remembered that of course it won't work since I'm only changing a reference to the bool, not its value. So I rewrote as:
for i in xrange(len(bool_list)):
bool_list[i] = False
and everything works fine. But I found myself asking, "Is that really the most pythonic way to alter all elements of a list?" Are there other ways that manage to be either more efficient or clearer?
|
If you only have one reference to the list, the following may be easier:
bool_list = [False] * len(bool_list)
This creates a new list populated with False elements.
See my answer to Python dictionary clear for a similar example.
|
socket.shutdown vs socket.close
|
I recently saw a bit of code that looked like this (with sock being a socket object of course):
sock.shutdown(socket.SHUT_RDWR)
sock.close()
What exactly is the purpose of calling shutdown on the socket and then closing it? If it makes a difference, this socket is being used for non-blocking IO.
|
Calling close and shutdown have two different effects on the underlying socket.
The first thing to point out is that the socket is a resource in the underlying OS and multiple processes can have a handle for the same underlying socket.
When you call close it decrements the handle count by one and if the handle count has reached zero then the socket and associated connection goes through the normal close procedure (effectively sending a FIN / EOF to the peer) and the socket is deallocated.
The thing to pay attention to here is that if the handle count does not reach zero because another process still has a handle to the socket then the connection is not closed and the socket is not deallocated.
On the other hand calling shutdown for reading and writing closes the underlying connection and sends a FIN / EOF to the peer regardless of how many processes have handles to the socket. However, it does not deallocate the socket and you still need to call close afterward.
|
How do you embed album art into an MP3 using Python?
|
I've been using mutagen for reading and writing MP3 tags, but I want to be able to embed album art directly into the file.
|
Here is how to add example.png as album cover into example.mp3 with mutagen:
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, error
audio = MP3('example.mp3', ID3=ID3)
# add ID3 tag if it doesn't exist
try:
audio.add_tags()
except error:
pass
audio.tags.add(
APIC(
encoding=3, # 3 is for utf-8
mime='image/png', # image/jpeg or image/png
type=3, # 3 is for the cover image
desc=u'Cover',
data=open('example.png').read()
)
)
audio.save()
|
For Python programmers, is there anything equivalent to Perl's CPAN?
|
I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modules as easy as CPAN. Also, a system that can handle dependencies automatically. I tried to install a module in Python by downloading a zip file from a website, unzipped it, then do:
sudo python setup.py install
but it's looking for another module. Now, lazy as I am, I don't like chasing dependencies and such, is there an easy way?
|
sammy, have a look at pip, which will let you do "pip install foo", and will download and install its dependencies (as long as they're on PyPI). There's also EasyInstall, but pip is intended to replace that.
|
Natural/Relative days in Python
|
I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.
Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.
Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something.
|
Twitter dates in specific are interesting because they are relative only for the first day. After 24 hours they just show the month and day. After a year they start showing the last two digits of the year. Here's a sample function that does something more akin to Twitter relative dates, though it always shows the year too after 24 hours. It's US locale only, but you can always alter it as needed.
# tested in Python 2.7
import datetime
def prettydate(d):
diff = datetime.datetime.utcnow() - d
s = diff.seconds
if diff.days > 7 or diff.days < 0:
return d.strftime('%d %b %y')
elif diff.days == 1:
return '1 day ago'
elif diff.days > 1:
return '{} days ago'.format(diff.days)
elif s <= 1:
return 'just now'
elif s < 60:
return '{} seconds ago'.format(s)
elif s < 120:
return '1 minute ago'
elif s < 3600:
return '{} minutes ago'.format(s/60)
elif s < 7200:
return '1 hour ago'
else:
return '{} hours ago'.format(s/3600)
|
Using AD as authentication for Django
|
I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities.
Does anyone have a good example of this?
|
Here's another more recent snippet (July 2008):
Authentication Against Active Directory (LDAP) over SSL
|
what's the 5 character alphanumeric id in reddit URL?
|
Whats the 7n5lu in the reddit URL
http://www.reddit.com/r/reddit.com/comments/7n5lu/man_can_fly_if_you_watch_one_video_in_2
how is it generated?
update:
@Gerald, Thanks for the code. I initially thought this is some obfuscation of the id.
But, it is just doing the conversion from integer to a more compact representation. I am thinking, why is this being done? why not use the original integer itself!!
>>> to36(4000)
'334'
>>> to36(4001)
'335'
|
The reddit source code is available! Here is what I found for generating that string:
def to_base(q, alphabet):
if q < 0: raise ValueError, "must supply a positive integer"
l = len(alphabet)
converted = []
while q != 0:
q, r = divmod(q, l)
converted.insert(0, alphabet[r])
return "".join(converted) or '0'
def to36(q):
return to_base(q, '0123456789abcdefghijklmnopqrstuvwxyz')
and elsewhere, under the "Link" class:
@property
def _id36(self):
return to36(self._id)
|
How do I parse XML from a Google app engine app?
|
How do I parse XML from a Google app engine app? Any examples?
|
Since the question was asked, Google has whitelisted pyexpat, which includes minidom, so you can use the following code without having to upload any libraries:
from xml.dom import minidom
dom = minidom.parseString('<eg>example text</eg>')
More information:
http://docs.python.org/library/xml.dom.minidom.html
|
Variable number of inputs with Django forms possible?
|
Is it possible to have a variable number of fields using django forms?
The specific application is this:
A user can upload as many pictures as they want on the image upload form. Once the pictures are uploaded they are taken to a page where they can give the pictures a name and description. The number of pictures will depend on how many the user has chosen to upload.
So how do I get django to generate a form using a variable number of input fields (which could be passed as an argument if necessary)?
edit: a few things have changed since the article mentioned in jeff bauer's answer was written.
Namely this line of code which doesn't seem to work:
# BAD CODE DO NOT USE!!!
return type('ContactForm', [forms.BaseForm], { 'base_fields': fields })
So here is what I came up with...
The Answer I used:
from tagging.forms import TagField
from django import forms
def make_tagPhotos_form(photoIdList):
"Expects a LIST of photo objects (ie. photo_sharing.models.photo)"
fields = {}
for id in photoIdList:
id = str(id)
fields[id+'_name'] = forms.CharField()
fields[id+'_tags'] = TagField()
fields[id+'_description'] = forms.CharField(widget=forms.Textarea)
return type('tagPhotos', (forms.BaseForm,), { 'base_fields': fields })
note tagging is not part of django, but it is free and very useful. check it out: django-tagging
|
Yes, it's possible to create forms dynamically in Django. You can even mix and match dynamic fields with normal fields.
class EligibilityForm(forms.Form):
def __init__(self, *args, **kwargs):
super(EligibilityForm, self).__init__(*args, **kwargs)
# dynamic fields here ...
self.fields['plan_id'] = CharField()
# normal fields here ...
date_requested = DateField()
For a better elaboration of this technique, see James Bennett's article: So you want a dynamic form?
http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/
|
How do I retrieve a Django model class dynamically?
|
Without having the full module path of a Django model, is it possible to do something like:
model = 'User' [in Django namespace]
model.objects.all()
...as opposed to:
User.objects.all().
EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g.,
model = django.authx.models.User
Without Django returning the error:
"global name django is not defined."
|
I think you're looking for this:
from django.db.models.loading import get_model
model = get_model('app_name', 'model_name')
There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.)
Update: According to Django's deprecation timeline, django.db.models.loading has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in Alasdair's answer, a new API for dynamically loading models was added to Django 1.7.
|
Is there a Python library than can simulate network traffic from different addresses
|
Is there a python library out there than can allow me to send UDP packets to a machine (sending to localhost is ok) from different source addresses and ports? I remember that one existed, but can't find it anymore.
|
You can spoof an IP address using Scapy library.
Here's an example from Packet Wizardry: Ruling the Network with Python:
#!/usr/bin/env python
import sys
from scapy import *
conf.verb=0
if len(sys.argv) != 4:
print "Usage: ./spoof.py <target> <spoofed_ip> <port>"
sys.exit(1)
target = sys.argv[1]
spoofed_ip = sys.argv[2]
port = int(sys.argv[3])
p1=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='S')
send(p1)
print "Okay, SYN sent. Enter the sniffed sequence number now: "
seq=sys.stdin.readline()
print "Okay, using sequence number " + seq
seq=int(seq[:-1])
p2=IP(dst=target,src=spoofed_ip)/TCP(dport=port,sport=5000,flags='A',
ack=seq+1,seq=1)
send(p2)
print "Okay, final ACK sent. Check netstat on your target :-)"
|
Django serialize to JSON
|
I have a Django model (schedule) with the class of entity, that is the parent of Activity, that is the parent of Event.
class Entity(models.Model):
<...>
class Activity(models.Model):
<...>
team_entity = models.ForeignKey(Entity)
<...>
class Event(models.Model):
<...>
activity = models.ForeignKey(Activity)
<...>
How do I serialize and get both the child object and grand children as part of the JSON file?
|
Before you do serialization, when retrieving your objects, to preserve the relationships use select_related() to get children, grandchildren, etc
see http://docs.djangoproject.com/en/dev/ref/models/querysets/
|
Add class to Django label_tag() output
|
I need some way to add a class attribute to the output of the label_tag() method for a forms field.
I see that there is the ability to pass in an attrs dictionary and I have tested it in the shell and I can do something like:
for field in form:
print field.label_tag(attrs{'class':'Foo'})
I will see the class='Foo' in my output, but I don't see a way to add an attrs argument from the template - in fact, templates are designed specifically against that, no?
Is there a way in my form definition to define the class to be displayed in the label?
In the form, I can do the following to give the inputs a class
self.fields['some_field'].widget.attrs['class'] = 'Foo'
I just need to have it output the class for the as well.
|
How about adding the CSS class to the form field in the forms.py, like:
class MyForm(forms.Form):
title = forms.CharField(widget=forms.TextInput(attrs={'class': 'foo'}))
then I just do the following in the template:
<label for="id_{{form.title.name}}" class="bar">
{{ form.title }}
</label>
Of course this can easily be modified to work within a for loop tag in the template.
|
SQLAlchemy DateTime timezone
|
SQLAlchemy's DateTime type allows for a timezone=True argument to save a non-naive datetime object to the datbase, and to return it as such. Is there any way to modify the timezone of the tzinfo that SQLAlchemy passes in so it could be, for instance, UTC? I realize that I could just use default=datetime.datetime.utcnow; however, this is a naive time that would happily accept someone passing in a naive localtime-based datetime, even if I used timezone=True with it, because it makes local or UTC time non-naive without having a base timezone to normailze it with. I have tried (using pytz) to make the datetime object non-naive, but when I save this to the db it comes back as naive.
Note how datetime.datetime.utcnow does not work with timezone=True so well:
import sqlalchemy as sa
from sqlalchemy.sql import select
import datetime
metadata = sa.MetaData('postgres://user:pass@machine/db')
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.utcnow)
)
metadata.create_all()
engine = metadata.bind
conn = engine.connect()
result = conn.execute(data_table.insert().values(id=1))
s = select([data_table])
result = conn.execute(s)
row = result.fetchone()
(1, datetime.datetime(2009, 1, 6, 0, 9, 36, 891887))
row[1].utcoffset()
datetime.timedelta(-1, 64800) # that's my localtime offset!!
datetime.datetime.now(tz=pytz.timezone("US/Central"))
datetime.timedelta(-1, 64800)
datetime.datetime.now(tz=pytz.timezone("UTC"))
datetime.timedelta(0) #UTC
Even if I change it to explicitly use UTC:
...
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset()
...
datetime.timedelta(-1, 64800) # it did not use the timezone I explicitly added
Or if I drop the timezone=True:
...
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset() is None
...
True # it didn't even save a timezone to the db this time
|
http://www.postgresql.org/docs/8.3/interactive/datatype-datetime.html#DATATYPE-TIMEZONES
All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the timezone configuration parameter before being displayed to the client.
The only way to store it with postgresql is to store it separately.
|
How to get current time in Python
|
What is the module/method used to get current time?
|
>>> import datetime
>>> datetime.datetime.now()
datetime(2009, 1, 6, 15, 8, 24, 78915)
And just the time:
>>> datetime.datetime.time(datetime.datetime.now())
datetime.time(15, 8, 24, 78915)
The same but slightly more compact:
>>> datetime.datetime.now().time()
See the documentation for more info.
To save typing, you can import the datetime object from the datetime module:
>>> from datetime import datetime
Then remove the leading datetime. from all the above.
|
Why does Python's string.printable contains unprintable characters?
|
I have two String.printable mysteries in the one question.
First, in Python 2.6:
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
Look at the end of the string, and you'll find '\x0b\x0c' sticking out like a sore-thumb. Why are they there? I am using a machine set to Australian settings, so there shouldn't be any accented characters or the like.
Next, try running this code:
for x in string.printable: print x,
print
for x in string.printable: print x
The first line successfully prints all the characters separated by a space. The two odd characters turn out as the Male and Female symbols.
The second line successfully prints all the characters EXCEPT THE LAST separated by a line feed. The Male symbol prints; the female symbol is replaced with a missing character (a box).
I'm sure Python wasn't intended to be gender-biased, so what gives with the difference?
|
There is a difference in "printable" for "can be displayed on your screen". Your terminal displays the low ascii printer control codes 0x0B and 0x0C as the male and female symbols because that is what those indices in your font contain. Those characters are more accurately described as the Vertical Tabulator and Form Feed characters. These two characters, along with \t \r and \n, are all printable, and do well defined things on a printer.
|
How to convert XML to objects?
|
I need to load an XML file and put the contents into an object-oriented structure. I want to take this:
<main>
<object1 attr="name">content</object>
</main>
and turn it into something like this:
main
main.object1 = "content"
main.object1.attr = "name"
It'll have a more complicated structure than that and I can't hard code the element names. The names need to be collected when parsing and used as the object properties.
Any thoughts on what would be the best way to go about this?
|
It's worth to have a look at http://lxml.de/objectify.html
>>> xml = """<main>
... <object1 attr="name">content</object1>
... <object1 attr="foo">contenbar</object1>
... <test>me</test>
... </main>"""
>>> from lxml import objectify
>>> main = objectify.fromstring(xml)
>>> main.object1[0]
'content'
>>> main.object1[1]
'contenbar'
>>> main.object1[0].get("attr")
'name'
>>> main.test
'me'
Or the other way around to build xml structures:
>>> item = objectify.Element("item")
>>> item.title = "Best of python"
>>> item.price = 17.98
>>> item.price.set("currency", "EUR")
>>> order = objectify.Element("order")
>>> order.append(item)
>>> order.item.quantity = 3
>>> order.price = sum(item.price * item.quantity
... for item in order.item)
>>> import lxml.etree
>>> print lxml.etree.tostring(order, pretty_print=True)
<order>
<item>
<title>Best of python</title>
<price currency="EUR">17.98</price>
<quantity>3</quantity>
</item>
<price>53.94</price>
</order>
|
Pythonic equivalent of unshift or redo?
|
I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.
For example, suppose I'm picking apples from a tree. My fruit basket can only hold 10kg before it needs to be emptied. But I have to pick each apple before I can weigh it and determine if this apple would exceed the capacity of the basket.
In a language like Perl, I could unshift() the apple back onto the tree, and then let the loop expression re-pick the apple:
while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
unshift(@tree, $apple);
} else {
push(@basket, $element);
}
}
Or else I can also use redo, which resumes processing at the top of block, without evaluating the loop expression. So the same apple can be re-processed, after the basket has been emptied.
while ($apple = shift(@tree)) {
$wt = weight($apple);
if ($wt + weight(@basket) > 10) {
send(@basket);
@basket = ();
redo;
} else {
push(@basket, $apple);
}
}
What would be the most pythonic solution for this kind of problem?
|
I'm learning Python, and I have a situation where I want to consume items from an iterator. The tricky part is that under certain conditions, I want to "un-iterate." That is, put an item back onto the front of the iterator before I loop.
Here's a simple solution:
class MyIterator(object): # undo-able iterator wrapper
def __init__(self, iterable):
super(MyIterator, self).__init__()
self.iterator = iter(iterable)
self.stack = []
def __iter__(self):
return self
def next(self):
if self.stack:
return self.stack.pop()
return self.iterator.next() # Raises StopIteration eventually
def undo(self, item):
self.stack.append(item)
for i in MyIterator(xrange(5)): print i
0
1
2
3
4
rng = MyIterator(xrange(5))
rng.next()
0
rng.next()
1
rng.undo(1)
rng.next()
1
|
What does `if __name__ == "__main__":` do?
|
What does the if __name__ == "__main__": do?
# Threading example
import time, thread
def myfunction(string, sleeptime, lock, *args):
while 1:
lock.acquire()
time.sleep(sleeptime)
lock.release()
time.sleep(sleeptime)
if __name__ == "__main__":
lock = thread.allocate_lock()
thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock))
thread.start_new_thread(myfunction, ("Thread #: 2", 2, lock))
|
When the Python interpreter reads a source file, it executes all of the code found in it.
Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name.
In the case of your script, let's assume that it's executing as the main function, e.g. you said something like
python threading_example.py
on the command line. After setting up the special variables, it will execute the import statement and load those modules. It will then evaluate the def block, creating a function object and creating a variable called myfunction that points to the function object. It will then read the if statement and see that __name__ does equal "__main__", so it will execute the block shown there.
One of the reasons for doing this is that sometimes you write a module (a .py file) where it can be executed directly. Alternatively, it can also be imported and used in another module. By doing the main check, you can have that code only execute when you want to run the module as a program and not have it execute when someone just wants to import your module and call your functions themselves.
See this page for some extra details.
|
Anyone know of a good Python based web crawler that I could use?
|
I'm half-tempted to write my own, but I don't really have enough time right now. I've seen the Wikipedia list of open source crawlers but I'd prefer something written in Python. I realize that I could probably just use one of the tools on the Wikipedia page and wrap it in Python. I might end up doing that - if anyone has any advice about any of those tools, I'm open to hearing about them. I've used Heritrix via its web interface and I found it to be quite cumbersome. I definitely won't be using a browser API for my upcoming project.
Thanks in advance. Also, this is my first SO question!
|
Mechanize is my favorite; great high-level browsing capabilities (super-simple form filling and submission).
Twill is a simple scripting language built on top of Mechanize
BeautifulSoup + urllib2 also works quite nicely.
Scrapy looks like an extremely promising project; it's new.
|
How would a system tray application be accomplished on other platforms?
|
Windows has the "system tray" that houses the clock and alway-running services like MSN, Steam, etc.
I'd like to develop a wxPython tray application but I'm wondering how well this will port to other platforms. What is the tray equivalent on each platform, and how much manual work would be required to support Windows, OSX and Linux (which shells in particular would be friendliest).
|
wx is a cross-platform GUI and tools library that supports Win32, Mac OS X, GTK+, X11, Motif, WinCE, and more. And if you use it's classes then your application should work on all these platforms.
For system tray look at wxTaskBarIcon (http://docs.wxwidgets.org/stable/wx_wxtaskbaricon.html#wxtaskbaricon).
|
Migrating from CPython to Jython
|
I'm considering moving my code (around 30K LOC) from CPython to Jython, so that I could have better integration with my java code.
Is there a checklist or a guide I should look at, to help my with the migration? Does anyone have experience with doing something similar?
From reading the Jython site, most of the problems seem too obscure to bother me.
I did notice that:
thread safety is an issue
Unicode support seems to be quite different, which may be a problem for me
mysqldb doesn't work and needs to be replaced with zxJDBC
Anything else?
Related question: What are some strategies to write python code that works in CPython, Jython and IronPython
|
First off, I have to say the Jython implementation is very good. Most things "just work".
Here are a few things that I have encountered:
C modules are not available, of course.
open('file').read() doesn't automatically close the file. This has to do with the difference in the garbage collector. This can cause issues with too many open files. It's better to use the "with open('file') as fp" idiom.
Setting the current working directory (using os.setcwd()) works for Python code, but not for Java code. It emulates the current working directory for everything file-related but can only do so for Jython.
XML parsing will try to validate an external DTD if it's available. This can cause massive slowdowns in XML handling code because the parser will download the DTD over the network. I reported this issue, but so far it remains unfixed.
The __ del __ method is invoked very late in Jython code, not immediately after the last reference to the object is deleted.
There is an old list of differences, but a recent list is not available.
|
How do I enable push-notification for IMAP (Gmail) using Python imaplib?
|
Is there a way to monitor a gmail account using imaplib without polling gmail each time I want to see if there is new mail. Or in other words, I just want the script to be notified of a new message so I can process it right away instead of any lag time between polls.
I see that the IMAP protocol supports this with the IDLE command, but I can't see anything documented with it in the imaplib docs, so any help with this would be great!
|
There isn't something in imaplib that does this, AFAIK (disclamer: I know very little about Python), however, it seems that someone has implemented an IDLE extension for Python which has the same interface as imaplib (which you can swap out with no changes to existing code, apparently):
http://www.cs.usyd.edu.au/~piers/python/imaplib.html
|
Python script to list users and groups
|
I'm attempting to code a script that outputs each user and their group on their own line like so:
user1 group1
user2 group1
user3 group2
...
user10 group6
etc.
I'm writing up a script in python for this but was wondering how SO might do this. Thanks!
p.s. Take a whack at it in any language but I'd prefer python.
EDIT: I'm working on Linux. Ubuntu 8.10 or CentOS =)
|
the grp module is your friend. Look at grp.getgrall() to get a list of all groups and their members.
EDIT example:
import grp
groups = grp.getgrall()
for group in groups:
for user in group[3]:
print user, group[0]
|
How to access the user profile in a Django template?
|
I'm storing some additional per-user information using the AUTH_PROFILE_MODULE.
We can access the user in a Django template using {{ request.user }} but how do we access fields in the profile since the profile is only accessible via a function user.get_profile() ?
Is it really required to explicitly pass the profile into the template every time?
|
Use {{ request.user.get_profile.whatever }}. Django's templating language automatically calls things that are callable - in this case, the .get_profile() method.
|
Using global variables in a function other than the one that created them
|
If I create a global variable in one function, how can I use that variable in another function?
Do I need to store the global variable in a local variable of the function which needs its access?
|
You can use a global variable in other functions by declaring it as global in each function that assigns to it:
globvar = 0
def set_globvar_to_one():
global globvar # Needed to modify global copy of globvar
globvar = 1
def print_globvar():
print globvar # No need for global declaration to read value of globvar
set_globvar_to_one()
print_globvar() # Prints 1
I imagine the reason for it is that, since global variables are so dangerous, Python wants to make sure that you really know that's what you're playing with by explicitly requiring the global keyword.
See other answers if you want to share a global variable across modules.
|
Python unittest with expensive setup
|
My test file is basically:
class Test(unittest.TestCase):
def testOk():
pass
if __name__ == "__main__":
expensiveSetup()
try:
unittest.main()
finally:
cleanUp()
However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in main. Looking at http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed.
How can I do the setup and cleanup once for all the tests in my TestSuite?
The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.
|
If you use Python >= 2.7 (or unittest2 for Python >= 2.4 & <= 2.6), the best approach would be be to use
def setUpClass(cls):
# ...
setUpClass = classmethod(setUpClass)
to perform some initialization once for all tests belonging to the given class.
And to perform the cleanup, use:
@classmethod
def tearDownClass(cls):
# ...
See also the unittest standard library documentation on setUpClass and tearDownClass classmethods.
|
Best Way To Determine if a Sequence is in another sequence in Python
|
This is a generalization of the "string contains substring" problem to (more) arbitrary types.
Given an sequence (such as a list or tuple), what's the best way of determining whether another sequence is inside it? As a bonus, it should return the index of the element where the subsequence starts:
Example usage (Sequence in Sequence):
>>> seq_in_seq([5,6], [4,'a',3,5,6])
3
>>> seq_in_seq([5,7], [4,'a',3,5,6])
-1 # or None, or whatever
So far, I just rely on brute force and it seems slow, ugly, and clumsy.
|
I second the Knuth-Morris-Pratt algorithm. By the way, your problem (and the KMP solution) is exactly recipe 5.13 in Python Cookbook 2nd edition. You can find the related code at http://code.activestate.com/recipes/117214/
It finds all the correct subsequences in a given sequence, and should be used as an iterator:
>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,6]): print s
3
>>> for s in KnuthMorrisPratt([4,'a',3,5,6], [5,7]): print s
(nothing)
|
Django on IronPython
|
I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success?
If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas?
|
Besides the Jeff Hardy blog post on Django + IronPython mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy_install and zlib. The first is Solving the zlib problem which discusses the absence of zlib for IronPython; hence, no easyinstall. Jeff reimplemented zlib based on ComponentAce's zlib.net. And finally, in easy_install on IronPython, Part Deux Jeff discusses some final tweaks that are needed before easy_install can be used with IronPython.
|
How do I mock the Python method OptionParser.error(), which does a sys.exit()?
|
I'm trying to unit test some code that looks like this:
def main():
parser = optparse.OptionParser(description='This tool is cool', prog='cool-tool')
parser.add_option('--foo', action='store', help='The foo option is self-explanatory')
options, arguments = parser.parse_args()
if not options.foo:
parser.error('--foo option is required')
print "Your foo is %s." % options.foo
return 0
if __name__ == '__main__':
sys.exit(main())
With code that looks like this:
@patch('optparse.OptionParser')
def test_main_with_missing_p4clientsdir_option(self, mock_optionparser):
#
# setup
#
optionparser_mock = Mock()
mock_optionparser.return_value = optionparser_mock
options_stub = Mock()
options_stub.foo = None
optionparser_mock.parse_args.return_value = (options_stub, sentinel.arguments)
def parser_error_mock(message):
self.assertEquals(message, '--foo option is required')
sys.exit(2)
optionparser_mock.error = parser_error_mock
#
# exercise & verify
#
self.assertEquals(sut.main(), 2)
I'm using Michael Foord's Mock, and nose to run the tests.
When I run the test, I get:
File "/Users/dspitzer/Programming/Python/test-optparse-error/tests/sut_tests.py", line 27, in parser_error_mock
sys.exit(2)
SystemExit: 2
----------------------------------------------------------------------
Ran 1 test in 0.012s
FAILED (errors=1)
The problem is that OptionParser.error does a sys.exit(2), and so main() naturally relies on that. But nose or unittest detects the (expected) sys.exit(2) and fails the test.
I can make the test pass by adding "return 2" under the parser.error() call in main() and removing the sys.exit() call from parser_error_mock(), but I find it distasteful to modify the code under test to allow a test to pass. Is there a better solution?
Update: df's answer works, although the correct call is "self.assertRaises(SystemExit, sut.main)".
Which means the test passes whatever the number is in the sys.exit() in parser_error_mock(). Is there any way to test for the exit code?
BTW, the test is more robust if I add:
self.assertEquals(optionparser_mock.method_calls, [('add_option', ('--foo',), {'action': 'store', 'help': 'The foo option is self-explanatory'}), ('parse_args', (), {})])
at the end.
Update 2: I can test for the exit code by replacing "self.assertRaises(SystemExit, sut.main)" with:
try:
sut.main()
except SystemExit, e:
self.assertEquals(type(e), type(SystemExit()))
self.assertEquals(e.code, 2)
except Exception, e:
self.fail('unexpected exception: %s' % e)
else:
self.fail('SystemExit exception expected')
|
Will this work instead of assertEquals?
self.assertRaises(SystemExit, sut.main, 2)
This should catch the SystemExit exception and prevent the script from terminating.
|
What is a "slug" in Django?
|
When I read Django code I often see in models what is called a "slug". I am not quite sure what this is, but I do know it has something to do with URLs. How and when is this slug-thing supposed to be used?
(I have read its definition in this glossary.)
|
It's a way of generating a valid URL, generally using data already obtained. For instance, using the title of an article to generate a URL. I'd advise to generate the slug, using a function, given a title (or other piece of data), rather than setting it manually.
An example:
<title> The 46 Year Old Virgin </title>
<content> A silly comedy movie </content>
<slug> the-46-year-old-virgin </slug>
Now let's pretend that we have a Django model such as:
class Article(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(max_length=1000)
slug = models.SlugField(max_length=40)
How would you reference this object with a URL, with a meaningful name? You could use Article.id so the URL would look like this:
www.example.com/article/23
Or, you could reference the title like so:
www.example.com/article/The 46 Year Old Virgin
Problem is, spaces aren't valid in URLs, they need to be replaced by %20 which is ugly, making it the following:
www.example.com/article/The%2046%20Year%20Old%20Virgin
That's not solving our meaningful URL. Wouldn't this be better:
www.example.com/article/the-46-year-old-virgin
That's a slug. the-46-year-old-virgin. All letters are downcased and spaces are replaced by hyphens -. See the URL of this very webpage for an example!
|
How can I get the source code of a Python function?
|
Suppose I have a Python function as defined below:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above?
|
If the function is from a source file available on the filesystem, then inspect.getsourcelines(foo) might be of help.
I believe that if the function is compiled from a string, stream or imported from a compiled file, then you cannot retrieve its source code.
|
How to split strings into text and number?
|
I'd like to split strings like these
'foofo21'
'bar432'
'foobar12345'
into
['foofo', '21']
['bar', '432']
['foobar', '12345']
Does somebody know an easy and simple way to do this in python?
|
I would approach this by using re.match in the following way:
match = re.match(r"([a-z]+)([0-9]+)", 'foofo21', re.I)
if match:
items = match.groups()
# items is ("foo", "21")
|
How can I programatically change the background in Mac OS X?
|
How would I go about programatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command?
|
From python, if you have appscript installed (sudo easy_install appscript), you can simply do
from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))
Otherwise, this applescript will change the desktop background
tell application "Finder"
set desktop picture to POSIX file "/your/filename.jpg"
end tell
You can run it from the command line using osascript, or from Python using something like
import subprocess
SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""
def set_desktop_background(filename):
subprocess.Popen(SCRIPT%filename, shell=True)
|
How do I "cd" in Python?
|
cd as in the shell command to change the working directory.
How do I change the current working directory in Python?
|
You can change the working directory with
os.chdir(path)
There are two best practices to follow when using this method:
Catch the exception (WindowsError, OSError) on invalid path. If the exception is thrown, do not perform any recursive operations, especially destructive ones. They will operate on the old path and not the new one.
Return to your old directory when you're done. This can be done in an exception-safe manner by wrapping your chdir call in a context manager, like Brian M. Hunt did in his answer.
Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use os.chdir() to change the CWD of the calling process.
|
Python csv.reader: How do I return to the top of the file?
|
When I'm moving through a file with a csv.reader, how do I return to the top of the file. If I were doing it with a normal file I could just do something like "file.seek(0)". Is there anything like that for the csv module?
Thanks ahead of time ;)
|
You can seek the file directly. For example:
>>> f = open("csv.txt")
>>> c = csv.reader(f)
>>> for row in c: print row
['1', '2', '3']
['4', '5', '6']
>>> f.seek(0)
>>> for row in c: print row # again
['1', '2', '3']
['4', '5', '6']
|
Ignore python multiple return value
|
Say I have a Python function that returns multiple values in a tuple:
def func():
return 1, 2
Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this:
x, temp = func()
|
You can use x = func()[0] to return the first value, x = func()[1] to return the second, and so on.
If you want to get multiple values at a time, use something like x, y = func()[2:4].
|
Is there a Numpy function to return the first index of something in an array?
|
I know there is a method for python list to return the first index of something
l = list(1,2,3)
l.index(2)
>>> 1
Is there something like that for numpy arrays?
|
Yes, here is the answer given a Numpy array, array, and a value, item, to search for.
itemindex = numpy.where(array==item)
The result is a tuple with first all the row indices, then all the column indices.
For example if array is two dimensions and it contained your item at two locations then
array[itemindex[0][0]][itemindex[1][0]]
would be equal to your item and so would
array[itemindex[0][1]][itemindex[1][1]]
numpy.where
|
SFTP in Python? (platform independent)
|
I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:
import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload a file by ftp to a site/directory
login hard-coded, binary transfer
"""
if verbose: print 'Uploading', file
local = open(file, 'rb')
remote = ftplib.FTP(site)
remote.login(*user)
remote.cwd(dir)
remote.storbinary('STOR ' + file, local, 1024)
remote.quit()
local.close()
if verbose: print 'Upload done.'
if __name__ == '__main__':
site = 'somewhere.com' #hard-coded
dir = './uploads/' #hard-coded
import sys, getpass
putfile(sys.argv[1], site, dir, user=info)
The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely?
Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.
import paramiko
host = "THEHOST.com" #hard-coded
port = 22
transport = paramiko.Transport((host, port))
password = "THEPASSWORD" #hard-coded
username = "THEUSERNAME" #hard-coded
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
import sys
path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded
localpath = sys.argv[1]
sftp.put(localpath, path)
sftp.close()
transport.close()
print 'Upload done.'
Thanks again!
|
Paramiko supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.
|
How can I assign a new class attribute via __dict__ in python?
|
I want to assign a class attribute via a string object - but how?
Example:
class test(object):
pass
a = test()
test.value = 5
a.value
# -> 5
test.__dict__['value']
# -> 5
# BUT:
attr_name = 'next_value'
test.__dict__[attr_name] = 10
# -> 'dictproxy' object does not support item assignment
|
There is a builtin function for this:
setattr(test, attr_name, 10)
Reference: http://docs.python.org/library/functions.html#setattr
Example:
>>> class a(object): pass
>>> a.__dict__['wut'] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'dictproxy' object does not support item assignment
>>> setattr(a, 'wut', 7)
>>> a.wut
7
|
How do you get the logical xor of two variables in Python?
|
How do you get the logical xor of two variables in Python?
For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
The ^ operator seems to be bitwise, and not defined on all objects:
>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'
|
If you're already normalizing the inputs to booleans, then != is xor.
bool(a) != bool(b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.