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 |
|---|---|---|---|---|---|---|---|---|---|
Django and monkey patching issue | 1,399,746 | 4 | 2009-09-09T13:40:39Z | 1,399,813 | 7 | 2009-09-09T13:52:26Z | [
"python",
"django",
"monkeypatching"
] | I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.
I tri... | When you add a field to any model, even if you do it the 'official' way, you need to migrate the database - Django doesn't do it for you. Drop the table and run `./manage.py syncdb` again.
You might want to investigate one of the migrations frameworks, such as `south`, which will manage this sort of thing for you. |
Django and monkey patching issue | 1,399,746 | 4 | 2009-09-09T13:40:39Z | 1,399,843 | 13 | 2009-09-09T13:55:48Z | [
"python",
"django",
"monkeypatching"
] | I have recently started experimenting with Django for some web applications in my spare time. While designing the data model for one, I came across the dilemma of using inheritance to define a user of the website or using a technique known as monkey patching with the User class already supplied by the framework.
I tri... | There's an alternative to both approaches, which is to simply use [a related profile model](http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/). This also happens to be a well-documented, highly recommended approach. Perhaps the reason that the add\_to\_class approach is not well-documented, as ... |
Endianness of integers in Python | 1,400,012 | 12 | 2009-09-09T14:20:42Z | 1,400,026 | 15 | 2009-09-09T14:23:14Z | [
"python",
"integer",
"endianness"
] | I'm working on a program where I store some data in an integer and process it bitwise. For example, I might receive the number 48, which I will process bit-by-bit. In general the endianness of integers depends on the machine representation of integers, but does Python do anything to guarantee that the ints will always ... | Python's `int` has the same endianness as the processor it runs on. The [`struct`](http://docs.python.org/library/struct.html) module lets you convert byte blobs to ints (and viceversa, and some other data types too) in either native, little-endian, or big-endian ways, depending on the [format string](http://docs.pytho... |
Endianness of integers in Python | 1,400,012 | 12 | 2009-09-09T14:20:42Z | 1,400,069 | 13 | 2009-09-09T14:27:59Z | [
"python",
"integer",
"endianness"
] | I'm working on a program where I store some data in an integer and process it bitwise. For example, I might receive the number 48, which I will process bit-by-bit. In general the endianness of integers depends on the machine representation of integers, but does Python do anything to guarantee that the ints will always ... | If you need to process your data 'bitwise' then the [`bitstring`](http://code.google.com/p/python-bitstring/) module might be of help to you. It can also deal with endianness between platforms (on the latest trunk build at least - to be released in the next few days).
The [`struct` module](http://docs.python.org/libra... |
Dictionary of tags in declarative SQLAlchemy? | 1,400,537 | 6 | 2009-09-09T15:54:37Z | 1,400,881 | 13 | 2009-09-09T17:04:33Z | [
"python",
"sqlalchemy",
"declarative"
] | I am working on a quite large code base that has been implemented using `sqlalchemy.ext.declarative`, and I need to add a dict-like property to one of the classes. What I need is the same as in [this question](http://stackoverflow.com/questions/780774/sqlalchemy-dictionary-of-tags), but in a declarative fashion. Can an... | Declarative is just another way of defining things. Virtually you end up with the exact same environment than if you used separated mapping.
Since I answered the other question, I'll try this one as well. Hope it gives more upvotes ;)
Well, first we define the classes
```
from sqlalchemy import Column, Integer, Stri... |
How to empty a list in Python? | 1,400,608 | 215 | 2009-09-09T16:08:21Z | 1,400,622 | 366 | 2009-09-09T16:10:40Z | [
"python",
"list"
] | It seems so "dirty" emptying a list in this way:
```
while len(alist) > 0 : alist.pop()
```
Does a clear way exist to do that? | This actually removes the contents from the list, not replaces the old label with a new empty list
```
del lst[:]
```
example:
```
lst1 = [1, 2, 3]
lst2 = lst1
del lst1[:]
print(lst2)
```
For the sake of completeness, slice assignment achieves the same effect:
```
lst[:] = []
```
and can be used to shrink a part ... |
How to empty a list in Python? | 1,400,608 | 215 | 2009-09-09T16:08:21Z | 1,400,624 | 37 | 2009-09-09T16:10:52Z | [
"python",
"list"
] | It seems so "dirty" emptying a list in this way:
```
while len(alist) > 0 : alist.pop()
```
Does a clear way exist to do that? | You could try:
```
alist[:] = []
```
Which means: Splice in the list `[]` (0 elements) at the location `[:]` (all indexes from start to finish)
The [:] is the slice operator. See [this question](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) for more information. |
How to empty a list in Python? | 1,400,608 | 215 | 2009-09-09T16:08:21Z | 8,239,837 | 23 | 2011-11-23T09:30:17Z | [
"python",
"list"
] | It seems so "dirty" emptying a list in this way:
```
while len(alist) > 0 : alist.pop()
```
Does a clear way exist to do that? | it turns out that with python 2.5.2, `del l[:]` is slightly slower than `l[:] = []` by 1.1 usec.
```
$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Pyt... |
How to empty a list in Python? | 1,400,608 | 215 | 2009-09-09T16:08:21Z | 30,087,221 | 15 | 2015-05-06T20:46:24Z | [
"python",
"list"
] | It seems so "dirty" emptying a list in this way:
```
while len(alist) > 0 : alist.pop()
```
Does a clear way exist to do that? | If you have Python 3.3 or better, you could use the [`clear()`](https://docs.python.org/dev/library/stdtypes.html#typesseq-mutable) method of `list`:
```
alist.clear() # removes all items from alist (equivalent to del alist[:])
```
As per the linked page, the same can also be achieved with `alist *= 0`. |
How to create QString in PyQt4? | 1,400,858 | 9 | 2009-09-09T17:00:03Z | 2,595,514 | 14 | 2010-04-07T20:04:01Z | [
"python",
"user-interface",
"pyqt"
] | ```
str = QtCore.QString('Hello')
AttributeError: 'module' object has no attribute 'QString'
QtCore.QString._init_(self)
AttributeError: 'module' object has no attribute 'QString'
```
Yes, I'm read [QString Class Reference](http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html)
if you can, answer with code sample. Th... | In Python 3, QString is automatically mapped to the native Python string by default:
> The QString class is implemented as a mapped type that is automatically converted to and from a Python string. In addition a None is converted to a null QString. However, a null QString is converted to an empty Python string (and no... |
How to create QString in PyQt4? | 1,400,858 | 9 | 2009-09-09T17:00:03Z | 3,982,776 | 9 | 2010-10-20T22:14:36Z | [
"python",
"user-interface",
"pyqt"
] | ```
str = QtCore.QString('Hello')
AttributeError: 'module' object has no attribute 'QString'
QtCore.QString._init_(self)
AttributeError: 'module' object has no attribute 'QString'
```
Yes, I'm read [QString Class Reference](http://pyqt.sourceforge.net/Docs/PyQt4/qstring.html)
if you can, answer with code sample. Th... | From PyQt4 4.6+ in Python3 QString doesn't exist and you are supposed to use ordinary Python3 unicode objects (string literals). To do this so that your code will work in both Python 2.x AND Python 3.x you can do following:
```
try:
from PyQt4.QtCore import QString
except ImportError:
# we are using Python3 so... |
Python with matplotlib - drawing multiple figures in parallel | 1,401,102 | 29 | 2009-09-09T17:57:12Z | 1,401,191 | 33 | 2009-09-09T18:11:15Z | [
"python",
"matplotlib",
"figures"
] | I have functions that contribute to small parts of a figure generation. I'm trying to use these functions to generate multiple figures? So something like this:
1. work with Figure 1
2. do something else
3. work with Figure 2
4. do something else
5. work with Figure 1
6. do something else
7. work with Figure 2
If anyo... | There are several ways to do this, and the simplest is to use the figure numbers. The code below makes two figures, #0 and #1, each with two lines. #0 has the points 1,2,3,4,5,6, and #2 has the points 10,20,30,40,50,60.
```
from pylab import *
figure(0)
plot([1,2,3])
figure(1)
plot([10, 20, 30])
figure(0)
plot([4, ... |
How do I programmatically check whether an image (PNG, JPEG, or GIF) is corrupted? | 1,401,527 | 14 | 2009-09-09T19:15:41Z | 1,401,565 | 20 | 2009-09-09T19:24:10Z | [
"php",
"python",
"image"
] | Okay. So I have about 250,000 high resolution images. What I want to do is go through all of them and find ones that are corrupted. If you know what 4scrape is, then you know the nature of the images I.
Corrupted, to me, is the image is loaded into Firefox and it says
> `The image âsuch and such imageâ cannot be ... | An easy way would be to try loading and verifying the files with PIL (Python Imaging Library).
```
from PIL import Image
v_image = Image.open(file)
v_image.verify()
```
Catch the exceptions...
From [the documentation](http://effbot.org/imagingbook/image.htm):
**im.verify()**
*Attempts to determine if the file is ... |
Python: copy.deepcopy produces an error | 1,401,610 | 2 | 2009-09-09T19:32:40Z | 1,401,640 | 9 | 2009-09-09T19:38:33Z | [
"python",
"generator"
] | I have been using this copy method for quite a while, in lots of classes that needed it.
```
class population (list):
def __init__ (self):
pass
def copy(self):
return copy.deepcopy(self)
```
It has suddenly started producing this error:
```
File "C:\Python26\lib\copy.py", line 338, in _reconstruct
... | Are you cloning a generator? [Generators can't be cloned.](https://mail.python.org/pipermail/python-list/2009-March/539759.html)
Copying answer by Gabriel Genellina here:
---
There is no way of "cloning" a generator:
```
py> g = (i for i in [1,2,3])
py> type(g)()
Traceback (most recent call last):
File "<stdin>"... |
Problem with list of strings in python | 1,401,650 | 5 | 2009-09-09T19:40:07Z | 1,401,691 | 12 | 2009-09-09T19:45:15Z | [
"python",
"list"
] | Why on Earth doesn't the interpreter raise SyntaxError everytime I do this:
```
my_abc = ['a',
'b',
'c'
'd',]
```
I just wanted to add 'c' to the list of strings, and forgot to append the comma. I would expect this to cause some kind of error, as it's cleary incorrect.
Instead, what I g... | Is called "Implicit String Concatenation" and a PEP that proposed its removal was rejected: <http://www.python.org/dev/peps/pep-3126/> |
Python: List all base classes in a hierarchy of given class | 1,401,661 | 65 | 2009-09-09T19:41:52Z | 1,401,706 | 12 | 2009-09-09T19:47:49Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] | Given a class `Foo` (whether it is a [new-style](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes) class or not), how do you generate **all** the base classes - anywhere in the inheritance hierarchy - it [`issubclass`](http://docs.python.org/library/functions.html?highlight=issubclass#issub... | you can use the `__bases__` tuple of the class object:
```
class A(object, B, C):
def __init__(self):
pass
print A.__bases__
```
The tuple returned by `__bases__` has all its base classes.
Hope it helps! |
Python: List all base classes in a hierarchy of given class | 1,401,661 | 65 | 2009-09-09T19:41:52Z | 1,401,707 | 19 | 2009-09-09T19:47:54Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] | Given a class `Foo` (whether it is a [new-style](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes) class or not), how do you generate **all** the base classes - anywhere in the inheritance hierarchy - it [`issubclass`](http://docs.python.org/library/functions.html?highlight=issubclass#issub... | `inspect.getclasstree()` will create a nested list of classes and their bases.
Usage:
```
inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.
``` |
Python: List all base classes in a hierarchy of given class | 1,401,661 | 65 | 2009-09-09T19:41:52Z | 1,401,708 | 23 | 2009-09-09T19:48:12Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] | Given a class `Foo` (whether it is a [new-style](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes) class or not), how do you generate **all** the base classes - anywhere in the inheritance hierarchy - it [`issubclass`](http://docs.python.org/library/functions.html?highlight=issubclass#issub... | See the [`__bases__` property](http://docs.python.org/library/stdtypes.html#special-attributes) available on a python `class`, which contains a tuple of the bases classes:
```
>>> def classlookup(cls):
... c = list(cls.__bases__)
... for base in c:
... c.extend(classlookup(base))
... return c
...
>... |
Python: List all base classes in a hierarchy of given class | 1,401,661 | 65 | 2009-09-09T19:41:52Z | 1,401,900 | 102 | 2009-09-09T20:28:21Z | [
"python",
"class",
"inheritance",
"oop",
"introspection"
] | Given a class `Foo` (whether it is a [new-style](http://docs.python.org/reference/datamodel.html#new-style-and-classic-classes) class or not), how do you generate **all** the base classes - anywhere in the inheritance hierarchy - it [`issubclass`](http://docs.python.org/library/functions.html?highlight=issubclass#issub... | `inspect.getmro(cls)` works for both new and old style classes and returns the same as `NewClass.mro()`: a list of the class and all its base classes.
```
>>> class A(object):
>>> pass
>>>
>>> class B(A):
>>> pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type '... |
How can the euclidean distance be calculated with numpy? | 1,401,712 | 150 | 2009-09-09T19:48:49Z | 1,401,755 | 16 | 2009-09-09T19:56:36Z | [
"python",
"numpy",
"euclidean-distance"
] | I have two points in 3D:
```
(xa, ya, za)
(xb, yb, zb)
```
And I want to calculate the distance:
```
dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
```
What's the best way to do this with Numpy, or with Python in general? I have:
```
a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
``` | Another instance of [this problem solving method](http://stackoverflow.com/questions/13289/can-you-share-your-secrets-or-best-practices-for-problem-solving/13336#13336). As soon as I submitted the question I got it:
```
def dist(x,y):
return numpy.sqrt(numpy.sum((x-y)**2))
a = numpy.array((xa,ya,za))
b = numpy... |
How can the euclidean distance be calculated with numpy? | 1,401,712 | 150 | 2009-09-09T19:48:49Z | 1,401,828 | 265 | 2009-09-09T20:12:50Z | [
"python",
"numpy",
"euclidean-distance"
] | I have two points in 3D:
```
(xa, ya, za)
(xb, yb, zb)
```
And I want to calculate the distance:
```
dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
```
What's the best way to do this with Numpy, or with Python in general? I have:
```
a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
``` | Use [`numpy.linalg.norm`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html):
```
dist = numpy.linalg.norm(a-b)
``` |
How can the euclidean distance be calculated with numpy? | 1,401,712 | 150 | 2009-09-09T19:48:49Z | 21,986,532 | 41 | 2014-02-24T11:32:29Z | [
"python",
"numpy",
"euclidean-distance"
] | I have two points in 3D:
```
(xa, ya, za)
(xb, yb, zb)
```
And I want to calculate the distance:
```
dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)
```
What's the best way to do this with Numpy, or with Python in general? I have:
```
a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
``` | There's a function for that in SciPy, it's called [Euclidean](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.euclidean.html#scipy.spatial.distance.euclidean)
example:
```
from scipy.spatial import distance
a = (1,2,3)
b = (4,5,6)
dst = distance.euclidean(a,b)
``` |
Why is there no list.clear() method in python? | 1,401,933 | 36 | 2009-09-09T20:34:42Z | 1,402,256 | 18 | 2009-09-09T21:40:04Z | [
"python",
"list",
"clear"
] | Inspired by [this question.](http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python)
Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.
```
del lst[:]
ls... | In the threads you linked [Raymond Hettinger pretty much sums up the pros and cons](https://mail.python.org/pipermail/python-list/2006-April/384992.html) of adding that method. When it comes to language design, it's really important to be conservative. See for example the ["every feature starts with -100 points"](http:... |
Why is there no list.clear() method in python? | 1,401,933 | 36 | 2009-09-09T20:34:42Z | 6,675,045 | 13 | 2011-07-13T06:43:22Z | [
"python",
"list",
"clear"
] | Inspired by [this question.](http://stackoverflow.com/questions/1400608/how-to-empty-a-list-in-python)
Why is there no list.clear() method in python? I've found several questions here that say the correct way to do it is one of the following, but no one has said why there isn't just a method for it.
```
del lst[:]
ls... | While there was no `list.clear()` when this question was asked, 3.3 now has one (as requested in <http://bugs.python.org/issue10516>). Additionally, `clear()` methods have been added to [`bytearray`](http://docs.python.org/dev/library/functions.html#bytearray) and [`MutableSequence`](http://docs.python.org/dev/library/... |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | 17 | 2009-09-09T20:48:09Z | 1,402,225 | 17 | 2009-09-09T21:35:09Z | [
"python",
"django"
] | I'm trying to add images to my models in my Django app.
models.py
```
class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
```
In development mode, every time I try to upload the image via Django admin, I keep getting:
> Upload a valid image. The fi... | Did you install libjpeg after PIL was already compiled/installed on the system? Maybe it can't find the decoder properly?
Here's one set of instructions I found on getting libjpeg and PIL playing nicely on MacOS (see towards the end; looks like you may need to explicitly set the dir of the decoder):
<http://djangoday... |
Why can't I upload jpg files to my Django app via admin/? | 1,402,002 | 17 | 2009-09-09T20:48:09Z | 4,366,389 | 16 | 2010-12-06T12:29:47Z | [
"python",
"django"
] | I'm trying to add images to my models in my Django app.
models.py
```
class ImageMain(models.Model):
product = models.ForeignKey(Product)
photo = models.ImageField(upload_to='products')
```
In development mode, every time I try to upload the image via Django admin, I keep getting:
> Upload a valid image. The fi... | I met the same problem in Ubuntu server, then you can fix it by installing libjpeg-dev before PIL.
```
sudo apt-get install libjpeg-dev
sudo pip install PIL --upgrade
```
and if you already installed libjpeg-dev after PIL. then you can remove PIL first, and try to reinstall PIL as following.
```
sudo pip uninstall P... |
How do I right-align numeric data in Python? | 1,402,048 | 24 | 2009-09-09T20:56:57Z | 1,402,081 | 30 | 2009-09-09T21:03:02Z | [
"python",
"string",
"text",
"formatting"
] | I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:
```
p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x... | In Python 2.5 use rjust (on strings). Also, try to get used to [string formatting](http://www.diveintopython.net/native_data_types/formatting_strings.html) in python instead of just concatenating strings. Simple example for rjust and string formatting below:
```
width = 10
str_number = str(ord('a'))
print 'a%s' % (str... |
How do I right-align numeric data in Python? | 1,402,048 | 24 | 2009-09-09T20:56:57Z | 1,402,091 | 21 | 2009-09-09T21:04:34Z | [
"python",
"string",
"text",
"formatting"
] | I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:
```
p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x... | Use python string formatting: `'%widths'` where width is an integer
```
>>> '%10s' % 10
' 10'
>>> '%10s' % 100000
' 100000'
``` |
How do I right-align numeric data in Python? | 1,402,048 | 24 | 2009-09-09T20:56:57Z | 1,402,453 | 59 | 2009-09-09T22:21:59Z | [
"python",
"string",
"text",
"formatting"
] | I have some data that I am displaying in 3 column format, of the form "key: value key: key: value key: value". Here's an example:
```
p: 1 sl: 10 afy: 4
q: 12 lg: 10 kla: 3
r: 0 kl: 10 klw: 3
s: 67 vw: 9 jes: 3
t: 16 uw: 9 skw: 3
u: 47 ug: 9 mjl: 3
v: 37 mj: 8 lza: 3
w: 119 fv: 8 fxg: 3
x... | In python 2.6+ (and it's the standard method in 3), the "preferred" method for string formatting is to use string.format() (the complete docs for which can be found [here](http://docs.python.org/library/string.html?highlight=string%20common%20string%20operations#format-string-syntax)).
right justification can be done w... |
Python on an Real-Time Operation System (RTOS) | 1,402,933 | 13 | 2009-09-10T01:12:23Z | 1,403,080 | 14 | 2009-09-10T02:17:38Z | [
"python",
"rtos",
"python-stackless",
"qnx"
] | I am planning to implement a small-scale data acquisition system on an RTOS platform. (Either on a QNX or an RT-Linux system.)
As far as I know, these jobs are performed using C / C++ to get the most out of the system. However I am curious to know and want to learn some experienced people's opinions before I blindly j... | I can't speak for *every* data acquisition setup out there, but *most* of them spend most of their "real-time operations" *waiting* for data to come in -- at least the ones I've worked on.
Then when the data *does* come in, you need to immediately record the event or respond to it, and then it's back to the waiting ga... |
Python on an Real-Time Operation System (RTOS) | 1,402,933 | 13 | 2009-09-10T01:12:23Z | 15,011,981 | 16 | 2013-02-21T20:52:00Z | [
"python",
"rtos",
"python-stackless",
"qnx"
] | I am planning to implement a small-scale data acquisition system on an RTOS platform. (Either on a QNX or an RT-Linux system.)
As far as I know, these jobs are performed using C / C++ to get the most out of the system. However I am curious to know and want to learn some experienced people's opinions before I blindly j... | I've built several all-Python soft real-time (RT) systems, with primary cycle times from 1 ms to 1 second. There are some basic strategies and tactics I've learned along the way:
1. Use threading/multiprocessing ***only*** to offload non-RT work from the primary thread, where queues between threads are acceptable and ... |
Python - IronPython dilemma | 1,403,103 | 15 | 2009-09-10T02:30:15Z | 1,403,134 | 18 | 2009-09-10T02:46:03Z | [
"python",
"excel",
"vba",
"ironpython",
"python.net"
] | I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:
1. What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of lang... | 1) IronPython and CPython share nearly identical language syntax. There is very little difference between them. Transitioning should be trivial.
2) The libraries in IronPython are very different than CPython. The **Python** libraries are a fair bit behind - quite a few of the CPython-accessible libraries will not work... |
Python - IronPython dilemma | 1,403,103 | 15 | 2009-09-10T02:30:15Z | 1,403,346 | 11 | 2009-09-10T04:24:42Z | [
"python",
"excel",
"vba",
"ironpython",
"python.net"
] | I'm starting to study Python, and for now I like it very much. But, if you could just answer a few questions for me, which have been troubling me, and I can't find any definite answers to them:
1. What is the relationship between Python's C implementation (main version from python.org) and IronPython, in terms of lang... | > What is the relationship between
> Python's C implementation (main
> version from python.org) and
> IronPython, in terms of language
> compatibility ? Is it the same
> language, and do I by learning one,
> will be able to smoothly cross to
> another, or is it Java to JavaScript ?
Same language (at 2.5 level for now ... |
Efficient way to determine whether a particular function is on the stack in Python | 1,403,471 | 3 | 2009-09-10T05:11:09Z | 1,403,485 | 8 | 2009-09-10T05:16:11Z | [
"python",
"callstack"
] | For debugging, it is often useful to tell if a particular function is higher up on the call stack. For example, we often only want to run debugging code when a certain function called us.
One solution is to examine all of the stack entries higher up, but it this is in a function that is deep in the stack and repeatedl... | Unless the function you're aiming for does something very special to mark "one instance of me is active on the stack" (IOW: if the function is pristine and untouchable and can't possibly be made aware of this peculiar need of yours), there is no conceivable alternative to walking frame by frame up the stack until you h... |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | 72 | 2009-09-10T06:32:29Z | 1,403,693 | 136 | 2009-09-10T06:37:28Z | [
"list",
"python"
] | Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]
Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line? | ```
>>> l = range(165)
>>> l[0::10]
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160]
```
EDIT: just for fun, a little timing comparison (ignoring the boundary condition):
```
$ python -m timeit -s "l = range(1000)" "l1 = [x for x in l if x % 10 == 0]"
1000 loops, best of 3: 525 usec per loop... |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | 72 | 2009-09-10T06:32:29Z | 1,403,698 | 16 | 2009-09-10T06:37:59Z | [
"list",
"python"
] | Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]
Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line? | You can use the slice operator like this:
```
l = [1,2,3,4,5]
l2 = l[::2] # get subsequent 2nd item
``` |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | 72 | 2009-09-10T06:32:29Z | 1,403,703 | 8 | 2009-09-10T06:39:50Z | [
"list",
"python"
] | Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]
Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line? | From manual: `s[i:j:k] slice of s from i to j with step k`
```
li = range(100); sub = li[0::10]
>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
``` |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | 72 | 2009-09-10T06:32:29Z | 1,403,706 | 8 | 2009-09-10T06:42:24Z | [
"list",
"python"
] | Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]
Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line? | ```
newlist = oldlist[::10]
```
This picks out every 10th element of the list. |
Pythonic way to return list of every n'th item in a larger list | 1,403,674 | 72 | 2009-09-10T06:32:29Z | 1,404,229 | 27 | 2009-09-10T09:13:49Z | [
"list",
"python"
] | Say we have a list of numbers from zero to 1000. Is there a pythonic/efficient way to produce a list of the first and every subsequent 10th item? ie. [0, 10, 20, 30 ...]
Yes I can do this using a for loop but I'm wondering if there is a neater way to do this, perhaps even in one line? | 1. `source_list[::10]` is the most obvious, but this doesn't work for any iterable and is not memory efficient for large lists.
2. `itertools.islice(source_sequence, 0, None, 10)` works for any iterable and is memery efficient, but probably is not the fastest solution for large list and big step.
3. `(source_list[i] fo... |
Plotting two graphs that share an x-axis in matplotlib | 1,404,502 | 8 | 2009-09-10T10:27:50Z | 1,404,572 | 17 | 2009-09-10T10:50:20Z | [
"python",
"matplotlib"
] | I have to plot 2 graphs in a single screen. The x-axis remains the same but the y-axis should be different.
How can I do that in 'matplotlib'? | [`twinx`](http://matplotlib.sourceforge.net/api/axes%5Fapi.html?highlight=twinx#matplotlib.axes.Axes.twinx) is the function you're looking for; [here's an example](http://matplotlib.sourceforge.net/examples/api/two%5Fscales.html) of how to use it.
:
```
autocmd FileType python set tabstop=4|set shiftwidth=4|set expandtab
``` |
gVim and multiple programming languages | 1,404,515 | 13 | 2009-09-10T10:34:07Z | 1,404,570 | 22 | 2009-09-10T10:49:21Z | [
"python",
"perl",
"editor",
"vim"
] | My day job involves coding with Perl. At home I play around with Python and Erlang. For Perl I want to indent my code with two spaces. Whereas for Python the standard is 4. Also I have some key bindings to open function declarations which I would like to use with all programming languages. How can this be achieved in g... | In your $HOME, make .vim/ directory (or vimfiles/ on Windows), in it make ftplugin/ directory, and in it keep files named "perl.vim" or "python.vim" or "html.vim" or ...
These should be loaded automatically when you open/create new file of given filetype as long as you don't forget to add `:filetype plugin on` in your... |
gVim and multiple programming languages | 1,404,515 | 13 | 2009-09-10T10:34:07Z | 1,405,318 | 7 | 2009-09-10T13:29:18Z | [
"python",
"perl",
"editor",
"vim"
] | My day job involves coding with Perl. At home I play around with Python and Erlang. For Perl I want to indent my code with two spaces. Whereas for Python the standard is 4. Also I have some key bindings to open function declarations which I would like to use with all programming languages. How can this be achieved in g... | In addition to rangerchris's answer, you might consider using modelines. Modelines tell the editor how to configure itself:
```
#!/usr/bin/perl
# vi: ts=4 sw=4 ht=4 et textwidth=76 :
use strict;
use warnings;
print "hello world\n";
```
That modeline tells vi to use 4 character tabs and autoindents, to use spaces in... |
Path separator char in python 2.4 | 1,404,749 | 15 | 2009-09-10T11:30:26Z | 1,404,767 | 36 | 2009-09-10T11:34:59Z | [
"python",
"path-separator"
] | Just out of curiosity - is there another way to obtain the platform's path separator char than `os.path.normcase('/')` in Python 2.4?
I was expecting something like a `os.path.separator` constant... | That would be [`os.sep`](http://docs.python.org/library/os.html#os.sep). |
How to adjust the quality of a resized image in Python Imaging Library? | 1,405,602 | 33 | 2009-09-10T14:27:55Z | 1,405,701 | 51 | 2009-09-10T14:41:39Z | [
"python",
"python-imaging-library"
] | thanks for taking time to read my question.
I am working on PIL and need to know if the image quality can be adjusted while resizing or thumbnailing an image. From what I have known is the default quality is set to 85. Can this parameter be tweaked during resizing?
I am currently using the following code:
```
image ... | Use PIL's `resize` method manually:
```
image = image.resize((x, y), Image.ANTIALIAS) # LANCZOS as of Pillow 2.7
```
Followed by the save method
```
quality_val = 90
image.save(filename, 'JPEG', quality=quality_val)
```
Take a look at the source for [`models.py`](http://code.google.com/p/django-photologue/source/b... |
How to adjust the quality of a resized image in Python Imaging Library? | 1,405,602 | 33 | 2009-09-10T14:27:55Z | 1,405,713 | 37 | 2009-09-10T14:44:19Z | [
"python",
"python-imaging-library"
] | thanks for taking time to read my question.
I am working on PIL and need to know if the image quality can be adjusted while resizing or thumbnailing an image. From what I have known is the default quality is set to 85. Can this parameter be tweaked during resizing?
I am currently using the following code:
```
image ... | ANTIALIAS is in no way comparable to the "85" quality level. The ANTIALIAS parameter tells the thumbnail method what algorithm to use for resampling pixels from one size to another. For example, if I have a 3x3 image that looks like this:
```
2 2 2
2 0 2
2 2 2
```
and I resize it to 2x2, one algorithm might give me:
... |
What is the simplest URL shortener application one could write in python for the Google App Engine? | 1,405,786 | 12 | 2009-09-10T14:57:02Z | 1,405,962 | 28 | 2009-09-10T15:21:01Z | [
"python",
"google-app-engine"
] | Services like bit.ly are great for shortening URLâs that you want to include in tweets and other conversations. What is the simplest URL shortener application one could write in python for the Google App Engine? | That sounds like a challenge!
```
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import run_wsgi_app
class ShortLink(db.Model):
url = db.TextProperty(required=True)
class CreateLinkHandler(webapp.RequestHandler):
def post(self):
link = ShortLink(u... |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | 224 | 2009-09-10T15:14:01Z | 1,405,971 | 247 | 2009-09-10T15:21:42Z | [
"python",
"osx"
] | I need a way to tell what mode the shell is in from within the shell.
I've tried looking at the [platform](http://docs.python.org/library/platform.html) module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm ru... | UPDATED:
One way is to look at `sys.maxsize` as documented [here](http://docs.python.org/library/platform.html#cross-platform):
```
$ python-32 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7fffffff', False)
$ python-64 -c 'import sys;print("%x" % sys.maxsize, sys.maxsize > 2**32)'
('7ffffffffffffff... |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | 224 | 2009-09-10T15:14:01Z | 1,406,210 | 43 | 2009-09-10T16:06:35Z | [
"python",
"osx"
] | I need a way to tell what mode the shell is in from within the shell.
I've tried looking at the [platform](http://docs.python.org/library/platform.html) module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm ru... | Try using ctypes to get the size of a void pointer:
```
import ctypes
print ctypes.sizeof(ctypes.c_voidp)
```
It'll be 4 for 32 bit or 8 for 64 bit. |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | 224 | 2009-09-10T15:14:01Z | 1,406,849 | 113 | 2009-09-10T18:11:27Z | [
"python",
"osx"
] | I need a way to tell what mode the shell is in from within the shell.
I've tried looking at the [platform](http://docs.python.org/library/platform.html) module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm ru... | Basically a variant on Matthew Marshall's answer (with struct from the std.library):
```
import struct
print struct.calcsize("P") * 8
``` |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | 224 | 2009-09-10T15:14:01Z | 1,484,362 | 11 | 2009-09-27T20:14:03Z | [
"python",
"osx"
] | I need a way to tell what mode the shell is in from within the shell.
I've tried looking at the [platform](http://docs.python.org/library/platform.html) module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm ru... | For a non-programmatic solution, look in the Activity Monitor. It lists the architecture of 64-bit processes as âIntel (64-bit)â. |
How do I determine if my python shell is executing in 32bit or 64bit mode on OS X? | 1,405,913 | 224 | 2009-09-10T15:14:01Z | 10,966,396 | 144 | 2012-06-10T04:37:47Z | [
"python",
"osx"
] | I need a way to tell what mode the shell is in from within the shell.
I've tried looking at the [platform](http://docs.python.org/library/platform.html) module but it seems only to tell you about "about the bit architecture and the linkage format used for the executable": the binary is compiled as 64bit though (I'm ru... | When starting the Python interpreter in the terminal/command line you may also see a line like:
`Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32`
Where `[MSC v.1500 64 bit (AMD64)]` means 64-bit Python.
Works for my particular setup. |
Is there a Python function to determine which quarter of the year a date is in? | 1,406,131 | 43 | 2009-09-10T15:54:08Z | 1,406,182 | 86 | 2009-09-10T16:02:18Z | [
"python",
"date"
] | Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this? | Given an instance `x` of [datetime.date](http://docs.python.org/library/datetime.html?highlight=datetime#datetime.date), `(x.month-1)//3` will give you the quarter (0 for first quarter, 1 for second quarter, etc -- add 1 if you need to count from 1 instead;-).
**Edit**: originally two answers, multiply upvoted and eve... |
Is there a Python function to determine which quarter of the year a date is in? | 1,406,131 | 43 | 2009-09-10T15:54:08Z | 4,684,964 | 9 | 2011-01-13T20:34:15Z | [
"python",
"date"
] | Sure I could write this myself, but before I go reinventing the wheel is there a function that already does this? | I would suggest another arguably cleaner solution. If X is a `datetime.datetime.now()` instance, then the quarter is:
```
import math
Q=math.ceil(X.month/3.)
```
ceil has to be imported from math module as it can't be accessed directly. |
How do I get rid of Python Tkinter root window? | 1,406,145 | 24 | 2009-09-10T15:56:42Z | 1,407,668 | 8 | 2009-09-10T20:54:41Z | [
"python",
"winapi",
"tkinter",
"tk"
] | Do you know a smart way to hide or in any other way get rid of the root window that appears, opened by `Tk()`? I would like just to use a normal dialog.
Should I skip the dialog and put all my components in the root window? Is it possible or desirable? Or is there a smarter solution? | I haven't tested since I don't have any Python/TKinter environment, but try this.
In pure Tk there's a method called "wm" to manage the windows. There you can do something like "wm withdraw .mywindow" where '.mywindow' is a toplevel.
In TkInter you should be able to do something similar to:
```
root = Tkinter.Tk()
r... |
How do I get rid of Python Tkinter root window? | 1,406,145 | 24 | 2009-09-10T15:56:42Z | 1,407,700 | 35 | 2009-09-10T21:02:32Z | [
"python",
"winapi",
"tkinter",
"tk"
] | Do you know a smart way to hide or in any other way get rid of the root window that appears, opened by `Tk()`? I would like just to use a normal dialog.
Should I skip the dialog and put all my components in the root window? Is it possible or desirable? Or is there a smarter solution? | Probably the vast majority of of tk-based applications place all the components in the default root window. This is the most convenient way to do it since it already exists. Choosing to hide the default window and create your own is a perfectly fine thing to do, though it requires just a tiny bit of extra work.
To ans... |
Splitting a string with no line breaks into a list of lines with a maximum column count | 1,406,493 | 6 | 2009-09-10T16:59:30Z | 1,406,526 | 12 | 2009-09-10T17:05:17Z | [
"python",
"text-manipulation"
] | I have a long string (multiple paragraphs) which I need to split into a list of line strings. The determination of what makes a "line" is based on:
* The number of characters in the line is less than or equal to X (where X is a fixed number of columns per line\_)
* OR, there is a newline in the original string (that w... | **EDIT**
What you are looking for is [textwrap](http://docs.python.org/library/textwrap.html#module-textwrap), but that's only part of the solution not the complete one. To take newline into account you need to do this:
```
from textwrap import wrap
'\n'.join(['\n'.join(wrap(block, width=50)) for block in text.splitl... |
Non-critical unittest failures | 1,406,552 | 3 | 2009-09-10T17:11:51Z | 1,406,570 | 7 | 2009-09-10T17:16:11Z | [
"python",
"unit-testing"
] | I'm using Python's built-in [unittest](http://docs.python.org/library/unittest.html) module and I want to write a few tests that are not critical.
I mean, if my program passes such tests, that's great! However, if it doesn't pass, it's not really a problem, the program will still work.
For example, my program is desi... | As a practical matter, I'd probably use print statements to indicate failure in that case. A more correct solution is to use warnings:
<http://docs.python.org/library/warnings.html>
You could, however, use the logging facility to generate a more detailed record of your test results (i.e. set your "B" class failures t... |
What is Facebook's new Tornado framework? | 1,406,912 | 15 | 2009-09-10T18:24:25Z | 1,406,930 | 13 | 2009-09-10T18:27:38Z | [
"python",
"facebook",
"tornado"
] | Facebook just open-sourced [a framework called Tornado](http://developers.facebook.com/opensource.php).
What is it? What does it help a site do?
I believe Facebook uses a LAMP structure. Is it useful for smaller sites which are written under the LAMP stack? | It looks like it is a web-server optimized for high-concurrency and high-scalability, but made for smaller payloads.
It was designed to support 10,000 concurrent users well.
> The framework is distinct from most
> mainstream web server frameworks (and
> certainly most Python frameworks)
> because it is non-blocking a... |
How do I regex match with grouping with unknown number of groups | 1,407,435 | 13 | 2009-09-10T20:06:45Z | 1,407,457 | 12 | 2009-09-10T20:12:21Z | [
"python",
"regex"
] | I want to do a regex match (in Python) on the output log of a program. The log contains some lines that look like this:
```
...
VALUE 100 234 568 9233 119
...
VALUE 101 124 9223 4329 1559
...
```
I would like to capture the list of numbers that occurs after the first incidence of the line that starts with VALUE. i.... | What you're looking for is a *parser*, instead of a regular expression match. In your case, I would consider using a very simple parser, [`split()`](http://docs.python.org/library/stdtypes.html#str.split):
```
s = "VALUE 100 234 568 9233 119"
a = s.split()
if a[0] == "VALUE":
print [int(x) for x in a[1:]]
```
You... |
Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file? | 1,407,474 | 23 | 2009-09-10T20:14:44Z | 1,407,835 | 14 | 2009-09-10T21:29:32Z | [
"python",
"logging"
] | I'm using the standard python (2.5.2) logging module, specifically the RotatingFileHandler, on a linux system. My application supports both a command-line interface and a web-service interface. I would like to have both write to the same log file. However, when the log file gets rotated, the new file has 644 permission... | I resorted to scanning the logging.handlers module and was unable to see any way to specify a different file permissions mode. So, I have a solution now based on extending the RotatingFileHandler as a custom handler. It was fairly painless, once I found some nice references to creating one. The code for the custom hand... |
Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file? | 1,407,474 | 23 | 2009-09-10T20:14:44Z | 6,779,307 | 20 | 2011-07-21T16:16:39Z | [
"python",
"logging"
] | I'm using the standard python (2.5.2) logging module, specifically the RotatingFileHandler, on a linux system. My application supports both a command-line interface and a web-service interface. I would like to have both write to the same log file. However, when the log file gets rotated, the new file has 644 permission... | Here is a slightly better solution. this overrides the \_open method that is used. setting the umask before creating then returning it back to what it was.
```
class GroupWriteRotatingFileHandler(logging.handlers.RotatingFileHandler):
def _open(self):
prevumask=os.umask(0o002)
#os.fdopen(os.ope... |
Is there a Rake equivalent in Python? | 1,407,837 | 69 | 2009-09-10T21:29:57Z | 1,407,850 | 25 | 2009-09-10T21:32:26Z | [
"python",
"build-automation"
] | Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python? | [Paver](http://paver.github.com/paver/) has a similar set of goals, though I don't really know how it compares. |
Is there a Rake equivalent in Python? | 1,407,837 | 69 | 2009-09-10T21:29:57Z | 12,166,213 | 13 | 2012-08-28T19:30:04Z | [
"python",
"build-automation"
] | Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python? | Shovel seems promising:
[Shovel â Rake for Python](http://devblog.seomoz.org/2012/03/shovel-rake-for-python/)
<https://github.com/seomoz/shovel> |
Is there a Rake equivalent in Python? | 1,407,837 | 69 | 2009-09-10T21:29:57Z | 17,372,701 | 30 | 2013-06-28T19:57:57Z | [
"python",
"build-automation"
] | Rake is a software build tool written in Ruby (like ant or make), and so all its files are written in this language. Does something like this exist in Python? | [Invoke](http://docs.pyinvoke.org/en/latest/) â [Fabric](http://docs.fabfile.org/en/latest) without the SSH dependencies.
The [Fabric roadmap](http://docs.fabfile.org/en/1.6/roadmap.html) discusses that [Fabric](http://docs.fabfile.org/en/latest) 1.x will be split into three portions:
1. [Invoke](http://docs.pyinvo... |
Thread local storage in Python | 1,408,171 | 32 | 2009-09-10T23:03:33Z | 1,408,178 | 11 | 2009-09-10T23:05:44Z | [
"python",
"multithreading",
"thread-local-storage"
] | How do I use thread local storage in Python?
### Related
* [What is âthread local storageâ in Python, and why do I need it?](http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it) - This thread appears to be focused more on when variables are shared.
* [Efficient wa... | As noted in the question, Alex Martelli gives a solution [here](http://stackoverflow.com/questions/1403471/efficient-way-to-determine-whether-a-particular-function-is-on-the-stack-in-pytho/1403485#1403485). This function allows us to use a factory function to generate a default value for each thread.
```
#Code origina... |
Thread local storage in Python | 1,408,171 | 32 | 2009-09-10T23:03:33Z | 13,240,093 | 53 | 2012-11-05T20:46:39Z | [
"python",
"multithreading",
"thread-local-storage"
] | How do I use thread local storage in Python?
### Related
* [What is âthread local storageâ in Python, and why do I need it?](http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it) - This thread appears to be focused more on when variables are shared.
* [Efficient wa... | Thread local storage is useful for instance if you have a thread worker pool and each thread needs access to its own resource, like a network or database connection. Note that the `threading` module uses the regular concept of threads (which have access to the process global data), but these are not too useful due to t... |
Thread local storage in Python | 1,408,171 | 32 | 2009-09-10T23:03:33Z | 29,781,795 | 9 | 2015-04-21T19:49:46Z | [
"python",
"multithreading",
"thread-local-storage"
] | How do I use thread local storage in Python?
### Related
* [What is âthread local storageâ in Python, and why do I need it?](http://stackoverflow.com/questions/104983/what-is-thread-local-storage-in-python-and-why-do-i-need-it) - This thread appears to be focused more on when variables are shared.
* [Efficient wa... | Thread-local storage can simply be thought of as a namespace (with values accessed via attribute notation). The difference is that each thread transparently gets its own set of attributes/values, so that one thread doesn't see the values from another thread.
Just like an ordinary object, you can create multiple `threa... |
Get file creation time with Python on linux | 1,408,272 | 18 | 2009-09-10T23:35:39Z | 1,408,281 | 25 | 2009-09-10T23:38:21Z | [
"python",
"linux"
] | os.stat returns st\_mtime and st\_ctime attributes, the modification time is st\_mtime and st\_ctime "change time" on POSIX.
is there any function that return the creation time of a file using python and under Linux? | [You probably](http://www.faqs.org/faqs/unix-faq/faq/part3/section-1.html) [can't.](http://linux.die.net/man/2/stat):
> 3.1) How do I find the creation time of a file?
>
> You can't - it isn't stored anywhere. Files have a last-modified
> time (shown by "ls -l"), a last-accessed time (shown by "ls -lu")
> and an inode... |
Get file creation time with Python on linux | 1,408,272 | 18 | 2009-09-10T23:35:39Z | 1,408,287 | 13 | 2009-09-10T23:39:19Z | [
"python",
"linux"
] | os.stat returns st\_mtime and st\_ctime attributes, the modification time is st\_mtime and st\_ctime "change time" on POSIX.
is there any function that return the creation time of a file using python and under Linux? | try:
```
st_birthtime
```
It isnt' guaranteed to be available on all systems though. From the docs:
> On some Unix systems (such as Linux),
> the following attributes may also be
> available: st\_blocks (number of blocks
> allocated for file), st\_blksize
> (filesystem blocksize), st\_rdev (type
> of device if an in... |
NumPy array slice using None | 1,408,311 | 12 | 2009-09-10T23:45:07Z | 1,408,435 | 16 | 2009-09-11T00:29:39Z | [
"python",
"arrays",
"numpy"
] | This had me scratching my head for a while. I was unintentionally slicing an array with None and getting something other than an error (I expected an error). Instead, it returns an array with an extra dimension.
```
>>> import numpy
>>> a = numpy.arange(4).reshape(2,2)
>>> a
array([[0, 1],
[2, 3]])
>>> a[None]
... | Using None is equivalent to using `numpy.newaxis`, so yes, it's intentional. In fact, they're the same thing, but, of course, `newaxis` spells it out better.
[The docs](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis)
[A related SO question](http://stackoverflow.com/questions/944863/numpy... |
send an arbitrary number of inputs from python to a .exe | 1,408,326 | 2 | 2009-09-10T23:48:56Z | 1,408,346 | 7 | 2009-09-10T23:55:37Z | [
"python",
"executable"
] | ```
p = subprocess.Popen(args = "myprog.exe" + " " +
str(input1) + " " +
str(input2) + " " +
str(input3) + " " +
strpoints, stdout = subprocess.PIPE)
```
in the code above, input1, input2, and input3 are all integers that get converted... | args can be a sequence:
```
p = subprocess.Popen(args = ["myprog.exe"] +
[str(x) for x in [input1,input2,input3]] +
strpoints,stdout = subprocess.PIPE)
```
This is more correct if your arguments contain shell metacharacters e.g. ' \* and you don't want them in... |
Keyboard Interrupts with python's multiprocessing Pool | 1,408,356 | 78 | 2009-09-10T23:59:35Z | 1,408,476 | 90 | 2009-09-11T00:45:17Z | [
"python",
"multiprocessing",
"pool",
"keyboardinterrupt"
] | How can I handle KeyboardInterrupt events with python's multiprocessing Pools? Here is a simple example:
```
from multiprocessing import Pool
from time import sleep
from sys import exit
def slowly_square(i):
sleep(1)
return i*i
def go():
pool = Pool(8)
try:
results = pool.map(slowly_square, r... | This is a Python bug. When waiting for a condition in threading.Condition.wait(), KeyboardInterrupt is never sent. Repro:
```
import threading
cond = threading.Condition(threading.Lock())
cond.acquire()
cond.wait(None)
print "done"
```
The KeyboardInterrupt exception won't be delivered until wait() returns, and it ne... |
Keyboard Interrupts with python's multiprocessing Pool | 1,408,356 | 78 | 2009-09-10T23:59:35Z | 2,561,809 | 13 | 2010-04-01T16:06:35Z | [
"python",
"multiprocessing",
"pool",
"keyboardinterrupt"
] | How can I handle KeyboardInterrupt events with python's multiprocessing Pools? Here is a simple example:
```
from multiprocessing import Pool
from time import sleep
from sys import exit
def slowly_square(i):
sleep(1)
return i*i
def go():
pool = Pool(8)
try:
results = pool.map(slowly_square, r... | For some reasons, only exceptions inherited from the base `Exception` class are handled normally. As a workaround, you may re-raise your `KeyboardInterrupt` as an `Exception` instance:
```
from multiprocessing import Pool
import time
class KeyboardInterruptError(Exception): pass
def f(x):
try:
time.sleep... |
Keyboard Interrupts with python's multiprocessing Pool | 1,408,356 | 78 | 2009-09-10T23:59:35Z | 6,191,991 | 30 | 2011-05-31T18:39:47Z | [
"python",
"multiprocessing",
"pool",
"keyboardinterrupt"
] | How can I handle KeyboardInterrupt events with python's multiprocessing Pools? Here is a simple example:
```
from multiprocessing import Pool
from time import sleep
from sys import exit
def slowly_square(i):
sleep(1)
return i*i
def go():
pool = Pool(8)
try:
results = pool.map(slowly_square, r... | From what I have recently found, the best solution is to set up the worker processes to ignore SIGINT altogether, and confine all the cleanup code to the parent process. This fixes the problem for both idle and busy worker processes, and requires no error handling code in your child processes.
```
import signal
...
... |
How can you profile a parallelized Python script? | 1,408,393 | 9 | 2009-09-11T00:15:21Z | 1,408,533 | 8 | 2009-09-11T01:11:09Z | [
"python",
"profile",
"parallel-processing",
"multiprocessing"
] | Suppose I have a python script called `my_parallel_script.py` that involves using `multiprocessing` to parallelize several things and I run it with the following command:
```
python -m cProfile my_parallel_script.py
```
This generates profiling output for the **parent process** only. Calls made in child processes are... | cProfile only works within a single process, so you will not automatically get the child process profiled.
I would recommend that you tweak the child process code so that you can invoke it separately as a single process. Then run it under the profiler. You probably don't need to run your system multi-process while pro... |
Getting another program's output as input on the fly | 1,408,678 | 9 | 2009-09-11T02:12:28Z | 1,408,730 | 8 | 2009-09-11T02:43:34Z | [
"python",
"c",
"linux",
"bash",
"stdio"
] | I've two programs I'm using in this way:
```
$ c_program | python_program.py
```
c\_program prints something using `printf()` and python\_program.py reads using `sys.stdin.readline()`
I'd like to make the python\_program.py process c\_program's output as it prints, immediately, so that it can print its own current o... | What you need is for your C program to call fflush(stdout) after every line. For example, with the GNU grep tool, you can invoke the option '--line-buffered', which causes this behavior. See **[fflush](http://www.thinkage.ca/english/gcos/expl/nsc/lib/fflush.html)**. |
Getting another program's output as input on the fly | 1,408,678 | 9 | 2009-09-11T02:12:28Z | 1,408,829 | 17 | 2009-09-11T03:27:43Z | [
"python",
"c",
"linux",
"bash",
"stdio"
] | I've two programs I'm using in this way:
```
$ c_program | python_program.py
```
c\_program prints something using `printf()` and python\_program.py reads using `sys.stdin.readline()`
I'd like to make the python\_program.py process c\_program's output as it prints, immediately, so that it can print its own current o... | Just set stdout to be line buffered at the beginning of your C program (before performing any output), like this:
```
#include <stdio.h>
setvbuf(stdout, NULL, _IOLBF, 0);
```
or
```
#include <stdio.h>
setlinebuf(stdout);
```
Either one will work on Linux, but `setvbuf` is part of the C standard so it will work on m... |
Getting the the keyword arguments actually passed to a Python method | 1,408,818 | 16 | 2009-09-11T03:21:12Z | 1,408,860 | 9 | 2009-09-11T03:37:44Z | [
"python",
"arguments",
"keyword"
] | I'm dreaming of a Python method with explicit keyword args:
```
def func(a=None, b=None, c=None):
for arg, val in magic_arg_dict.items(): # Where do I get the magic?
print '%s: %s' % (arg, val)
```
I want to get a dictionary of only those arguments the caller actually passed into the method, just like `... | Here is the easiest and simplest way:
```
def func(a=None, b=None, c=None):
args = locals().copy()
print args
func(2, "egg")
```
This give the output: `{'a': 2, 'c': None, 'b': 'egg'}`.
The reason `args` should be a copy of the `locals` dictionary is that dictionaries are mutable, so if you created any local... |
Getting the the keyword arguments actually passed to a Python method | 1,408,818 | 16 | 2009-09-11T03:21:12Z | 1,409,284 | 22 | 2009-09-11T06:25:43Z | [
"python",
"arguments",
"keyword"
] | I'm dreaming of a Python method with explicit keyword args:
```
def func(a=None, b=None, c=None):
for arg, val in magic_arg_dict.items(): # Where do I get the magic?
print '%s: %s' % (arg, val)
```
I want to get a dictionary of only those arguments the caller actually passed into the method, just like `... | I was inspired by lost-theory's decorator goodness, and after playing about with it for a bit came up with this:
```
def actual_kwargs():
"""
Decorator that provides the wrapped function with an attribute 'actual_kwargs'
containing just those keyword arguments actually passed in to the function.
"""
... |
django templates: include and extends | 1,408,925 | 54 | 2009-09-11T04:08:38Z | 1,408,937 | 69 | 2009-09-11T04:13:46Z | [
"python",
"django",
"django-templates"
] | I would like to provide the same content inside 2 different base files.
So I'm trying to do this:
page1.html:
```
{% extends "base1.html" %}
{% include "commondata.html" %}
```
page2.html:
```
{% extends "base2.html" %}
{% include "commondata.html" %}
```
The problem is that I can't seem to use both extends and ... | When you use the extends template tag, you're saying that the current template extends another -- that it is a child template, dependent on a parent template. Django will look at your child template and use its content to populate the parent.
Everything that you want to use in a child template should be within blocks,... |
django templates: include and extends | 1,408,925 | 54 | 2009-09-11T04:08:38Z | 1,409,113 | 7 | 2009-09-11T05:21:24Z | [
"python",
"django",
"django-templates"
] | I would like to provide the same content inside 2 different base files.
So I'm trying to do this:
page1.html:
```
{% extends "base1.html" %}
{% include "commondata.html" %}
```
page2.html:
```
{% extends "base2.html" %}
{% include "commondata.html" %}
```
The problem is that I can't seem to use both extends and ... | More info about why it wasn't working for me in case it helps future people:
The reason why it wasn't working is that {% include %} in django doesn't like special characters like fancy apostrophe. The template data I was trying to include was pasted from word. I had to manually remove all of these special characters a... |
django templates: include and extends | 1,408,925 | 54 | 2009-09-11T04:08:38Z | 13,298,495 | 53 | 2012-11-08T21:55:20Z | [
"python",
"django",
"django-templates"
] | I would like to provide the same content inside 2 different base files.
So I'm trying to do this:
page1.html:
```
{% extends "base1.html" %}
{% include "commondata.html" %}
```
page2.html:
```
{% extends "base2.html" %}
{% include "commondata.html" %}
```
The problem is that I can't seem to use both extends and ... | From Django docs:
> The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely... |
How do I hide the field label for a HiddenInput widget in Django Admin? | 1,408,940 | 16 | 2009-09-11T04:15:15Z | 4,246,248 | 33 | 2010-11-22T14:12:59Z | [
"python",
"django",
"django-admin"
] | I've got a bit of Django form code that looks like this:
```
class GalleryAdminForm(forms.ModelForm):
auto_id=False
order = forms.CharField(widget=forms.HiddenInput())
```
And that makes the form field go away, but it leaves the label "Order" in the Django admin page. If I use:
```
order = forms.CharField(wi... | I can't believe several people have suggested using jQuery for this...
Is it a case of: when the only tool you know is a hammer everything looks like a nail?
Come on, if you're going to do it from the client-side (instead of fixing the source of the problem in the back-end code) surely the right place to do it would ... |
How do I hide the field label for a HiddenInput widget in Django Admin? | 1,408,940 | 16 | 2009-09-11T04:15:15Z | 12,171,430 | 13 | 2012-08-29T05:29:49Z | [
"python",
"django",
"django-admin"
] | I've got a bit of Django form code that looks like this:
```
class GalleryAdminForm(forms.ModelForm):
auto_id=False
order = forms.CharField(widget=forms.HiddenInput())
```
And that makes the form field go away, but it leaves the label "Order" in the Django admin page. If I use:
```
order = forms.CharField(wi... | Try
{% for field in form.visible\_fields %} |
How do I hide the field label for a HiddenInput widget in Django Admin? | 1,408,940 | 16 | 2009-09-11T04:15:15Z | 12,588,805 | 30 | 2012-09-25T18:17:05Z | [
"python",
"django",
"django-admin"
] | I've got a bit of Django form code that looks like this:
```
class GalleryAdminForm(forms.ModelForm):
auto_id=False
order = forms.CharField(widget=forms.HiddenInput())
```
And that makes the form field go away, but it leaves the label "Order" in the Django admin page. If I use:
```
order = forms.CharField(wi... | Oraculum has got it right. You shouldn't be cleaning this up on the client side. If it is clutter, then you shouldn't be sending it to client at all. Building on Oraculum's answer, you should use a custom form template because you you probably still want the hidden values in the form.
```
{% for field in form.visible_... |
Set function signature in Python | 1,409,295 | 15 | 2009-09-11T06:29:05Z | 1,409,496 | 10 | 2009-09-11T07:35:49Z | [
"python",
"function"
] | Suppose I have a generic function f. I want to **programmatically** create a function f2 that behaves the same as f, but has a customised signature.
**More detail**
Given a list l and and dictionary d I want to be able to:
* Set the non-keyword arguments of f2 to the strings in l
* Set the keyword arguments of f2 to... | For your usecase, having a docstring in the class/function should work -- that will show up in help() okay, and can be set programmatically (func.\_\_doc\_\_ = "stuff").
I can't see any way of setting the actual signature. I would have thought the [functools module](http://docs.python.org/library/functools.html) would... |
Python code readability | 1,409,821 | 11 | 2009-09-11T08:58:26Z | 1,409,872 | 10 | 2009-09-11T09:12:21Z | [
"python"
] | I have a programming experience with statically typed languages. Now writing code in Python I feel difficulties with its readability. Lets say I have a class *Host*:
```
class Host(object):
def __init__(self, name, network_interface):
self.name = name
self.network_interface = network_interface
```
I don't u... | The docstring conventions are at [PEP 257](http://ftp.python.org/dev/peps/pep-0257/).
The example there follows this format for specifying arguments, you can add the types if they matter:
```
def complex(real=0.0, imag=0.0):
"""Form a complex number.
Keyword arguments:
real -- the real part (default 0.0)... |
Python code readability | 1,409,821 | 11 | 2009-09-11T08:58:26Z | 1,409,885 | 8 | 2009-09-11T09:14:46Z | [
"python"
] | I have a programming experience with statically typed languages. Now writing code in Python I feel difficulties with its readability. Lets say I have a class *Host*:
```
class Host(object):
def __init__(self, name, network_interface):
self.name = name
self.network_interface = network_interface
```
I don't u... | The most pythonic solution is to document with examples. If possible, state what operations an object must support to be acceptable, rather than a specific type.
```
class Host(object):
def __init__(self, name, network_interface)
"""Initialise host with given name and network_interface.
network_interface --... |
Python code readability | 1,409,821 | 11 | 2009-09-11T08:58:26Z | 1,410,208 | 18 | 2009-09-11T10:43:07Z | [
"python"
] | I have a programming experience with statically typed languages. Now writing code in Python I feel difficulties with its readability. Lets say I have a class *Host*:
```
class Host(object):
def __init__(self, name, network_interface):
self.name = name
self.network_interface = network_interface
```
I don't u... | Using dynamic languages will teach you something about static languages: all the help you got from the static language that you now miss in the dynamic language, it wasn't all that helpful.
To use your example, in a static language, you'd know that the parameter was a string, and in Python you don't. So in Python you ... |
Inverse Dict in Python | 1,410,087 | 2 | 2009-09-11T10:02:32Z | 1,410,118 | 8 | 2009-09-11T10:12:23Z | [
"python",
"data-structures",
"dictionary"
] | I am trying to create a new dict using a list of values of an existing dict as individual keys.
So for example:
```
dict1 = dict({'a':[1,2,3], 'b':[1,2,3,4], 'c':[1,2]})
```
and I would like to obtain:
```
dict2 = dict({1:['a','b','c'], 2:['a','b','c'], 3:['a','b'], 4:['b']})
```
So far, I've not been able to do t... | If you are using Python 2.5 or above, use the [`defaultdict` class from the `collections`](http://docs.python.org/library/collections.html#collections.defaultdict) module; a `defaultdict` automatically creates values on the first access to a missing key, so you can use that here to create the lists for `dict2`, like th... |
What are the pros and cons of PyRo and RPyC python libs? | 1,410,328 | 13 | 2009-09-11T11:20:11Z | 1,411,448 | 17 | 2009-09-11T15:02:58Z | [
"python",
"distributed",
"pyro",
"rpyc"
] | I am looking for a remote procedure call engine for Python and I've found that [PyRo (Python Remote Object)](http://pythonhosted.org/Pyro4/) and [RPyC (Remote Python Call)](http://rpyc.wikidot.com/) are both the kind of thing I am searching for.
However, I am curious to know how they compare to each other and what ar... | I personally find them roughly equivalent, but RPyC's author ([here](http://rpyc.wikispaces.com/about)) claims more simplicity (and maybe for somebody not all that used to distributed computing he's got a point; I may be too used to it to make a good judge;-). Quoting him...:
> although PYRO has a long list of
> consi... |
Checking Python code correctness | 1,410,444 | 5 | 2009-09-11T11:56:30Z | 1,410,456 | 7 | 2009-09-11T12:00:12Z | [
"python",
"compiler-construction",
"correctness"
] | In C++ I have compiler that tell me if something wrong with my code after refactoring. How to make sure that Python code is at least correct after changes? There may be some stupid error like wrong function name etc. that pretty easy to find in compile time.
Thanks | Looks like [PyChecker](http://pychecker.sourceforge.net/) or [pylint](http://www.logilab.org/857) are what you're looking for |
copy.deepcopy vs pickle | 1,410,615 | 24 | 2009-09-11T12:39:43Z | 1,411,229 | 27 | 2009-09-11T14:27:53Z | [
"python",
"pickle",
"deep-copy"
] | I have a tree structure of widgets e.g. collection contains models and model contains widgets. I want to copy whole collection, `copy.deepcopy` is faster in comparison to 'pickle and de-pickle'ing the object but cPickle as being written in C is much faster, so
1. Why shouldn't I(we) always be using cPickle instead of ... | Problem is, pickle+unpickle can be faster (in the C implementation) because it's *less general* than deepcopy: many objects can be deepcopied but not pickled. Suppose for example that your class `A` were changed to...:
```
class A(object):
class B(object): pass
def __init__(self): self.b = self.B()
```
now, `copy... |
Is there a way to reopen a socket? | 1,410,723 | 6 | 2009-09-11T13:00:14Z | 1,410,764 | 14 | 2009-09-11T13:08:37Z | [
"python",
"sockets"
] | I create many "short-term" sockets in some code that look like that :
```
nb=1000
for i in range(nb):
sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sck.connect((adr, prt)
sck.send('question %i'%i)
sck.shutdown(SHUT_WR)
answer=sck.recv(4096)
print 'answer %i : %s' % (%i, answer)
sc... | No, this is a limitation of the underlying C sockets (and the TCP/IP protocol, for that matter). My question to you is: why are you shutting them down when you can architect your application to use them?
The problem with many short-term sockets is that shutting them down puts them in a state where they cannot be used ... |
Bypassing buffering of subprocess output with popen in C or Python | 1,410,849 | 9 | 2009-09-11T13:25:03Z | 1,411,112 | 10 | 2009-09-11T14:11:29Z | [
"python",
"c",
"buffer",
"pipe"
] | I have a general question about popen (and all related functions), applicable to all operating systems, when I write a python script or some c code and run the resulting executable from the console (win or linux), i can immediately see the output from the process. However, if I run the same executable as a forked proce... | In general, the standard C runtime library (that's running on behalf of just about every program on every system, more or less;-) detects whether stdout is a terminal or not; if not, it buffers the output (which can be a huge efficiency win, compared to unbuffered output).
If you're in control of the program that's do... |
Apache vs Twisted | 1,410,967 | 4 | 2009-09-11T13:46:13Z | 1,411,038 | 10 | 2009-09-11T14:01:03Z | [
"python",
"apache",
"twisted"
] | I know Twisted is a framework that allows you to do asynchronous non-blocking i/o but I still do not understand how that is different from what Apache server does. If anyone could explain the need for twisted, I would appreciate it.. | Twisted is a platform for developing internet applications, for handling the underlying communications and such. It doesn't "do" anything out of the box--you've got to program it.
Apache is an internet application, of sorts. Upon install, you have a working web server which can serve up static and dynamic web pages. B... |
Equivalent of Bash Backticks in Python | 1,410,976 | 67 | 2009-09-11T13:47:53Z | 1,410,997 | 71 | 2009-09-11T13:52:17Z | [
"python",
"backticks"
] | What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:
```
foo = `cat /tmp/baz`
```
What does the equivalent statement look like in Python? I've tried `os.system("cat /tmp/baz")` but that puts the result to standard out and returns to me the error code of that operat... | The most flexible way is to use the [`subprocess`](http://docs.python.org/library/subprocess.html) module:
```
import subprocess
proc = subprocess.Popen(["cat", "/tmp/baz"], stdout=subprocess.PIPE)
(out, err) = proc.communicate()
print "program output:", out
```
If you want to pass the call through the shell, for ex... |
Equivalent of Bash Backticks in Python | 1,410,976 | 67 | 2009-09-11T13:47:53Z | 1,411,004 | 65 | 2009-09-11T13:53:48Z | [
"python",
"backticks"
] | What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:
```
foo = `cat /tmp/baz`
```
What does the equivalent statement look like in Python? I've tried `os.system("cat /tmp/baz")` but that puts the result to standard out and returns to me the error code of that operat... | ```
output = os.popen('cat /tmp/baz').read()
``` |
Equivalent of Bash Backticks in Python | 1,410,976 | 67 | 2009-09-11T13:47:53Z | 1,411,035 | 23 | 2009-09-11T14:00:11Z | [
"python",
"backticks"
] | What is the equivalent of the backticks found in Ruby and Perl in Python? That is, in Ruby I can do this:
```
foo = `cat /tmp/baz`
```
What does the equivalent statement look like in Python? I've tried `os.system("cat /tmp/baz")` but that puts the result to standard out and returns to me the error code of that operat... | [sth is right](http://stackoverflow.com/a/1410997/456814). You can also use os.popen(), but where available (Python 2.4+) subprocess is generally preferable.
However, unlike some languages that encourage it, it's generally considered bad form to spawn a subprocess where you can do the same job inside the language. It'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.