title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
Delete multiple files matching a pattern | 1,548,704 | 19 | 2009-10-10T18:32:43Z | 1,548,720 | 29 | 2009-10-10T18:38:01Z | [
"python"
] | I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.
When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them pe... | Try something like this:
```
import os, re
def purge(dir, pattern):
for f in os.listdir(dir):
if re.search(pattern, f):
os.remove(os.path.join(dir, f))
```
Then you would pass the directory containing the files and the pattern you wish to match. |
Delete multiple files matching a pattern | 1,548,704 | 19 | 2009-10-10T18:32:43Z | 1,548,788 | 7 | 2009-10-10T18:59:31Z | [
"python"
] | I have made an online gallery using Python and Django. I've just started to add editing functionality, starting with a rotation. I use sorl.thumbnail to auto-generate thumbnails on demand.
When I edit the original file, I need to clean up all the thumbnails so new ones are generated. There are three or four of them pe... | If you need recursion into several subdirectories, you can use this method:
```
import os, re, os.path
pattern = "^(?P<photo_id>\d+)[^\d].*jpg$"
mypath = "Photos"
for root, dirs, files in os.walk(mypath):
for file in filter(lambda x: re.match(pattern, x), files):
os.remove(os.path.join(root, file))
```
Yo... |
How to set an nonexistent field in Python ClientForm? | 1,548,996 | 5 | 2009-10-10T20:29:30Z | 1,549,036 | 14 | 2009-10-10T20:45:03Z | [
"python",
"mechanize",
"clientform"
] | I'm using mechanize (which uses clientform) for some web crawling in python and since it doesn't support JS, I want to set a value of an unexistent input in a form (the input is generated by JS). How can I do this?
The error is similar to the one you get if you try to execute
```
from mechanize import Browser
br = Br... | You need to first add the control to the form, and then `fixup` the form.
```
br.form.new_control('text','unexistent',{'value':''})
br.form.fixup()
br['unexistent'] = 'hello'
```
This really isn't very well documented, and in the source under `fixup()` there is the comment:
```
This method should only be called once... |
Sorting a heterogeneous list of objects in Python | 1,549,037 | 5 | 2009-10-10T20:45:18Z | 1,549,049 | 8 | 2009-10-10T20:51:57Z | [
"python",
"sorting"
] | I have some custom objects and dictionaries that I want to sort. I want to sort both the objects the dictionaries together. I want to sort the objects by an attribute and the dictionaries by a key.
```
object.name = 'Jack'
d = {'name':'Jill'}
sort_me =[object, d]
```
How do I sort this list using the object's name a... | What you are almost certainly looking for is to use the key= option for sorted(), which provides a function which returns an arbitrary sort key for each element. This function can check the type of its argument and take various actions. For instance:
```
import types
class obj(object):
def __init__(self, arg):
... |
Separately validating username and password during Django authentication | 1,549,442 | 5 | 2009-10-11T00:11:56Z | 1,549,582 | 19 | 2009-10-11T01:29:45Z | [
"python",
"django",
"security",
"authentication"
] | When using the standard authentication module in django, a failed user authentication is ambiguous. Namely, there seems to be no way of distinguishing between the following 2 scenarios:
* Username was valid, password was invalid
* Username was invalid
I am thinking that I would like to display the appropriate message... | You really don't want to distinguish between these two cases. Otherwise, you are giving a potential hacker a clue as to whether or not a username is valid - a significant help towards gaining a fraudulent login. |
How do do this list manipulation in Python? This is tricky | 1,549,445 | 2 | 2009-10-11T00:13:38Z | 1,549,455 | 10 | 2009-10-11T00:18:03Z | [
"python",
"list"
] | Suppose I have this list:
```
[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
```
What is the MOST efficient way to turn it into this list?
```
[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
```
Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.
I've tr... | ```
>>> L1 = [ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
>>> L2 = []
>>> map(L2.extend, zip(*L1))
>>> L2
[5, 7, 1, 44, 21, 32, 73, 99, 100]
``` |
How do do this list manipulation in Python? This is tricky | 1,549,445 | 2 | 2009-10-11T00:13:38Z | 1,549,482 | 8 | 2009-10-11T00:33:01Z | [
"python",
"list"
] | Suppose I have this list:
```
[ [5, 44, 73] , [7, 21, 99], [1, 32, 100] ]
```
What is the MOST efficient way to turn it into this list?
```
[ 5, 7, 1, 44, 21, 32, 73, 99, 100 ]
```
Notice, I grab the first from each. Then the 2nd element from each.
Of course, this function needs to be done with X elements.
I've tr... | ```
import itertools
list(itertools.chain(*zip(*L1)))
```
If you need lists of varying length:
```
import itertools
[x for x in itertools.chain(*itertools.izip_longest(*L1)) if x is not None]
``` |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | 19 | 2009-10-11T00:49:35Z | 1,549,549 | 20 | 2009-10-11T01:11:15Z | [
"python",
"list"
] | This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python>
```
biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Conc... | My answer to your other question, which you completely ignored!, shows you're wrong in claiming that
> The answers of that question did not
> keep the "order"
* my answer **did** keep order, and it clearly **said** it did. Here it is again, with added emphasis to see if you can just keep ignoring it...:
Probably the... |
Remove duplicates in a list while keeping its order (Python) | 1,549,509 | 19 | 2009-10-11T00:49:35Z | 25,560,184 | 11 | 2014-08-29T00:59:31Z | [
"python",
"list"
] | This is actually an extension of this question. The answers of that question did not keep the "order" of the list after removing duplicates. <http://stackoverflow.com/questions/1534736/how-to-remove-these-duplicates-in-a-list-python>
```
biglist =
[
{'title':'U2 Band','link':'u2.com'},
{'title':'Live Conc... | use set(), then re-sort using the index of the original list.
```
>>> mylist = ['c','a','a','b','a','b','c']
>>> sorted(set(mylist), key=lambda x: mylist.index(x))
['c', 'a', 'b']
``` |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | 267 | 2009-10-11T02:03:54Z | 1,549,644 | 436 | 2009-10-11T02:04:35Z | [
"python",
"capitalization",
"capitalize"
] | ```
s = 'the brown fox'
```
...do something here...
`s` should be :
```
'The Brown Fox'
```
What's the easiest way to do this? | The [`.title()`](http://docs.python.org/library/stdtypes.html#str.title) method of a string (either ASCII or Unicode is fine) does this:
```
>>> "hello world".title()
'Hello World'
>>> u"hello world".title()
u'Hello World'
```
However, look out for strings with embedded apostrophes, as noted in the docs.
> The algor... |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | 267 | 2009-10-11T02:03:54Z | 1,549,983 | 62 | 2009-10-11T06:04:11Z | [
"python",
"capitalization",
"capitalize"
] | ```
s = 'the brown fox'
```
...do something here...
`s` should be :
```
'The Brown Fox'
```
What's the easiest way to do this? | Just because this sort of thing is fun for me, here are two more solutions.
Split into words, initial-cap each word from the split groups, and rejoin. This will change the white space separating the words into a single white space, no matter what it was.
```
s = 'the brown fox'
lst = [word[0].upper() + word[1:] for w... |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | 267 | 2009-10-11T02:03:54Z | 10,013,565 | 10 | 2012-04-04T14:47:11Z | [
"python",
"capitalization",
"capitalize"
] | ```
s = 'the brown fox'
```
...do something here...
`s` should be :
```
'The Brown Fox'
```
What's the easiest way to do this? | Copy-paste-ready version of @jibberia anwser:
```
def capitalize(line):
return ' '.join(s[0].upper() + s[1:] for s in line.split(' '))
``` |
How to capitalize the first letter of each word in a string (Python)? | 1,549,641 | 267 | 2009-10-11T02:03:54Z | 12,336,911 | 90 | 2012-09-09T06:03:36Z | [
"python",
"capitalization",
"capitalize"
] | ```
s = 'the brown fox'
```
...do something here...
`s` should be :
```
'The Brown Fox'
```
What's the easiest way to do this? | the 'title' method can't work well,
```
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
```
Try string.capwords,
```
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
```
From the [python docs on capwords](https://docs.p... |
Difference between defining a member in __init__ to defining it in the class body in python? | 1,549,722 | 6 | 2009-10-11T03:00:40Z | 1,549,749 | 9 | 2009-10-11T03:15:07Z | [
"python",
"class",
"init"
] | What is the difference between doing
```
class a:
def __init__(self):
self.val=1
```
to doing
```
class a:
val=1
def __init__(self):
pass
``` | ```
class a:
def __init__(self):
self.val=1
```
this creates a class (in Py2, a cruddy, legacy, old-style, **don't do that!** class; in Py3, the nasty old legacy classes have finally gone away so this would be a class of the one and only kind -- the \**good* kind, which requires `class a(object):` in Py2) su... |
Differences between isinstance() and type() in python | 1,549,801 | 588 | 2009-10-11T03:50:54Z | 1,549,809 | 41 | 2009-10-11T03:54:17Z | [
"python",
"oop",
"inheritance",
"types"
] | What are the differences between these two code fragments? Which way is considered to be more pythonic?
Using `type()`:
```
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
```
Using `isinstance()`:
```
if isinstance(a, dict):
do_something()... | The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because `isinstance()`'s second parameter may be a tuple:
```
if isinstance(b, (str, unicode)):
do_something_else()
```
or, using the `basestring` abstract class:
```
if isinstance(b, basest... |
Differences between isinstance() and type() in python | 1,549,801 | 588 | 2009-10-11T03:50:54Z | 1,549,814 | 149 | 2009-10-11T03:58:54Z | [
"python",
"oop",
"inheritance",
"types"
] | What are the differences between these two code fragments? Which way is considered to be more pythonic?
Using `type()`:
```
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
```
Using `isinstance()`:
```
if isinstance(a, dict):
do_something()... | Here's why `isinstance` is better than `type`:
```
class Vehicle:
pass
class Truck(Vehicle):
pass
```
in this case, a truck object is a Vehicle, but you'll get this:
```
isinstance(Vehicle(), Vehicle) # returns True
type(Vehicle()) == Vehicle # returns True
isinstance(Truck(), Vehicle) # returns Tr... |
Differences between isinstance() and type() in python | 1,549,801 | 588 | 2009-10-11T03:50:54Z | 1,549,815 | 7 | 2009-10-11T03:59:14Z | [
"python",
"oop",
"inheritance",
"types"
] | What are the differences between these two code fragments? Which way is considered to be more pythonic?
Using `type()`:
```
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
```
Using `isinstance()`:
```
if isinstance(a, dict):
do_something()... | According to python documentation here is a statement:
> ### [8.15. types â Names for built-in types](http://docs.python.org/library/types.html)
>
> Starting in Python 2.2, built-in
> factory functions such as `int()` and
> `str()` are also names for the
> corresponding types.
So [`isinstance()`](http://docs.python... |
Differences between isinstance() and type() in python | 1,549,801 | 588 | 2009-10-11T03:50:54Z | 1,549,854 | 654 | 2009-10-11T04:31:57Z | [
"python",
"oop",
"inheritance",
"types"
] | What are the differences between these two code fragments? Which way is considered to be more pythonic?
Using `type()`:
```
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
```
Using `isinstance()`:
```
if isinstance(a, dict):
do_something()... | To summarize the contents of other (already good!) answers, `isinstance` caters for inheritance (an instance of a derived class *is an* instance of a base class, too), while checking for equality of `type` does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).
Normally, in Python, y... |
Differences between isinstance() and type() in python | 1,549,801 | 588 | 2009-10-11T03:50:54Z | 28,358,473 | 24 | 2015-02-06T04:13:45Z | [
"python",
"oop",
"inheritance",
"types"
] | What are the differences between these two code fragments? Which way is considered to be more pythonic?
Using `type()`:
```
import types
if type(a) is types.DictType:
do_something()
if type(b) in types.StringTypes:
do_something_else()
```
Using `isinstance()`:
```
if isinstance(a, dict):
do_something()... | > # Differences between `isinstance()` and `type()` in Python?
Type-checking with
```
isinstance(obj, Base)
```
allows for instances of subclasses and multiple possible bases:
```
isinstance(obj, (Base1, Base2))
```
whereas type-checking with
```
type(obj) == Base
```
only supports the type referenced.
## Usual... |
"Cloning" row or column vectors | 1,550,130 | 55 | 2009-10-11T07:54:05Z | 1,550,137 | 25 | 2009-10-11T07:59:23Z | [
"python",
"matlab",
"numpy",
"octave",
"linear-algebra"
] | Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as
```
[1,2,3]
```
Into a matrix
```
[[1,2,3]
[1,2,3]
[1,2,3]
]
```
or a column vector such as
```
[1
2
3
]
```
into
```
[[1,1,1]
[2,2,2]
[3,3,3]
]
```
In matlab or octave this is done pret... | Here's an elegant, Pythonic way to do it:
```
>>> array([[1,2,3],]*3)
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
```
the problem with `[16]` seems to be that the transpose has no effect for an array. you're probabl... |
"Cloning" row or column vectors | 1,550,130 | 55 | 2009-10-11T07:54:05Z | 1,552,016 | 18 | 2009-10-11T22:56:20Z | [
"python",
"matlab",
"numpy",
"octave",
"linear-algebra"
] | Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as
```
[1,2,3]
```
Into a matrix
```
[[1,2,3]
[1,2,3]
[1,2,3]
]
```
or a column vector such as
```
[1
2
3
]
```
into
```
[[1,1,1]
[2,2,2]
[3,3,3]
]
```
In matlab or octave this is done pret... | First note that with numpy's *broadcasting* operations it's usually not necessary to duplicate rows and columns. See [this](http://www.scipy.org/EricsBroadcastingDoc) and [this](http://www.oreillynet.com/pub/a/python/2000/09/27/numerically.html?page=1) for descriptions.
But to do this, [**repeat**](http://docs.scipy.o... |
"Cloning" row or column vectors | 1,550,130 | 55 | 2009-10-11T07:54:05Z | 1,582,742 | 130 | 2009-10-17T17:33:21Z | [
"python",
"matlab",
"numpy",
"octave",
"linear-algebra"
] | Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as
```
[1,2,3]
```
Into a matrix
```
[[1,2,3]
[1,2,3]
[1,2,3]
]
```
or a column vector such as
```
[1
2
3
]
```
into
```
[[1,1,1]
[2,2,2]
[3,3,3]
]
```
In matlab or octave this is done pret... | Use `numpy.tile`:
```
>>> tile(array([1,2,3]), (3, 1))
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
```
or for repeating columns:
```
>>> tile(array([[1,2,3]]).transpose(), (1, 3))
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
``` |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | 7 | 2009-10-11T07:57:29Z | 1,550,148 | 8 | 2009-10-11T08:03:25Z | [
"python"
] | ```
def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
```
This works:
```
if isBig(y): return isBig(y)
```
This does NOT work:
```
if fruit = isBig(y): return fruit
```
Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.
*How to make ... | The one liner doesn't work because, in Python, assignment (`fruit = isBig(y)`) is a statement, not an expression. In C, C++, Perl, and countless other languages it is an expression, and you can put it in an `if` or a `while` or whatever you like, but not in Python, because the creators of Python thought that this was t... |
How to assign a variable in IF, and then return it. (Python) | 1,550,134 | 7 | 2009-10-11T07:57:29Z | 1,551,223 | 14 | 2009-10-11T17:31:16Z | [
"python"
] | ```
def isBig(x):
if x > 4:
return 'apple'
else:
return 'orange'
```
This works:
```
if isBig(y): return isBig(y)
```
This does NOT work:
```
if fruit = isBig(y): return fruit
```
Why doesn't the 2nd one work!? I want a 1-liner. Except, the 1st one will call the function TWICE.
*How to make ... | I see somebody else has already pointed to my old "assign and set" Cookbook recipe, which boils down in its simplest version to:
```
class Holder(object):
def set(self, value):
self.value = value
return value
def get(self):
return self.value
h = Holder()
...
if h.set(isBig(y)): return h.get()
`... |
python setup.py uninstall | 1,550,226 | 489 | 2009-10-11T09:06:56Z | 1,550,235 | 621 | 2009-10-11T09:12:27Z | [
"python",
"setup.py",
"pypi"
] | I have installed a python package with `python setup.py install`.
How do I uninstall it? | You need to remove all files manually, and also undo any other stuff that installation did manually.
If you don't know the list of all files, you can reinstall it with the `--record` option, and take a look at the list this produces.
To record list of installed files, you can use:
```
python setup.py install --recor... |
python setup.py uninstall | 1,550,226 | 489 | 2009-10-11T09:06:56Z | 1,550,238 | 7 | 2009-10-11T09:13:42Z | [
"python",
"setup.py",
"pypi"
] | I have installed a python package with `python setup.py install`.
How do I uninstall it? | The lazy way: simply uninstall from the Windows installation menu (if you're using Windows), or from the rpm command, provided you first re-install it after creating a distribution package.
For example,
```
python setup.py bdist_wininst
dist/foo-1.0.win32.exe
```
("foo" being an example of course). |
python setup.py uninstall | 1,550,226 | 489 | 2009-10-11T09:06:56Z | 4,042,668 | 21 | 2010-10-28T12:00:21Z | [
"python",
"setup.py",
"pypi"
] | I have installed a python package with `python setup.py install`.
How do I uninstall it? | Or more simply you could just do;
```
sudo rm $(cat install.record)
```
This works because the rm command takes a whitespace-seperated list of files to delete and your installation record is just such a list. Also, using "less" for this type of command could get you in big trouble depending on the local configuration... |
python setup.py uninstall | 1,550,226 | 489 | 2009-10-11T09:06:56Z | 12,797,865 | 164 | 2012-10-09T10:19:27Z | [
"python",
"setup.py",
"pypi"
] | I have installed a python package with `python setup.py install`.
How do I uninstall it? | For me, the following mostly works:
have pip installed, e.g.:
```
$ easy_install pip
```
Check, how is your installed package named from pip point of view:
```
$ pip freeze
```
This shall list names of all packages, you have installed (and which were detected by pip).
The name can be sometime long, then use just t... |
python setup.py uninstall | 1,550,226 | 489 | 2009-10-11T09:06:56Z | 25,209,129 | 50 | 2014-08-08T17:34:59Z | [
"python",
"setup.py",
"pypi"
] | I have installed a python package with `python setup.py install`.
How do I uninstall it? | The #1 answer has problems:
* Won't work on mac.
* If a file is installed which includes spaces or other special
characters, the xargs command will fail, and delete any
files/directories which matched the individual words.
* the -r in rm -rf is unnecessary and at worst could delete things you
don't want to.
Ins... |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | 65 | 2009-10-11T11:27:38Z | 1,550,483 | 8 | 2009-10-11T11:28:56Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] | I discovered this pattern (or anti-pattern) and I am very happy with it.
I feel it is very agile:
```
def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
```
Sometimes I use its cousin:
```
def example2(obj):
print "The file at %(path)s has %(length)s byte... | I think it is a great pattern because you are leveraging built-in functionality to reduce the code you need to write. I personally find it quite Pythonic.
I never write code that I don't need to write - less code is better than more code and this practice of using `locals()` for example allows me to write less code an... |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | 65 | 2009-10-11T11:27:38Z | 1,550,527 | 8 | 2009-10-11T11:54:55Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] | I discovered this pattern (or anti-pattern) and I am very happy with it.
I feel it is very agile:
```
def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
```
Sometimes I use its cousin:
```
def example2(obj):
print "The file at %(path)s has %(length)s byte... | The `"%(name)s" % <dictionary>` or even better, the `"{name}".format(<parameters>)` have the merit of
* being more readable than "%0s"
* being independent from the argument order
* not compelling to use all the arguments in the string
I would tend to favour the str.format(), since it should be the way to do that in P... |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | 65 | 2009-10-11T11:27:38Z | 1,550,684 | 11 | 2009-10-11T13:22:53Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] | I discovered this pattern (or anti-pattern) and I am very happy with it.
I feel it is very agile:
```
def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
```
Sometimes I use its cousin:
```
def example2(obj):
print "The file at %(path)s has %(length)s byte... | Never in a million years. It's unclear what the context for formatting is: `locals` could include almost any variable. `self.__dict__` is not as vague. Perfectly awful to leave future developers scratching their heads over what's local and what's not local.
It's an intentional mystery. Why saddle your organization wit... |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | 65 | 2009-10-11T11:27:38Z | 1,551,187 | 80 | 2009-10-11T17:14:09Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] | I discovered this pattern (or anti-pattern) and I am very happy with it.
I feel it is very agile:
```
def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
```
Sometimes I use its cousin:
```
def example2(obj):
print "The file at %(path)s has %(length)s byte... | It's OK for small applications and allegedly "one-off" scripts, especially with the `vars` enhancement mentioned by @kaizer.se and the `.format` version mentioned by @RedGlyph.
However, for large applications with a long maintenance life and many maintainers this practice can lead to maintenance headaches, and I think... |
Python: is using "..%(var)s.." % locals() a good practice? | 1,550,479 | 65 | 2009-10-11T11:27:38Z | 6,106,580 | 8 | 2011-05-24T06:32:44Z | [
"python",
"string",
"design-patterns",
"anti-patterns"
] | I discovered this pattern (or anti-pattern) and I am very happy with it.
I feel it is very agile:
```
def example():
age = ...
name = ...
print "hello %(name)s you are %(age)s years old" % locals()
```
Sometimes I use its cousin:
```
def example2(obj):
print "The file at %(path)s has %(length)s byte... | Regarding the "cousin", instead of `obj.__dict__`, it looks a lot better with new string formatting:
```
def example2(obj):
print "The file at {o.path} has {o.length} bytes".format(o=obj)
```
I use this a lot for **repr** methods, e.g.
```
def __repr__(self):
return "{s.time}/{s.place}/{s.warning}".format(s=... |
Dynamically importing modules in Python3.0? | 1,551,063 | 2 | 2009-10-11T16:17:17Z | 1,551,073 | 7 | 2009-10-11T16:21:31Z | [
"python",
"import",
"python-3.x"
] | I want to dynamically import a list of modules. I'm having a problem doing this. Python always yells out an `ImportError` and tells me my module doesn't exist.
First I get the list of module filenames and chop off the `".py"` suffixes, like so:
```
viable_plugins = filter(is_plugin, os.listdir(plugin_dir))
viable_plu... | It says it can't do it, because even though you're changing your directory to where the modules are, that directory isn't on your import path.
What you need to do, instead of changing to the directory where the modules are located, is to insert that directory into `sys.path`.
```
import sys
sys.path.insert(0, directo... |
User-friendly time format in Python? | 1,551,382 | 49 | 2009-10-11T18:28:45Z | 1,551,394 | 93 | 2009-10-11T18:32:06Z | [
"python",
"datetime",
"date",
"time",
"formatting"
] | Python: I need to show file modification times in the "1 day ago", "two hours ago", format.
Is there something ready to do that? It should be in English. | [Yes, there is](http://evaisse.com/post/93417709/python-pretty-date-function "Python Pretty Date function"). Or, write your own and tailor it to your needs.
---
The function (as the blog author deleted it).
```
def pretty_date(time=False):
"""
Get a datetime object or a int() Epoch timestamp and return a
... |
User-friendly time format in Python? | 1,551,382 | 49 | 2009-10-11T18:28:45Z | 2,611,952 | 14 | 2010-04-10T02:03:36Z | [
"python",
"datetime",
"date",
"time",
"formatting"
] | Python: I need to show file modification times in the "1 day ago", "two hours ago", format.
Is there something ready to do that? It should be in English. | In looking for the same thing with the additional requirement that it handle future dates, I found this:
<http://pypi.python.org/pypi/py-pretty/1>
Example code (from site):
```
from datetime import datetime, timedelta
now = datetime.now()
hrago = now - timedelta(hours=1)
yesterday = now - timedelta(days=1)
tomorrow =... |
User-friendly time format in Python? | 1,551,382 | 49 | 2009-10-11T18:28:45Z | 9,969,729 | 27 | 2012-04-02T00:49:46Z | [
"python",
"datetime",
"date",
"time",
"formatting"
] | Python: I need to show file modification times in the "1 day ago", "two hours ago", format.
Is there something ready to do that? It should be in English. | If you happen to be using [Django](https://www.djangoproject.com/), then new in version 1.4 is the `naturaltime` template filter.
To use it, first add `'django.contrib.humanize'` to your `INSTALLED_APPS` setting in settings.py, and `{% load humanize %}` into the template you're using the filter in.
Then, in your temp... |
Using Python locale or equivalent in web applications? | 1,551,508 | 3 | 2009-10-11T19:20:00Z | 1,551,834 | 9 | 2009-10-11T21:31:34Z | [
"python",
"django",
"internationalization"
] | Python's locale implementation seems to want to either read the locale from system settings or have it be set via a setlocale call. Neither of these work for me since I'd like to use the capabilities in a web application, where the desired locale is the user's locale.
And there are warnings in the [locale docs](http:/... | `locale` is no good for any app that needs to support several locales -- it's really badly designed for those apps (basically any server-side app, including web apps). Where feasible, [PyICU](http://pyicu.osafoundation.org/) is a *vastly* superior solution -- top-quality i18n/L10n support, speed, flexibility (downside:... |
Rules of thumb for when to use operator overloading in python | 1,552,260 | 10 | 2009-10-12T01:00:03Z | 1,552,267 | 12 | 2009-10-12T01:04:38Z | [
"python",
"operator-overloading"
] | From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading `+` you probably also want to overload `++` and `+=`, and also make sure to handle end cases like adding an object to itself... | I've written software with significant amounts of overloading, and lately I regret that policy. I would say this:
**Only overload operators if it's the natural, expected thing to do and doesn't have any side effects.**
So if you make a new `RomanNumeral` class, it makes sense to overload addition and subtraction etc.... |
Rules of thumb for when to use operator overloading in python | 1,552,260 | 10 | 2009-10-12T01:00:03Z | 1,552,299 | 21 | 2009-10-12T01:23:07Z | [
"python",
"operator-overloading"
] | From what I remember from my C++ class, the professor said that operator overloading is cool, but since it takes relatively a lot of thought and code to cover all end-cases (e.g. when overloading `+` you probably also want to overload `++` and `+=`, and also make sure to handle end cases like adding an object to itself... | Operator overloading is mostly useful when you're making a new class that falls into an existing "Abstract Base Class" (ABC) -- indeed, many of the ABCs in standard library module [collections](http://docs.python.org/library/collections.html#module-collections) rely on the presence of certain special methods (and speci... |
Is there a cleaner way to chain empty list checks in Python? | 1,552,310 | 3 | 2009-10-12T01:28:33Z | 1,552,313 | 14 | 2009-10-12T01:30:17Z | [
"python",
"coding-style"
] | I have a fairly complex object (deserialized json, so I don't have too much control over it) that I need to check for the existence of and iterate over a fairly deep elements, so right now I have something like this:
```
if a.get("key") and a["key"][0] and a["key"][0][0] :
for b in a["key"][0][0] :
#Do som... | ```
try:
bs = a["key"][0][0]
# Note: the syntax for catching exceptions is different in old versions
# of Python. Use whichever one of these lines is appropriate to your version.
except KeyError, IndexError, TypeError: # Python 3
except (KeyError, IndexError, TypeError): # Python 2
bs = []
for b in bs:
```
And y... |
IPython tab completes only some modules | 1,552,961 | 4 | 2009-10-12T06:05:19Z | 3,631,259 | 10 | 2010-09-02T21:04:23Z | [
"python",
"module",
"ipython",
"tab-completion",
"enthought"
] | I'm using the EPD version of python and IPython. After installing some modules using easy\_install I notice that, although they can be imported, they cannot be tab completed. They exist on the path but, while included modules (pylab, readline, math) *can* be completed, these new modules cannot.
Anyone know what I shou... | I found an answer to this question yesterday, after I got tired of this behavior.
It seems that IPython has a simple database with all the modules it can find in `sys.path`. Every time you install a new module you have to write the magic
```
In [1]: %rehashx
```
so that IPython regenerates its database. Then you can... |
Python sqlite3 version | 1,553,160 | 19 | 2009-10-12T07:22:09Z | 1,553,190 | 47 | 2009-10-12T07:31:01Z | [
"python",
"sqlite"
] | ```
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite3
>>> sqlite3.version
'2.4.1'
```
Questions:
* Why is the version of the sqlite\*\*3\*\* module **'2.4.1'**
* Whats the reason behind bundli... | ```
Python 2.5.1
>>> import sqlite3
>>> sqlite3.version
'2.3.2'
>>> sqlite3.sqlite_version
'3.3.4'
```
version - pysqlite version
sqlite\_version - sqlite version |
multiple django sites with apache & mod_wsgi | 1,553,165 | 49 | 2009-10-12T07:22:51Z | 1,553,751 | 89 | 2009-10-12T10:13:05Z | [
"python",
"django",
"apache2",
"hosting",
"mod-wsgi"
] | I want to host several sites with under the same server which uses Debian 5, say I have `site1`, `site2` and `site3`, and assume my ip is `155.55.55.1`:
```
site1: 155.55.55.1:80 , script at /opt/django/site1/
site2: 155.55.55.1:8080, script at /opt/django/site2/
site3: 155.55.55.1:8090, script at /opt/django/site3/
... | Your ServerName/ServerAlias directives are wrong. ServerName should be hostname. You probably should just delete ServerAlias.
Then just do the obvious and duplicate VirtualHost/Listen directives, just changing the port number and locations of scripts in the file system.
Finally, do not set DocumentRoot to be where yo... |
How to upload html documentation generated from sphinx to github? | 1,553,800 | 15 | 2009-10-12T10:25:40Z | 1,622,472 | 30 | 2009-10-25T23:29:02Z | [
"python",
"github",
"python-sphinx"
] | I just documented loads of my code and learnt how to use sphinx to generate the documentation. I want to include that into my github project page but I do not know how to. Does anyone know existing tutorial or simple step to do so?
Thanks. | github will serve static content for you using their [github pages](http://github.com/blog/272-github-pages) feature. Essentially, you create a branch called gh-pages, into which you commit your static pages. The pages are then served at you.github.com/yourproject.
See the instructions at <http://pages.github.com/>.
... |
python: interact with the session in cgi scripts | 1,554,250 | 2 | 2009-10-12T12:21:38Z | 1,554,303 | 7 | 2009-10-12T12:28:43Z | [
"python",
"session",
"cgi"
] | Can python cgi scripts write and read data to the session? If so how? Is there a high-level API or must I roll my own classes? | There's no "*session*" on `cgi`. You must roll your own session handling code if you're using raw `cgi`.
Basically, sessions work by creating a unique cookie number and sending it on a response header to the client, and then checking for this cookie on every connection. Store the session data somewhere on the server (... |
When and how to use the builtin function property() in python | 1,554,546 | 52 | 2009-10-12T13:22:07Z | 1,554,617 | 26 | 2009-10-12T13:34:19Z | [
"python",
"properties"
] | It appears to me that except for a little syntactic sugar, property() does nothing good.
Sure, it's nice to be able to write `a.b=2` instead of `a.setB(2)`, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result can happen, such as `a.b=2` actual... | The idea is to allow you to avoid having to write getters and setters until you actually need them.
So, to start off you write:
```
class MyClass(object):
def __init__(self):
self.myval = 4
```
Obviously you can now write `myobj.myval = 5`.
But later on, you decide that you do need a setter, as you want... |
When and how to use the builtin function property() in python | 1,554,546 | 52 | 2009-10-12T13:22:07Z | 1,554,753 | 14 | 2009-10-12T14:01:05Z | [
"python",
"properties"
] | It appears to me that except for a little syntactic sugar, property() does nothing good.
Sure, it's nice to be able to write `a.b=2` instead of `a.setB(2)`, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result can happen, such as `a.b=2` actual... | > but hiding the fact that a.b=2 isn't a
> simple assignment looks like a recipe
> for trouble
You're not hiding that fact though; that fact was never there to begin with. This is python -- a high-level language; not assembly. Few of the "simple" statements in it boil down to single CPU instructions. To read simplicit... |
When and how to use the builtin function property() in python | 1,554,546 | 52 | 2009-10-12T13:22:07Z | 1,555,169 | 101 | 2009-10-12T15:16:54Z | [
"python",
"properties"
] | It appears to me that except for a little syntactic sugar, property() does nothing good.
Sure, it's nice to be able to write `a.b=2` instead of `a.setB(2)`, but hiding the fact that a.b=2 isn't a simple assignment looks like a recipe for trouble, either because some unexpected result can happen, such as `a.b=2` actual... | In languages that rely on getters and setters, like Java, they're not supposed nor expected to do anything but what they say -- it would be astonishing if `x.getB()` did anything but return the current value of logical attribute `b`, or if `x.setB(2)` did anything but whatever small amount of internal work is needed to... |
Implementing "Starts with" and "Ends with" queries with Google App Engine | 1,554,600 | 5 | 2009-10-12T13:30:22Z | 1,554,837 | 14 | 2009-10-12T14:13:27Z | [
"python",
"google-app-engine",
"gae-datastore"
] | Am wondering if anyone can provide some guidance on how I might implement a starts with or ends with query against a Datastore model using Python?
In pseudo code, it would work something like...
Query for all entities A where property P starts with X
or
Query for all entities B where property P ends with X
Thanks,... | You can do a 'starts with' query by using inequality filters:
```
MyModel.all().filter('prop >=', prefix).filter('prop <', prefix + u'\ufffd')
```
Doing an 'ends with' query would require storing the reverse of the string, then applying the same tactic as above. |
How to save a model without sending a signal? | 1,555,060 | 12 | 2009-10-12T14:56:46Z | 1,556,235 | 17 | 2009-10-12T18:46:43Z | [
"python",
"django",
"django-models"
] | How can I save a model, such that signals arent sent. (post\_save and pre\_save) | It's a bit of a hack, but you can do something like this:
use a unique identifier with a filter and then use the update method of the queryset (which does not trigger the signals)
```
user_id = 142187
User.objects.filter(id=user_id).update(name='tom')
``` |
Fill form values in a web page via a Python script (not testing) | 1,555,234 | 17 | 2009-10-12T15:28:41Z | 1,555,247 | 17 | 2009-10-12T15:31:59Z | [
"python"
] | I need to fill form values on a target page then click a button via Python. I've looked at Selenium and Windmill, but these are testing frameworks - I'm not testing. I'm trying to log into a 3rd party website programatically, then download and parse a file we need to insert into our database. The problem with the testi... | You are looking for [Mechanize](http://wwwsearch.sourceforge.net/mechanize/)
Form submitting sample:
```
import re
from mechanize import Browser
br = Browser()
br.open("http://www.example.com/")
br.select_form(name="order")
# Browser passes through unknown attributes (including methods)
# to the selected HTMLForm (f... |
Fill form values in a web page via a Python script (not testing) | 1,555,234 | 17 | 2009-10-12T15:28:41Z | 18,498,044 | 10 | 2013-08-28T20:57:46Z | [
"python"
] | I need to fill form values on a target page then click a button via Python. I've looked at Selenium and Windmill, but these are testing frameworks - I'm not testing. I'm trying to log into a 3rd party website programatically, then download and parse a file we need to insert into our database. The problem with the testi... | Have a look on this example: it will give the basic idea:
```
#!/usr/bin/python
import re
from mechanize import Browser
br = Browser()
# Ignore robots.txt
br.set_handle_robots( False )
# Google demands a user-agent that isn't a robot
br.addheaders = [('User-agent', 'Firefox')]
# Retrieve the Google home page, savin... |
sending a non-blocking HTTP POST request | 1,555,517 | 10 | 2009-10-12T16:22:37Z | 1,555,709 | 7 | 2009-10-12T16:55:03Z | [
"php",
"python",
"nonblocking"
] | I have a two websites in php and python.
When a user sends a request to the server I need php/python to send an HTTP POST request to a remote server. I want to reply to the user immediately without waiting for a response from the remote server.
Is it possible to continue running a php/python script after sending a res... | In PHP you can close the connection by sending this request (this is HTTP related and works also in python, although I don't know the proper syntax to use):
```
// Send the response to the client
header('Connection: Close');
// Do the background job: just don't output anything!
```
Addendum: I forgot to mention you p... |
Can one prevent Genshi from parsing HTML entities? | 1,555,644 | 3 | 2009-10-12T16:42:34Z | 1,555,869 | 9 | 2009-10-12T17:25:43Z | [
"python",
"html",
"entities",
"genshi"
] | I have the following Python code using Genshi (simplified):
```
with open(pathToHTMLFile, 'r') as f:
template = MarkupTemplate(f.read())
finalPage = template.generate().render('html', doctype = 'html')
```
The source HTML file contains entities such as `©`, `™` and `®`. Genshi replaces these with t... | Actually `&` isn't passed through, it's parsed into an ampersand character, and then serialised back to `&` on the way out because that's necessary to represent a literal ampersand in HTML. `©`, on the other hand, is not a necessary escape, so it can be left as its literal character.
So no, there's no way... |
How to dereference a memory location from python ctypes? | 1,555,944 | 6 | 2009-10-12T17:42:06Z | 1,556,482 | 10 | 2009-10-12T19:43:44Z | [
"python",
"ctypes",
"ffi"
] | I want to replicate the following c code in python ctypes:
```
main() {
long *ptr = (long *)0x7fff96000000;
printf("%lx",*ptr);
}
```
I can figure out how to call this memory location as a function pointer but not just do a normal dereference:
```
from ctypes import *
"""
>>> fptr = CFUNCTYPE(None, None)
Traceba... | `ctypes.cast`.
```
>>> import ctypes
>>> c_long_p = ctypes.POINTER(ctypes.c_long)
>>> some_long = ctypes.c_long(42)
>>> ctypes.addressof(some_long)
4300833936
>>> ctypes.cast(4300833936, c_long_p)
<__main__.LP_c_long object at 0x1005983b0>
>>> ctypes.cast(4300833936, c_long_p).contents
c_long(42)
``` |
Efficient way to find the largest key in a dictionary with non-zero value | 1,555,968 | 5 | 2009-10-12T17:48:22Z | 1,555,991 | 12 | 2009-10-12T17:51:55Z | [
"python",
"dictionary"
] | I'm new Python and trying to implement code in a more Pythonic and efficient fashion.
Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?
Thanks | Something like this should be reasonably fast:
```
>>> x = {0: 5, 1: 7, 2: 0}
>>> max(k for k, v in x.iteritems() if v != 0)
1
```
(removing the `!= 0` will be slightly faster still, but obscures the meaning somewhat.) |
Efficient way to find the largest key in a dictionary with non-zero value | 1,555,968 | 5 | 2009-10-12T17:48:22Z | 1,556,050 | 8 | 2009-10-12T18:09:11Z | [
"python",
"dictionary"
] | I'm new Python and trying to implement code in a more Pythonic and efficient fashion.
Given a dictionary with numeric keys and values, what is the best way to find the largest key with a non-zero value?
Thanks | To get the largest key, you can use the [`max`](http://docs.python.org/3.1/library/functions.html#max) function and inspect the keys like this:
```
max(x.iterkeys())
```
To filter out ones where the value is 0, you can use a [*generator expression*](http://docs.python.org/reference/expressions.html#grammar-token-gene... |
Circular import dependency in Python | 1,556,387 | 57 | 2009-10-12T19:19:30Z | 1,556,429 | 128 | 2009-10-12T19:27:53Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] | Let's say I have the following directory structure:
```
a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
```
In the `a` package's `__init__.py`, the `c` package is imported. But `c_file.py` imports `a.b.d`.
... | You may defer the import, for example in `a/__init__.py`:
```
def my_function():
from a.b.c import Blah
return Blah()
```
that is, defer the import until it is really needed. However, I would also have a close look at my package definitions/uses, as a cyclic dependency like the one pointed out might indicate ... |
Circular import dependency in Python | 1,556,387 | 57 | 2009-10-12T19:19:30Z | 1,556,444 | 53 | 2009-10-12T19:33:28Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] | Let's say I have the following directory structure:
```
a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
```
In the `a` package's `__init__.py`, the `c` package is imported. But `c_file.py` imports `a.b.d`.
... | If a depends on c and c depends on a, aren't they actually the same unit then?
You should really examine why you have split a and c into two packages, because either you have some code you should split off into another package (to make them both depend on that new package, but not each other), or you should merge them... |
Circular import dependency in Python | 1,556,387 | 57 | 2009-10-12T19:19:30Z | 19,186,096 | 14 | 2013-10-04T16:18:32Z | [
"python",
"dependencies",
"circular-dependency",
"python-import"
] | Let's say I have the following directory structure:
```
a\
__init__.py
b\
__init__.py
c\
__init__.py
c_file.py
d\
__init__.py
d_file.py
```
In the `a` package's `__init__.py`, the `c` package is imported. But `c_file.py` imports `a.b.d`.
... | I've wondered this a couple times (usually while dealing with models that need to know about each other). The simple solution is just to import the whole module, then reference the thing that you need.
So instead of doing
```
from models import Student
```
in one, and
```
from models import Classroom
```
in the ot... |
jinja2: html escape variables | 1,556,554 | 13 | 2009-10-12T20:00:49Z | 1,556,570 | 23 | 2009-10-12T20:03:50Z | [
"python",
"security",
"escaping",
"jinja2"
] | how do I html-escape dangerous unsanitized input in jinja2?
Can I do it inside the template or must it be done in python code?
I have a variable that may contain da<ngero>u&s chars. How do I escape it in jinja2 | e.g.
```
{{ user.username|e }}
```
Pipe it through the `|e` filter
[Jinija: Template Designer Documentation -> Builtin Filters: Escape](http://jinja.pocoo.org/2/documentation/templates#escape) |
jinja2: html escape variables | 1,556,554 | 13 | 2009-10-12T20:00:49Z | 3,820,710 | 11 | 2010-09-29T10:25:13Z | [
"python",
"security",
"escaping",
"jinja2"
] | how do I html-escape dangerous unsanitized input in jinja2?
Can I do it inside the template or must it be done in python code?
I have a variable that may contain da<ngero>u&s chars. How do I escape it in jinja2 | You could also tell the environment to autoescape everything:
```
e = Environment(loader=fileloader, autoescape=True)
```
note: in jinja1 this is auto\_escape |
Should you import all classes you use in Python? | 1,556,766 | 2 | 2009-10-12T20:35:36Z | 1,556,785 | 8 | 2009-10-12T20:38:56Z | [
"python",
"coding-style"
] | Python's lack of static typing makes it possible to use and rely on classes without importing them. Should you import them anyway? Does it matter?
### Example
**someclass.py**
```
class SomeClass:
def __init__(self, some_value):
self.some_value = some_value
```
**someclient.py**
```
class SomeClient:
... | Yes, it's completely ok. `some_class_instance` might be anything, it doesn't have to be an instance of `SomeClass`. You might want to pass an instance that looks just like `SomeClass`, but uses a different implementation for testing purposes, for example. |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 1,557,577 | 66 | 2009-10-12T23:59:18Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | In Linux or UNIX:
```
time python yourprogram.py
```
In Windows, see this Stackoverflow discussion: <http://stackoverflow.com/questions/673523/how-to-measure-execution-time-of-command-in-windows-command-line> |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 1,557,584 | 514 | 2009-10-13T00:00:53Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | The simplest way in python:
```
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
```
This assumes that your program takes at least a tenth of second to run.
Prints:
```
--- 0.764891862869 seconds ---
``` |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 1,557,605 | 10 | 2009-10-13T00:07:58Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | The solution of rogeriopvl works fine, but if you want more specific info you can use the python built-in profiler. Check this page:
<http://docs.python.org/library/profile.html>
a profiler tells you a lot of useful information like the time spent in every function |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 1,557,805 | 28 | 2009-10-13T01:25:01Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | ```
import time
start_time = time.clock()
main()
print time.clock() - start_time, "seconds"
```
`time.clock()` returns the processor time, which allows us to calculate only the time used by this process (on Unix anyway). The documentation says "in any case, this is the function to use for benchmarking Python or timin... |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 1,557,906 | 113 | 2009-10-13T02:08:22Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | I put this `timing.py` module into my own `site-packages` directory, and just insert `import timing` at the top of my module:
```
import atexit
from time import clock
def secondsToStr(t):
return "%d:%02d:%02d.%03d" % \
reduce(lambda ll,b : divmod(ll[0],b) + ll[1:],
[(t*1000,),1000,60,60])
lin... |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 1,558,436 | 17 | 2009-10-13T06:10:50Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | Even better for Linux: `/usr/bin/time`
```
$ /usr/bin/time -v python rhtest2.py
Command being timed: "python rhtest2.py"
User time (seconds): 4.13
System time (seconds): 0.07
Percent of CPU this job got: 91%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:04.58
Average shared text size (kbytes)... |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 12,344,609 | 18 | 2012-09-10T02:03:40Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | I really like Paul McGuire's answer, but I use Python3. So for those who are interested: here's a modification of his answer that works with Python 3 on \*nix (I imagine, under Windows, that clock() should be used instead of time()):
```
#python3
import atexit
from time import time
from datetime import timedelta
def ... |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 20,874,769 | 23 | 2014-01-02T00:35:57Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | You can use the python profiler cProfile to measure [CPU time](http://en.wikipedia.org/wiki/CPU_time) and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where to start. [This answe... |
How to get time of a python program execution? | 1,557,571 | 292 | 2009-10-12T23:56:47Z | 26,099,345 | 16 | 2014-09-29T11:55:08Z | [
"python",
"time"
] | I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the `timeit` module, but it seems it's only for small snippets of code. I want to time the whole program. | I like the output the `datetime` module provides, where time delta objects show days, hours, minutes etc. as necessary in a human-readable way.
For example:
```
from datetime import datetime
start_time = datetime.now()
# do your work here
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))
`... |
How can I distribute python programs? | 1,558,385 | 61 | 2009-10-13T05:48:20Z | 1,558,404 | 22 | 2009-10-13T05:54:46Z | [
"python",
"distribution"
] | My application looks like this:
```
main.py
windows/
__init__.py
mainwindow.py
...
model/
__init__.py
orders.py
...
resources/
image1.png
logo.jpg
...
```
The program is started with main.py. Is there a good way to create a 'final' application out of it? I'm thinking of something l... | The normal way of distributing Python applications is with [distutils](http://docs.python.org/distutils/index.html). It's made both for distributing library type python modules, and python applications, although I don't know how it works on Windows. You would on Windows have to install Python separately if you use dist... |
How can I distribute python programs? | 1,558,385 | 61 | 2009-10-13T05:48:20Z | 1,558,488 | 40 | 2009-10-13T06:31:20Z | [
"python",
"distribution"
] | My application looks like this:
```
main.py
windows/
__init__.py
mainwindow.py
...
model/
__init__.py
orders.py
...
resources/
image1.png
logo.jpg
...
```
The program is started with main.py. Is there a good way to create a 'final' application out of it? I'm thinking of something l... | I highly recommend [Pyinstaller](http://www.pyinstaller.org/), which supports all major platforms pretty seamlessly. Like py2exe and py2app, it produces a standard executable on Windows and an app bundle on OS X, but has the benefit of also doing a fantastic job of auto-resolving common dependencies and including them ... |
how do I get only the time in models | 1,558,896 | 2 | 2009-10-13T08:28:41Z | 1,558,940 | 7 | 2009-10-13T08:37:56Z | [
"python",
"django"
] | How do I format datetime to give me only the time in my model | If you've got a `datetime` object in your template called `foo`, use:
```
{{ foo|time:"H:i" }}
```
Look at the `time` filter [documentation](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#time). You're not limited to `"H:i"`, there are lots of options around for formatting `datetime` objects.
If for so... |
String arguments in python multiprocessing | 1,559,125 | 14 | 2009-10-13T09:27:27Z | 1,559,149 | 37 | 2009-10-13T09:33:44Z | [
"python",
"string",
"multiprocessing",
"arguments"
] | I'm trying to pass a string argument to a target function in a process. Somehow, the string is interpreted as a list of as many arguments as there are characters.
This is the code:
```
import multiprocessing
def write(s):
print s
write('hello')
p = multiprocessing.Process(target=write, args=('hello'))
p.start(... | This is a common gotcha in Python - if you want to have a tuple with only one element, you need to specify that it's actually a tuple (and not just something with brackets around it) - this is done by adding a comma after the element.
To fix this, just put a comma after the string, inside the brackets:
```
p = multip... |
Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools | 1,559,372 | 11 | 2009-10-13T10:25:31Z | 1,559,436 | 17 | 2009-10-13T10:41:50Z | [
"python",
"setuptools",
"distutils",
"pip"
] | Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that.
In general, I used to install system stuff via package manager, and language stuff via it's own package manager ( gem/easy\_install|pip/cpan)
Now using py... | The system python version and its libraries are often used by software in the distribution. As long as the software you are using are happy with the same versions of python and all the libraries as your distribution is, than using the distribution packages will work just fine.
However, quite often you need development... |
Which is the most pythonic: installing python modules via a package manager ( macports, apt) or via pip/easy_install/setuptools | 1,559,372 | 11 | 2009-10-13T10:25:31Z | 1,559,521 | 17 | 2009-10-13T10:57:17Z | [
"python",
"setuptools",
"distutils",
"pip"
] | Usually I tend to install things via the package manager, for unixy stuff. However, when I programmed a lot of perl, I would use CPAN, newer versions and all that.
In general, I used to install system stuff via package manager, and language stuff via it's own package manager ( gem/easy\_install|pip/cpan)
Now using py... | There are two completely opposing camps: one in favor of system-provided packages, and one in favor of separate installation. I'm personally in the "system packages" camp. I'll provide arguments from each side below.
Pro system packages: system packager already cares about dependency, and compliance with overall syste... |
coverage.py: exclude files | 1,559,424 | 24 | 2009-10-13T10:38:04Z | 1,559,639 | 34 | 2009-10-13T11:28:08Z | [
"python",
"testing",
"software-quality",
"code-coverage",
"coverage.py"
] | How do I exclude entire files from [coverage.py](http://nedbatchelder.com/code/coverage/) reports?
According to the documentation you can exclude code by matching lines. I want to exclude entire files, so that the reports don't include 3rd party libraries. Am I missing something? Can it be done? | You can omit modules with the --omit flag. It takes a comma-separated list of path prefixes. So for example:
```
coverage run my_program.py
coverage report --omit=path/to/3rdparty
``` |
coverage.py: exclude files | 1,559,424 | 24 | 2009-10-13T10:38:04Z | 19,678,723 | 9 | 2013-10-30T09:42:18Z | [
"python",
"testing",
"software-quality",
"code-coverage",
"coverage.py"
] | How do I exclude entire files from [coverage.py](http://nedbatchelder.com/code/coverage/) reports?
According to the documentation you can exclude code by matching lines. I want to exclude entire files, so that the reports don't include 3rd party libraries. Am I missing something? Can it be done? | Omitting some files worked for me using coverage API.
Well it is the same kind what Ned suggested.
Here it is how I did it:
`cov = coverage.coverage(omit='/usr/lib/python2.6/site-packages/*')` |
How to send a dictionary to a function that accepts **kwargs? | 1,559,638 | 18 | 2009-10-13T11:28:05Z | 1,559,652 | 35 | 2009-10-13T11:31:36Z | [
"python"
] | I have a function that accepts wildcard keyword parameters:
```
def func(**kargs):
doA
doB
```
How do I send it a dictionary? | Just use `func(**some_dict)` to call it.
This is documented on [section 4.7.4 of python tutorial](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists).
Note that the *same* `dict` is **not** passed into the function. A new copy is created, so `some_dict is not kwargs`. |
What is a good example of an __eq__ method for a collection class? | 1,560,245 | 6 | 2009-10-13T13:26:53Z | 1,560,279 | 7 | 2009-10-13T13:31:03Z | [
"python",
"api",
"collections",
"equality"
] | I'm working on a collection class that I want to create an `__eq__` method for. It's turning out to be more nuanced than I thought it would be and I've noticed several intricacies as far as how the built-in collection classes work.
What would really help me the most is a good example. Are there any pure Python impleme... | Parts are hard. Parts should be simple delegation.
```
def __eq__( self, other ):
if len(self) != len(other):
# Can we continue? If so, what rule applies? Pad shorter? Truncate longer?
else:
return all( self[i] == other[i] for i in range(len(self)) )
``` |
How can I get the (x,y) values of the line that is ploted by a contour plot (matplotlib)? | 1,560,424 | 11 | 2009-10-13T13:57:47Z | 1,560,735 | 8 | 2009-10-13T14:52:11Z | [
"python",
"matplotlib",
"data-analysis"
] | Is there an easy way to get the (x,y) values of a contour line that was plotted like this:
```
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [1,2,3,4]
m = [[15,14,13,12],[14,12,10,8],[13,10,7,4],[12,8,4,0]]
cs = plt.contour(x,y,m, [9.5])
plt.show()
```
Cheers, Philipp | Look at the collections property of the returned ContourSet. In particular the get\_paths() method of the first collection returns paired points making up each line segment.
```
cs.collections[0].get_paths()
``` |
Python Reverse Generator | 1,561,214 | 8 | 2009-10-13T16:04:24Z | 1,561,303 | 15 | 2009-10-13T16:15:58Z | [
"python",
"generator",
"reverse"
] | I'm looking for a way to reverse a generator object. I know how to reverse sequences:
```
foo = imap(seq.__getitem__, xrange(len(seq)-1, -1, -1))
```
But is something similar possible with a generator as the input and a reversed generator as the output (len(seq) stays the same, so the value from the original sequence... | You cannot reverse a generator in any generic way except by casting it to a sequence and creating an iterator from that. Later terms of a generator cannot necessarily be known until the earlier ones have been calculated.
Even worse, you can't know if your generator will ever hit a StopIteration exception until you hit... |
Python MySQL installing wrongly on Mac OS X 10.6 i386 | 1,562,314 | 2 | 2009-10-13T19:09:36Z | 1,562,456 | 9 | 2009-10-13T19:34:22Z | [
"python",
"mysql",
"osx"
] | When trying to install MySQL's python bindings, MySQLdb, I followed the instructions to build and install on my MacBook running Mac OS X 10.6 i386, and after entering the following line into the terminal:
```
user-152-3-158-79:MySQL-python-1.2.3c1 jianweigan$ sudo python setup.py build
```
I get the following errors:... | It appears you have installed and are using a python.org python2.6. Because that installer is designed to work for a range of systems, to build extensions with that python on 10.6, you need to install the optional 10.4 SDK which is part of the Xcode package on the Snow Leopard installation DVD or machine restore DVD; t... |
Can Python print a function definition? | 1,562,759 | 37 | 2009-10-13T20:33:35Z | 1,562,772 | 32 | 2009-10-13T20:35:55Z | [
"python"
] | In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python?
(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious). | If you're using [iPython](http://ipython.org/ "ipython homepage"), you can use **`function_name?`** to get help, and **`function_name??`** will print out the source, if it can. |
Can Python print a function definition? | 1,562,759 | 37 | 2009-10-13T20:33:35Z | 1,562,795 | 53 | 2009-10-13T20:41:18Z | [
"python"
] | In JavaScript, one can print out the definition of a function. Is there a way to accomplish this in Python?
(Just playing around in interactive mode, and I wanted to read a module without open(). I was just curious). | If you are importing the function, you can use [`inspect.getsource`](http://docs.python.org/library/inspect.html#inspect.getsource):
```
>>> import re
>>> import inspect
>>> print inspect.getsource(re.compile)
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a pattern object."
re... |
What pure Python library should I use to scrape a website? | 1,563,165 | 2 | 2009-10-13T21:58:03Z | 1,563,177 | 11 | 2009-10-13T22:01:06Z | [
"python",
"google-app-engine",
"xpath",
"beautifulsoup",
"mechanize"
] | I currently have some Ruby code used to scrape some websites. I was using Ruby because at the time I was using Ruby on Rails for a site, and it just made sense.
Now I'm trying to port this over to Google App Engine, and keep getting stuck.
I've ported Python Mechanize to work with Google App Engine, but it doesn't su... | Beautiful Soup. |
How does the Jinja2 "recursive" tag actually work? | 1,563,276 | 8 | 2009-10-13T22:21:37Z | 1,565,090 | 7 | 2009-10-14T08:56:56Z | [
"python",
"recursion",
"templates",
"jinja2"
] | I'm trying to write a very simple, tree-walking template in jinja2, using some custom objects with overloaded special methods (getattr, getitem, etc) It seems straightforward, and the equivalent python walk of the tree works fine, but there's something about the way that Jinja's recursion works that I don't understand.... | As I see from your code you understand recursive correctly, except one thing: it does replace iterable in the for statement, but doesn't update variable (`category` in your code) originally used in it. Thus, you nested loop iterates through children, but `set` tag lookups in original `category`, not one passed to the `... |
What is an "app" in Django? | 1,563,457 | 11 | 2009-10-13T23:09:56Z | 1,563,500 | 12 | 2009-10-13T23:24:30Z | [
"python",
"django"
] | According to [the documentation](http://docs.djangoproject.com/en/dev/intro/tutorial01/#id3):
> An app is a Web application that does
> something -- e.g., a weblog system, a
> database of public records or a simple
> poll app. A project is a collection of
> configuration and apps for a
> particular Web site. A project... | What makes an app (for us) is one thing:
**An App Is The Unit Of Reuse**
If we might want to split it off to use somewhere else, it's an app.
If it has a reusable data model, it's an app. User Profiles: App. Customers: App. Customer Statistical History (this is hard to explain without providing too many details): Ap... |
Add timeout argument to python's Queue.join() | 1,564,501 | 9 | 2009-10-14T06:02:49Z | 1,564,786 | 14 | 2009-10-14T07:33:14Z | [
"python",
"join",
"timeout",
"queue"
] | I want to be able to join() the Queue class but timeouting after some time if the call hasn't returned yet.
What is the best way to do it? Is it possible to do it by subclassing queue\using metaclass? | Subclassing `Queue` is probably the best way. Something like this should work (untested):
```
def join_with_timeout(self, timeout):
self.all_tasks_done.acquire()
try:
endtime = time() + timeout
while self.unfinished_tasks:
remaining = endtime - time()
if remaining <= 0.0... |
Add timeout argument to python's Queue.join() | 1,564,501 | 9 | 2009-10-14T06:02:49Z | 3,516,318 | 8 | 2010-08-18T20:20:30Z | [
"python",
"join",
"timeout",
"queue"
] | I want to be able to join() the Queue class but timeouting after some time if the call hasn't returned yet.
What is the best way to do it? Is it possible to do it by subclassing queue\using metaclass? | The *join()* method is all about waiting for all the tasks to be done. If you don't care whether the tasks have actually finished, you can periodically poll the unfinished task count:
```
stop = time() + timeout
while q.unfinished_tasks and time() < stop:
sleep(1)
```
This loop will exist either when the tasks ar... |
CMake output name for dynamic-loaded library? | 1,564,696 | 32 | 2009-10-14T07:08:01Z | 1,566,114 | 53 | 2009-10-14T13:07:17Z | [
"python",
"cmake",
"shared-libraries",
"boost-python"
] | I'm trying to write cmake rules to build dynamic-loaded library for python using boost.python on linux. I'd like to use 'foo' for python module name. So, the library must be called `foo.so`.
But by default, cmake uses standard rules for library naming, so if I write
```
add_library(foo foo.cpp)
```
I will get `libfoo... | You can unset the prefix with this line:
```
set_target_properties(foo PROPERTIES PREFIX "")
``` |
Python: imports at the beginning of the main program & PEP 8 | 1,565,173 | 5 | 2009-10-14T09:20:19Z | 1,565,181 | 8 | 2009-10-14T09:23:03Z | [
"python",
"import",
"main",
"pep8",
"pep"
] | The [PEP 8](http://python.org/dev/peps/pep-0008/) recommends that modules be imported at the beginning of programs.
Now, I feel that importing some of them at the beginning of the *main* program (i.e., after `if __name__ == '__main__'`) makes sense. For instance, if the main program reads arguments from the command li... | I can't really tell you how bad this is to do.
However, I've greatly improved performance (response time, load) for a web app by importing certain libraries only at the first usage.
BTW, the following is also from PEP 8:
> But most importantly: know when to be
> inconsistent -- sometimes the style
> guide just doesn... |
Subclassing Python tuple with multiple __init__ arguments | 1,565,374 | 33 | 2009-10-14T10:10:41Z | 1,565,448 | 43 | 2009-10-14T10:24:33Z | [
"python",
"inheritance",
"subclass",
"tuples"
] | The following code works:
```
class Foo(tuple):
def __init__(self, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo([3, 4])
$ python play.py
play.py:4: DeprecationWarning: object.__init__() takes no parameters
super(Foo, self).__init__(tuple(b))
(3, 4)
```
But not the... | Because tuples are immutable, you have to override `__new__` instead:
[python docs](http://docs.python.org/reference/datamodel.html#object.__new__)
> `object.__new__(cls[, ...])`
>
> Called to create a new instance of
> class `cls`. `__new__()` is a static
> method (special-cased so you need not
> declare it as such)... |
Subclassing Python tuple with multiple __init__ arguments | 1,565,374 | 33 | 2009-10-14T10:10:41Z | 13,094,796 | 26 | 2012-10-26T21:38:33Z | [
"python",
"inheritance",
"subclass",
"tuples"
] | The following code works:
```
class Foo(tuple):
def __init__(self, b):
super(Foo, self).__init__(tuple(b))
if __name__ == '__main__':
print Foo([3, 4])
$ python play.py
play.py:4: DeprecationWarning: object.__init__() takes no parameters
super(Foo, self).__init__(tuple(b))
(3, 4)
```
But not the... | To assign the tuple value you need to override the `__new__` method:
```
class Foo(tuple):
def __new__ (cls, a, b):
return super(Foo, cls).__new__(cls, tuple(b))
```
The arguments seem to be ignored by the `__init__` implementation of the tuple class, but if you need to do some init stuff you can do it a... |
Plot GeoIP data on a World Map | 1,565,555 | 6 | 2009-10-14T10:49:21Z | 1,566,197 | 7 | 2009-10-14T13:23:08Z | [
"python",
"geolocation",
"maps",
"plot"
] | I need a library (preferably written in Python) which is able to take a series of IP addresses (or geographic coordinates) and plots them on a World Map.
I already found [this one](http://gsl-nagoya-u.net/appendix/software/worldmap/), but it outputs data as a .svg file and it's simply unable to cope with large data se... | Perhaps [Basemap](http://matplotlib.org/basemap/) in [Matplotlib](http://matplotlib.sourceforge.net/) for the plotting.
It can do all sorts of [projections](http://matplotlib.org/basemap/users/mapsetup.html) (don't mind the ugly default colours). And you have good control over what/how you plot. You can even use [NASA... |
Why is Python's "append" not "push"? | 1,566,266 | 176 | 2009-10-14T13:34:26Z | 1,566,285 | 18 | 2009-10-14T13:36:55Z | [
"python"
] | Does anyone know why Python's `list.append` function is not called `list.push` given that there's already a `list.pop` that removes and returns the last element (that indexed at -1) and `list.append` semantic is consistent with that use? | Because it appends; it doesn't push. "Appending" adds to the end of a list, "pushing" adds to the front.
Think of a queue vs. a stack.
<http://docs.python.org/tutorial/datastructures.html>
**Edit:** To reword my second sentence more exactly, "Appending" very clearly implies adding something to the *end* of a list, r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.