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 |
|---|---|---|---|---|---|---|---|---|---|
removing the oldest element from a dictionary in python | 1,756,992 | 3 | 2009-11-18T15:56:50Z | 1,757,075 | 12 | 2009-11-18T16:06:40Z | [
"python",
"dictionary"
] | I would like to know the best way to remove the **oldest** element in a dictionary in order to control the maximum dictionary size.
**example**:
```
MAXSIZE = 4
dict = {}
def add(key,value):
if len(dict) == MAXSIZE:
old = get_oldest_key() # returns the key to the oldest item
del dict[old]
dict[key] = valu... | Python 3.1 has an ordered dict. use the class `collections.OrderedDict` to keep the elements in their order of insertions. beware that if you are overwriting an element, it keeps its place in the order, you need to delete and re-insert an element to make it last.
if you are using an older release, a patch may be avail... |
How can I run a Python program over telnet? | 1,758,276 | 2 | 2009-11-18T19:02:22Z | 1,758,297 | 10 | 2009-11-18T19:05:47Z | [
"python",
"telnet"
] | How can I run a Python program so it outputs its STDOUT and inputs its STDIN to/from a remote telnet client?
All the program does is print out text then wait for raw\_input(), repeatedly. I want a remote user to use it without needing shell access. It can be single threaded/single user. | On a Unix system, you can use [inetd](http://en.wikipedia.org/wiki/Inetd) for this. It will take care of opening the network connection for you, so your program will work as-is. |
How to produce html unit test output in Python? | 1,758,354 | 6 | 2009-11-18T19:15:23Z | 1,836,762 | 7 | 2009-12-02T23:59:49Z | [
"python",
"unit-testing",
"nose"
] | I'm looking for any way to display the results of python unit tests in an html summary. There are tools like this for Java and Ruby... haven't yet located any tools that seem to do this for Python. Are there any out there?
**JUnit html output:**
 to cycle through the old commands typed. I know its possible since it works on python on cygwin/windows.
thanks | Use the [rlcompleter](http://docs.python.org/library/rlcompleter.html) module to get both readline and completion.
Sample PYTHONSTARTUP code:
```
try:
import readline
except ImportError:
print "Module readline unavailable."
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
```
Sample .bashrc ... |
How can I account for period (AM/PM) with datetime.strptime? | 1,759,455 | 54 | 2009-11-18T22:04:41Z | 1,759,485 | 75 | 2009-11-18T22:07:33Z | [
"python",
"datetime",
"strptime"
] | Specifically I have code that simplifies to this:
```
from datetime import datetime
date_string = '2009-11-29 03:17 PM'
format = '%Y-%m-%d %H:%M %p'
my_date = datetime.strptime(date_string, format)
# This prints '2009-11-29 03:17 AM'
print my_date.strftime(format)
```
What gives? Does Python just ignore the period s... | The Python [`time.strftime` docs](https://docs.python.org/2/library/time.html#time.strftime) say:
> When used with the strptime() function, the **`%p`** directive only
> affects the output hour field if the **`%I`** directive is used to parse
> the hour.
Sure enough, changing your `%H` to `%I` makes it work. |
How can I account for period (AM/PM) with datetime.strptime? | 1,759,455 | 54 | 2009-11-18T22:04:41Z | 1,759,494 | 7 | 2009-11-18T22:08:59Z | [
"python",
"datetime",
"strptime"
] | Specifically I have code that simplifies to this:
```
from datetime import datetime
date_string = '2009-11-29 03:17 PM'
format = '%Y-%m-%d %H:%M %p'
my_date = datetime.strptime(date_string, format)
# This prints '2009-11-29 03:17 AM'
print my_date.strftime(format)
```
What gives? Does Python just ignore the period s... | Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ? |
How can I account for period (AM/PM) with datetime.strptime? | 1,759,455 | 54 | 2009-11-18T22:04:41Z | 1,759,497 | 9 | 2009-11-18T22:09:19Z | [
"python",
"datetime",
"strptime"
] | Specifically I have code that simplifies to this:
```
from datetime import datetime
date_string = '2009-11-29 03:17 PM'
format = '%Y-%m-%d %H:%M %p'
my_date = datetime.strptime(date_string, format)
# This prints '2009-11-29 03:17 AM'
print my_date.strftime(format)
```
What gives? Does Python just ignore the period s... | You used `%H` (24 hour format) instead of `%I` (12 hour format). |
How can I account for period (AM/PM) with datetime.strptime? | 1,759,455 | 54 | 2009-11-18T22:04:41Z | 1,759,498 | 16 | 2009-11-18T22:09:19Z | [
"python",
"datetime",
"strptime"
] | Specifically I have code that simplifies to this:
```
from datetime import datetime
date_string = '2009-11-29 03:17 PM'
format = '%Y-%m-%d %H:%M %p'
my_date = datetime.strptime(date_string, format)
# This prints '2009-11-29 03:17 AM'
print my_date.strftime(format)
```
What gives? Does Python just ignore the period s... | ```
format = '%Y-%m-%d %H:%M %p'
```
The format is using `%H` instead of `%I`. Since `%H` is the "24-hour" format, it's likely just discarding the `%p` information. It works just fine if you change the `%H` to `%I`. |
What Is The Best Python Zip Module To Handle Large Files? | 1,759,736 | 6 | 2009-11-18T22:57:27Z | 1,760,715 | 13 | 2009-11-19T03:32:10Z | [
"python",
"performance",
"compression",
"zip",
"extraction"
] | EDIT: Specifically compression and extraction speeds.
Any Suggestions?
Thanks | So I made a random-ish large zipfile:
```
$ ls -l *zip
-rw-r--r-- 1 aleax 5000 115749854 Nov 18 19:16 large.zip
$ unzip -l large.zip | wc
23396 93633 2254735
```
i.e., 116 MB with 23.4K files in it, and timed things:
```
$ time unzip -d /tmp large.zip >/dev/null
real 0m14.702s
user 0m2.586s
sys ... |
Limit Python VM memory | 1,760,025 | 18 | 2009-11-19T00:05:15Z | 1,760,046 | 11 | 2009-11-19T00:09:04Z | [
"python",
"memory",
"jvm"
] | I'm trying to find a way to limit the memory available for the Python VM, as the option "-Xmx" in the Java VM does. (The idea is to be able to play with the MemoryError exception)
I'm not sure this option exist but there may be a solution using a command of the OS to "isolate" a process and its memory.
Thank you. | On \*nix you can play around with the `ulimit` command, specifically the -m (max memory size) and -v (virtual memory). |
Limit Python VM memory | 1,760,025 | 18 | 2009-11-19T00:05:15Z | 5,433,168 | 33 | 2011-03-25T13:34:36Z | [
"python",
"memory",
"jvm"
] | I'm trying to find a way to limit the memory available for the Python VM, as the option "-Xmx" in the Java VM does. (The idea is to be able to play with the MemoryError exception)
I'm not sure this option exist but there may be a solution using a command of the OS to "isolate" a process and its memory.
Thank you. | On Linux I'm using the [resource](http://docs.python.org/library/resource.html) module:
```
import resource
resource.setrlimit(resource.RLIMIT_AS, (megs * 1048576L, -1L))
``` |
How to escape characters in Pango markup? | 1,760,070 | 6 | 2009-11-19T00:17:10Z | 1,798,944 | 13 | 2009-11-25T18:18:54Z | [
"python",
"gtk",
"pygtk",
"pango"
] | My program has a `gtk.TreeView` which displays a `gtk.ListStore`. The `gtk.ListStore` contains strings like this:
```
"<span size='medium'><b>"+site_title+"</b></span>"+"\n"+URL
```
Where `URL` is (obviously) a URL string. Sometimes there are characters in `URL` that cause pango to fail to parse the markup.
Is there... | [`glib.markup_escape_text`](http://www.pygtk.org/docs/pygobject/glib-functions.html#function-glib--markup-escape-text) may be a more canonical approach when using GTK. |
How can I render a ManyToManyField as checkboxes? | 1,760,421 | 23 | 2009-11-19T01:52:25Z | 1,760,476 | 30 | 2009-11-19T02:11:59Z | [
"python",
"django"
] | I'm making a game link site, where users can post links to their
favorite web game.
When people post games they are supposed to check what category the
game falls into.
I decided to allow many categories for each game since some games can
fall into many categories.
So the question is, how do I handle this in my view?
A... | ```
class GameForm(forms.ModelForm):
name = forms.CharField(max_length=15, label='Name')
url = forms.URLField(label='URL', initial='http://')
cats = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(),required=True)
class Meta:
model = Game
... |
How can I render a ManyToManyField as checkboxes? | 1,760,421 | 23 | 2009-11-19T01:52:25Z | 1,760,592 | 30 | 2009-11-19T02:52:07Z | [
"python",
"django"
] | I'm making a game link site, where users can post links to their
favorite web game.
When people post games they are supposed to check what category the
game falls into.
I decided to allow many categories for each game since some games can
fall into many categories.
So the question is, how do I handle this in my view?
A... | Here is how I solved it (Edit: and the admin thing)
## Forms:
```
cats = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Category.objects.all())
```
(It was the queryset part I couldn't find..)
## View:
```
cats = form.cleaned_data['cats']
game.cats = cats
```
And that's all the code... |
Python func_dict used to memoize; other useful tricks? | 1,760,495 | 6 | 2009-11-19T02:18:27Z | 1,760,640 | 7 | 2009-11-19T03:12:41Z | [
"python",
"dictionary",
"function",
"fibonacci",
"memoization"
] | A Python function object has an attribute dictionary called `func_dict` which is visible from outside the function and is mutable, but which is not modified when the function is called. (I learned this from answers to a question I asked yesterday (#1753232): thanks!) I was reading code (at <http://pythonprogramming.jot... | Just be careful: the `fib.cache` trick only works if `fib` is indeed the name of the relevant function object in the scope that's active while it's executing (for example, when you decorate it as you have done, you must assign the starting value for the cache to the decorator wrapper, not to the decorated function -- a... |
Numpy equivalent of MATLAB's cell array | 1,761,419 | 8 | 2009-11-19T07:03:36Z | 1,761,989 | 14 | 2009-11-19T09:27:51Z | [
"python",
"matlab",
"numpy"
] | I want to create a MATLAB-like cell array in Numpy. How can I accomplish this? | Matlab cell arrays [are most similar](http://docs.scipy.org/doc/scipy/reference/tutorial/io.html#matlab-cell-arrays) to Python lists, since they can hold any object - but scipy.io.loadmat imports them as numpy object arrays - which is an array with dtype=object.
To be honest though you are just as well off using Pytho... |
Read password from stdin | 1,761,744 | 146 | 2009-11-19T08:25:58Z | 1,761,753 | 225 | 2009-11-19T08:29:02Z | [
"python",
"passwords",
"prompt",
"interactive"
] | Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.
In bash I could get a password read in without re-prompting it on screen via
```
read -s
```
Is there something similar for Python? I.e.,
```
password = raw_input('Password: ', dont_print_... | ```
>>> import getpass
>>> pw = getpass.getpass()
``` |
Read password from stdin | 1,761,744 | 146 | 2009-11-19T08:25:58Z | 1,761,754 | 39 | 2009-11-19T08:29:10Z | [
"python",
"passwords",
"prompt",
"interactive"
] | Scenario: An interactive CLI Python program, that is in need for a password. That means also, there's no GUI solution possible.
In bash I could get a password read in without re-prompting it on screen via
```
read -s
```
Is there something similar for Python? I.e.,
```
password = raw_input('Password: ', dont_print_... | Yes, [`getpass`](http://docs.python.org/3.1/library/getpass.html): "Prompt the user for a password without echoing."
**Edit:** I had not played with this module myself yet, so this is what I just cooked up (wouldn't be surprised if you find similar code all over the place, though):
```
import getpass
def login():
... |
How to convert text into URL syntax on Python? | 1,762,123 | 4 | 2009-11-19T09:52:02Z | 1,762,156 | 10 | 2009-11-19T09:57:22Z | [
"python",
"url"
] | I want to convert python str to URL syntax.
For example
```
>>> u'íê¸'.encode('utf-8')
'\xed\x95\x9c\xea\xb8\x80' to '%ed%95%9c%ea%b8%80'
```
Thanks in advance. | ```
>>> import urllib2
>>> urllib2.quote('íê¸')
'%ED%95%9C%EA%B8%80'
``` |
How to create an ontology in python? | 1,762,291 | 12 | 2009-11-19T10:22:05Z | 1,762,848 | 7 | 2009-11-19T12:06:50Z | [
"python",
"text",
"computer-science",
"ontology"
] | Are there libraries or certain "techniques" that you can use to create an ontology of elements?
Or "design patterns"?
I am talking about just a "graph" of things.
Suppose I have a bunch of words. Certain words are "under" other words or "related" to other words. I need a good way to group them and know their relation... | You can use rdflib (<http://www.rdflib.net/>) for storing triples. You then have to make your own decisions about the kind of ontology you want to build. Look at the OWL format for that.
I toyed with python and ontologies during my PhD, so perhaps a quick scan through my thesis can give you some ideas. For instance a ... |
How to find the position of an element in a list , in Python? | 1,762,484 | 7 | 2009-11-19T10:53:59Z | 1,762,492 | 13 | 2009-11-19T10:55:07Z | [
"python",
"list"
] | ```
for s in stocks_list:
print s
```
how do I know what "position" s is in? So that I can do **stocks\_list[4]** in the future? | ```
for index, s in enumerate(stocks_list):
print index, s
``` |
How to find the position of an element in a list , in Python? | 1,762,484 | 7 | 2009-11-19T10:53:59Z | 7,532,611 | 37 | 2011-09-23T17:19:14Z | [
"python",
"list"
] | ```
for s in stocks_list:
print s
```
how do I know what "position" s is in? So that I can do **stocks\_list[4]** in the future? | If you know what you're looking for ahead of time you can use the index method:
```
>>> stocks_list = ['AAPL', 'MSFT', 'GOOG']
>>> stocks_list.index('MSFT')
1
>>> stocks_list.index('GOOG')
2
``` |
Encoding a string to ascii | 1,762,564 | 7 | 2009-11-19T11:09:32Z | 1,762,576 | 8 | 2009-11-19T11:10:46Z | [
"python",
"encoding",
"ascii"
] | I have a long string that I want to encode to ascii. I'm doing:
```
s = s.encode('ascii', 'replace')
```
but I get:
```
'ascii' codec can't decode byte 0xc3 in position 2646: ordinal not in range(128)
```
(I've also tried `'ignore'` but it doesn't help.)
What am I doing wrong? | Your string is **already encoded** with some encoding. Before encoding it to ascii, you **must decode it first**.
Python is ***implicity*** trying to decode it (That's why you get a `UnicodeDecodeError` not `UnicodeEncodeError`).
You can solve the problem by *explicity decoding your bytestring* (using the appropriate... |
Python Tesseract OCR question | 1,762,565 | 10 | 2009-11-19T11:09:34Z | 1,763,824 | 11 | 2009-11-19T14:51:37Z | [
"python",
"image-processing",
"image-manipulation",
"ocr",
"tesseract"
] | I have this image:

I want to read it to a string using python, which I didn't think would be that hard. I came upon tesseract, and then a wrapper for python scripts using tesseract.
So I started reading images, and it's done great until I tried to... | Just train the engine for the 10 digits and a '.' . That should do it. And make sure you change your image to grayscale before OCRing it. |
Why is it when I print something, there is always a unicode next to it? (Python) | 1,762,690 | 4 | 2009-11-19T11:34:27Z | 1,762,705 | 9 | 2009-11-19T11:38:35Z | [
"python"
] | ```
[u'Iphones', u'dont', u'receieve', u'messages']
```
Is there a way to print it without the "u" in front of it? | What you are seeing is the `__repr__()` representation of the unicode string which includes the u to make it clear. If you don't want the u you could print the object (using `__str__`) - this works for me:
```
print [str(x) for x in l]
```
Probably better is to read up on [python unicode](http://docs.python.org/dev/h... |
Create broken symlink with Python | 1,762,831 | 4 | 2009-11-19T12:03:53Z | 1,762,937 | 7 | 2009-11-19T12:24:41Z | [
"python",
"symlink",
"ln"
] | Using Python I want to create a symbolic link pointing to a path that does not exist. However os.symlink just complains about "OSError: [Errno 2] No such file or directory:".. This can easily be done with the *ln* program, but how to do it in Python without calling the *ln* program from Python?
**Edit:** *somehow I re... | Such error is raised when you try to create a symlink in non-existent directory. For example, the following code will fail if `/tmp/subdir` doesn't exist:
```
os.symlink('/usr/bin/python', '/tmp/subdir/python')
```
But this should run successfully:
```
src = '/usr/bin/python'
dst = '/tmp/subdir/python'
if not os.pa... |
String formatting expressions (Python) | 1,763,184 | 5 | 2009-11-19T13:09:51Z | 1,763,223 | 8 | 2009-11-19T13:16:43Z | [
"python",
"string",
"printf",
"deprecated"
] | String formatting expressions:
```
'This is %d %s example!' % (1, 'nice')
```
String formatting method calls:
```
'This is {0} {1} example!'.format(1, 'nice')
```
I personally prefer the method calls (second example) for readability but since it is new, there is some chance that one or the other of these may become... | Neither; the first one is used in a lot of places and the second one was just introduced. So the question is more which style you prefer. I actually prefer the `dict` based formatting:
```
d = { 'count': 1, 'txt': 'nice' }
'This is %(count)d %(txt)s example!' % d
```
It makes sure that the right parameter goes into t... |
Python: asynchronous tcp socketserver | 1,763,549 | 4 | 2009-11-19T14:12:28Z | 1,763,607 | 9 | 2009-11-19T14:18:19Z | [
"python",
"python-2.7",
"networking",
"asynchronous"
] | I'm looking <http://docs.python.org/library/socketserver.html> to try and handle asynchronous requests with the socketserver in python. At the very bottom there is an example, but it doesn't make sense. It says you use port 0 which assigns an arbitrary unused port. But how do you know what port to use for the client if... | Since the client is implemented in the same script as the server, the port is known. In a real-world scenario, you should specify a port for your daemon. Besides letting your clients know on which port to connect, you may also need to know so that you can open firewalls between your clients and your server. |
Conditional counting in Python | 1,764,309 | 16 | 2009-11-19T15:54:25Z | 1,764,335 | 10 | 2009-11-19T15:57:23Z | [
"python",
"arrays",
"list",
"count"
] | not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have
```
class A:
def __init__(self, a, b):
self.a = a
self.b = b
st... | ```
print sum(1 for e in L if e.b == 1)
``` |
Conditional counting in Python | 1,764,309 | 16 | 2009-11-19T15:54:25Z | 1,764,391 | 28 | 2009-11-19T16:03:10Z | [
"python",
"arrays",
"list",
"count"
] | not sure this was asked before, but I couldn't find an obvious answer. I'm trying to count the number of elements in a list that are equal to a certain value. The problem is that these elements are not of a built-in type. So if I have
```
class A:
def __init__(self, a, b):
self.a = a
self.b = b
st... | ```
sum(x.b == 1 for x in L)
```
A boolean (as resulting from comparisons such as `x.b == 1`) is also an `int`, with a value of `0` for `False`, `1` for `True`, so arithmetic such as summation works just fine.
This is the simplest code, but perhaps not the speediest (only `timeit` can tell you for sure;-). Consider (... |
Python type long vs C 'long long' | 1,764,548 | 10 | 2009-11-19T16:21:15Z | 1,764,637 | 13 | 2009-11-19T16:32:07Z | [
"python",
"64bit",
"long-integer"
] | I would like to represent a value as a 64bit signed `long`, such that values larger than (2\*\*63)-1 are represented as negative, however Python `long` has infinite precision. Is there a 'quick' way for me to achieve this? | You could use [`ctypes.c_longlong`](http://docs.python.org/3.1/library/ctypes.html#ctypes.c%5Flonglong):
```
>>> from ctypes import c_longlong as ll
>>> ll(2 ** 63 - 1)
c_longlong(9223372036854775807L)
>>> ll(2 ** 63)
c_longlong(-9223372036854775808L)
>>> ll(2 ** 63).value
-9223372036854775808L
```
This is really **o... |
Python type long vs C 'long long' | 1,764,548 | 10 | 2009-11-19T16:21:15Z | 1,767,591 | 9 | 2009-11-20T00:28:00Z | [
"python",
"64bit",
"long-integer"
] | I would like to represent a value as a 64bit signed `long`, such that values larger than (2\*\*63)-1 are represented as negative, however Python `long` has infinite precision. Is there a 'quick' way for me to achieve this? | Can you use [numpy](http://numpy.scipy.org/)? It has an int64 type that does exactly what you want.
```
In [1]: import numpy
In [2]: numpy.int64(2**63-1)
Out[2]: 9223372036854775807
In [3]: numpy.int64(2**63-1)+1
Out[3]: -9223372036854775808
```
It's transparent to users, unlike the ctypes example, and it's coded i... |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | 9 | 2009-11-19T17:28:40Z | 12,964,900 | 10 | 2012-10-18T22:44:40Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] | If I save my code files as `.pyw`, no console window appears - which is what I want - but if the code includes a call to `os.system`, I still get a pesky console window. I assume it's caused by the call to `os.system`. Is there a way to execute other files from within my `.pyw` script without raising the console window... | You should use [`subprocess.Popen`](http://docs.python.org/library/subprocess.html#popen-constructor) class passing as `startupinfo` parameter's value instance of [`subprocess.STARTUPINFO`](http://docs.python.org/library/subprocess.html#subprocess.STARTUPINFO) class with `dwFlags` attribute holding [`subprocess.STARTF_... |
How to avoid console window with .pyw file containing os.system call? | 1,765,078 | 9 | 2009-11-19T17:28:40Z | 16,057,764 | 12 | 2013-04-17T10:33:53Z | [
"python",
"windows",
"console",
"windows-console",
"pythonw"
] | If I save my code files as `.pyw`, no console window appears - which is what I want - but if the code includes a call to `os.system`, I still get a pesky console window. I assume it's caused by the call to `os.system`. Is there a way to execute other files from within my `.pyw` script without raising the console window... | The solution that Piotr describes is actually not as complicated as it may sound. Here is an example where a `startupinfo` is passed to a `check_call` invocation to suppress the console window:
```
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
subprocess.check_call(cmd,... |
Python nested classes scope | 1,765,677 | 81 | 2009-11-19T18:53:05Z | 1,765,716 | 76 | 2009-11-19T18:58:53Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] | I'm trying to understand scope in nested classes in python. Here is my example code :
```
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
```
The creation of class does not complete and I get the error :
```
<type 'exceptions.NameError'>: name 'outer_var' is not defined
`... | ```
class Outer(object):
outer_var = 1
class Inner(object):
@property
def inner_var(self):
return Outer.outer_var
```
This isn't quite the same as similar things work in other languages, and uses global lookup instead of scoping the access to `outer_var`. (If you change what object the name `Outer` ... |
Python nested classes scope | 1,765,677 | 81 | 2009-11-19T18:53:05Z | 1,765,849 | 19 | 2009-11-19T19:19:33Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] | I'm trying to understand scope in nested classes in python. Here is my example code :
```
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
```
The creation of class does not complete and I get the error :
```
<type 'exceptions.NameError'>: name 'outer_var' is not defined
`... | You might be better off if you just don't use nested classes. If you must nest, try this:
```
x = 1
class OuterClass:
outer_var = x
class InnerClass:
inner_var = x
```
Or declare both classes before nesting them:
```
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = OuterClass.ou... |
Python nested classes scope | 1,765,677 | 81 | 2009-11-19T18:53:05Z | 8,366,758 | 35 | 2011-12-03T09:26:51Z | [
"python",
"class",
"scope",
"nested",
"inner-classes"
] | I'm trying to understand scope in nested classes in python. Here is my example code :
```
class OuterClass:
outer_var = 1
class InnerClass:
inner_var = outer_var
```
The creation of class does not complete and I get the error :
```
<type 'exceptions.NameError'>: name 'outer_var' is not defined
`... | I think you can simply do:
```
class OuterClass:
outer_var = 1
class InnerClass:
pass
InnerClass.inner_var = outer_var
```
The problem you encountered is due to this:
> A block is a piece of Python program text that is executed as a unit.
> The following are blocks: a module, a function body, an... |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | 32 | 2009-11-19T19:05:26Z | 1,783,734 | 31 | 2009-11-23T15:13:06Z | [
"python",
"django",
"django-forms"
] | ## What I'm trying to do
I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.
## About competition types
Competition types are kept in a tuple. A slightly shortened example:
```
COMPETITION_TYPE_CHOICES = (... | I've found a solution that works the way I want it to without violating the DRY principle. Not very clean, but it'll have to do I suppose.
According to [the documentation](http://docs.djangoproject.com/en/dev/ref/models/fields/#choices) choices don't have to be a tuple:
> Finally, note that choices can be any
> itera... |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | 32 | 2009-11-19T19:05:26Z | 2,216,679 | 7 | 2010-02-07T10:31:52Z | [
"python",
"django",
"django-forms"
] | ## What I'm trying to do
I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.
## About competition types
Competition types are kept in a tuple. A slightly shortened example:
```
COMPETITION_TYPE_CHOICES = (... | Better choice is to update field choices in form **init** method
```
COMPETITION_TYPE_CHOICES = (
(1, 'Olympic Games'),
(2, 'ISU Championships'),
(3, 'Grand Prix Series'),
)
class CompetitionSearchForm(forms.Form):
name = forms.CharField(required=False)
type = forms.ChoiceField(choices=COMPETITIO... |
ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong? | 1,765,757 | 32 | 2009-11-19T19:05:26Z | 21,357,946 | 21 | 2014-01-26T00:10:34Z | [
"python",
"django",
"django-forms"
] | ## What I'm trying to do
I'm going to be keeping data about competitions in my database. I want to be able to search the competitions by certain criteria - competition type in particular.
## About competition types
Competition types are kept in a tuple. A slightly shortened example:
```
COMPETITION_TYPE_CHOICES = (... | I tried both Monika's and Evgeniy's solutions with no success, but Monika has a good point in that the choices do not need to be tuples. Therefore, the easiest (and DRYest) solution is to simply do what Django does already in the Model Field. Simply add the blank choice and the tuples together after converting them to ... |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | 27 | 2009-11-19T19:19:28Z | 1,768,210 | 8 | 2009-11-20T03:43:13Z | [
"python",
"beautifulsoup"
] | Currently I have code that does something like this:
```
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
```
Except I don't want to throw away the contents inside the invalid tag. How do I get rid of the tag but keep the conten... | I have a simpler solution but I don't know if there's a drawback to it.
**UPDATE:** there's a drawback, see Jesse Dhillon's comment. Also, another solution will be to use Mozilla's [Bleach](https://github.com/jsocol/bleach) instead of BeautifulSoup.
```
from BeautifulSoup import BeautifulSoup
VALID_TAGS = ['div', 'p... |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | 27 | 2009-11-19T19:19:28Z | 3,225,671 | 46 | 2010-07-12T03:25:02Z | [
"python",
"beautifulsoup"
] | Currently I have code that does something like this:
```
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
```
Except I don't want to throw away the contents inside the invalid tag. How do I get rid of the tag but keep the conten... | The strategy I used is to replace a tag with its contents if they are of type `NavigableString` and if they aren't, then recurse into them and replace their contents with `NavigableString`, etc. Try this:
```
from BeautifulSoup import BeautifulSoup, NavigableString
def strip_tags(html, invalid_tags):
soup = Beaut... |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | 27 | 2009-11-19T19:19:28Z | 8,439,761 | 41 | 2011-12-09T00:47:21Z | [
"python",
"beautifulsoup"
] | Currently I have code that does something like this:
```
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
```
Except I don't want to throw away the contents inside the invalid tag. How do I get rid of the tag but keep the conten... | Current versions of the BeautifulSoup library have an undocumented method on Tag objects called replaceWithChildren(). So, you could do something like this:
```
html = "<p>Good, <b>bad</b>, and <i>ug<b>l</b><u>y</u></i></p>"
invalid_tags = ['b', 'i', 'u']
soup = BeautifulSoup(html)
for tag in invalid_tags:
for ma... |
Remove a tag using BeautifulSoup but keep its contents | 1,765,848 | 27 | 2009-11-19T19:19:28Z | 12,989,845 | 8 | 2012-10-20T15:22:36Z | [
"python",
"beautifulsoup"
] | Currently I have code that does something like this:
```
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
tag.extract()
soup.renderContents()
```
Except I don't want to throw away the contents inside the invalid tag. How do I get rid of the tag but keep the conten... | Although this has already been mentoned by other people in the comments, I thought I'd post a full answer showing how to do it with Mozilla's Bleach. Personally, I think this is a lot nicer than using BeautifulSoup for this.
```
import bleach
html = "<b>Bad</b> <strong>Ugly</strong> <script>Evil()</script>"
clean = bl... |
Python, UnicodeDecodeError | 1,766,669 | 6 | 2009-11-19T21:22:54Z | 1,766,804 | 13 | 2009-11-19T21:47:46Z | [
"python",
"unicode"
] | I get this error:
```
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe0 in position 4: ordinal not in range(128)
```
I tried setting many different codecs (in the header, like `# -*- coding: utf8 -*-`), or even using u"string", but it still appears.
How do I fix this?
Edit: I don't know the actual character ... | We can't guess what you are trying to do, nor what's in your code, not what "setting many different codecs" means, nor what u"string" is supposed to do for you.
Please change your code to its initial state so that it reflects as best you can what you are trying to do, run it again, and then edit your question to provi... |
Read first N lines of a file in python | 1,767,513 | 55 | 2009-11-20T00:09:32Z | 1,767,589 | 81 | 2009-11-20T00:27:18Z | [
"python",
"file",
"head"
] | We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.
How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the implementatio... | ```
with open("datafile") as myfile:
head = [next(myfile) for x in xrange(N)]
print head
```
Here's another way
```
from itertools import islice
with open("datafile") as myfile:
head = list(islice(myfile, N))
print head
``` |
Read first N lines of a file in python | 1,767,513 | 55 | 2009-11-20T00:09:32Z | 1,767,879 | 11 | 2009-11-20T02:04:36Z | [
"python",
"file",
"head"
] | We have a large raw data file that we would like to trim to a specified size.
I am experienced in .net c#, however would like to do this in python to simplify things and out of interest.
How would I go about getting the first N lines of a text file in python?
Will the OS being used have any effect on the implementatio... | ```
N=10
f=open("file")
for i in range(N):
line=f.next().strip()
print line
f.close()
``` |
checksum udp calculation python | 1,767,910 | 4 | 2009-11-20T02:16:43Z | 1,769,267 | 8 | 2009-11-20T09:17:24Z | [
"python",
"networking",
"checksum",
"packet"
] | I'd like to calculate the checksum of an UDP header packet I want to send:
```
packetosend = """60 00 00 00 00 24 3a 40 20 02 c0 a8 01 50 00 01 00 00
00 00 00 00 09 38 20 02 c0 a8 01 50 00 01 00 00 00 00 00 00 09 6f"""
```
so I need to join this utf-16 (not a problem) and calculate the checksum of **this** specific ... | This doesn't look like a UDP packet to me. It looks like an IPv6 header for an ICMPv6 packet, but the actual payload of the packet is missing.
IPv6 headers [do not contain a checksum](http://mailman.isi.edu/pipermail/6bone/2002-November/006839.html).
For [ICMP](http://www.networksorcery.com/enp/protocol/icmp.htm), th... |
Why am I getting this error in python ? (httplib) | 1,767,934 | 21 | 2009-11-20T02:24:19Z | 1,767,954 | 23 | 2009-11-20T02:31:41Z | [
"python",
"http"
] | ```
if theurl.startswith("http://"): theurl = theurl[7:]
head = theurl[:theurl.find('/')]
tail = theurl[theurl.find('/'):]
response_code = 0
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
response_code = int(res.status)
http://www.garageband.com/mp3cat/.UZ... | From the documentation for [httplib (Python 2)](https://docs.python.org/2/library/httplib.html) (called [http.client in Python 3](https://docs.python.org/3/library/http.client.html)):
> *exception* `httplib.`**`BadStatusLine`**: (*exception* `http.client.`**`BadStatusLine`**:)
>
> > A subclass of `HTTPException`.
> >
... |
Why am I getting this error in python ? (httplib) | 1,767,934 | 21 | 2009-11-20T02:24:19Z | 1,767,959 | 7 | 2009-11-20T02:33:15Z | [
"python",
"http"
] | ```
if theurl.startswith("http://"): theurl = theurl[7:]
head = theurl[:theurl.find('/')]
tail = theurl[theurl.find('/'):]
response_code = 0
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
response_code = int(res.status)
http://www.garageband.com/mp3cat/.UZ... | The Python Standard Library: [httplib (Python 2)](https://docs.python.org/2/library/httplib.html) (called [http.client in Python 3](https://docs.python.org/3/library/http.client.html)):
> `exception httplib.BadStatusLine`
> A subclass of HTTPException. Raised if a server responds with a HTTP status code that we donâ... |
Why am I getting this error in python ? (httplib) | 1,767,934 | 21 | 2009-11-20T02:24:19Z | 19,017,158 | 21 | 2013-09-26T00:02:36Z | [
"python",
"http"
] | ```
if theurl.startswith("http://"): theurl = theurl[7:]
head = theurl[:theurl.find('/')]
tail = theurl[theurl.find('/'):]
response_code = 0
import httplib
conn = httplib.HTTPConnection(head)
conn.request("HEAD",tail)
res = conn.getresponse()
response_code = int(res.status)
http://www.garageband.com/mp3cat/.UZ... | I recently got this error, in a situation where the method that contained the http request ran successfully once, and then threw this exception (with the status code as an empty string) the second time the method was called (with a different URL). I had a debugging advantage because this is calling my own REST api, so ... |
How to make python_select work for '$>python' command? | 1,768,881 | 2 | 2009-11-20T07:23:12Z | 1,769,070 | 7 | 2009-11-20T08:37:54Z | [
"python",
"osx",
"mysql"
] | I installed a couple of pythons in different versions with macports, and the apple python 2.6 is also working. Now I need to run a program which requires MySQLdb package support in python, and this package was installed to the python I installed by macports. The program tells me that there is no MySQLdb installed, so I... | By default, MacPorts installs user programs (or links to them) in `/opt/local/bin`. The MacPorts `select_python` command selects which python instance is linked to `/opt/local/bin/python`. It has no effect (nor should it) on what Apple installs in `/usr/bin`, which is where the Apple-supplied `python` and `python2.x` c... |
Script to remove python comments/docstrings | 1,769,332 | 5 | 2009-11-20T09:28:37Z | 1,769,577 | 8 | 2009-11-20T10:23:52Z | [
"python",
"comments"
] | Is there a python script or tool available which can remove comments and docstrings from python source?
it should take care of cases like
```
"""
aas
"""
def f():
m = {
u'x':
u'y'
} # faake docstring ;)
if 1:
'string' >> m
if 2:
'string' , m
if 3:
's... | This does the job:
```
""" Strip comments and docstrings from a file.
"""
import sys, token, tokenize
def do_file(fname):
""" Run on just one file.
"""
source = open(fname)
mod = open(fname + ",strip", "w")
prev_toktype = token.INDENT
first_line = None
last_lineno = -1
last_col = 0
... |
Script to remove python comments/docstrings | 1,769,332 | 5 | 2009-11-20T09:28:37Z | 2,962,727 | 8 | 2010-06-03T01:05:02Z | [
"python",
"comments"
] | Is there a python script or tool available which can remove comments and docstrings from python source?
it should take care of cases like
```
"""
aas
"""
def f():
m = {
u'x':
u'y'
} # faake docstring ;)
if 1:
'string' >> m
if 2:
'string' , m
if 3:
's... | I'm the author of the "*mygod, he has written a python interpreter using regex...*" (i.e. pyminifier) mentioned [at that link below](http://stackoverflow.com/questions/1769332/script-to-remove-python-comments-docstrings#comment1653880_1769362) =).
I just wanted to chime in and say that I've improved the code quite a ... |
Understanding kwargs in Python | 1,769,403 | 397 | 2009-11-20T09:40:57Z | 1,769,452 | 40 | 2009-11-20T09:51:25Z | [
"python",
"kwargs"
] | What are the uses for `**kwargs` in Python?
I know you can do an `objects.filter` on a table and pass in a `**kwargs` argument.
Can I also do this for specifying time deltas i.e. `timedelta(hours = time1)`?
How exactly does it work? Is it classes as 'unpacking'? Like `a,b=1,2`? | kwargs is just a dictionary that is added to the parameters.
A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.
The whatfor is not so simple.
For example (very hypothetical) you have an interface that just calls other routines to do the job:
```
def myDo(what, where, why):
if wh... |
Understanding kwargs in Python | 1,769,403 | 397 | 2009-11-20T09:40:57Z | 1,769,475 | 454 | 2009-11-20T09:58:18Z | [
"python",
"kwargs"
] | What are the uses for `**kwargs` in Python?
I know you can do an `objects.filter` on a table and pass in a `**kwargs` argument.
Can I also do this for specifying time deltas i.e. `timedelta(hours = time1)`?
How exactly does it work? Is it classes as 'unpacking'? Like `a,b=1,2`? | You can use `**kwargs` to let your functions take an arbitrary number of keyword arguments ("kwargs" means "keyword arguments"):
```
>>> def print_keyword_args(**kwargs):
... # kwargs is a dict of the keyword args passed to the function
... for key, value in kwargs.iteritems():
... print "%s = %s" % (k... |
Understanding kwargs in Python | 1,769,403 | 397 | 2009-11-20T09:40:57Z | 1,769,478 | 182 | 2009-11-20T09:59:16Z | [
"python",
"kwargs"
] | What are the uses for `**kwargs` in Python?
I know you can do an `objects.filter` on a table and pass in a `**kwargs` argument.
Can I also do this for specifying time deltas i.e. `timedelta(hours = time1)`?
How exactly does it work? Is it classes as 'unpacking'? Like `a,b=1,2`? | ## Unpacking dictionaries
`**` unpacks dictionaries.
This
```
func(a=1, b=2, c=3)
```
is the same as
```
args = {'a': 1, 'b': 2, 'c':3}
func(**args)
```
It's useful if you have to construct parameters:
```
args = {'name': person.name}
if hasattr(person, "address"):
args["address"] = person.address
func(**arg... |
Understanding kwargs in Python | 1,769,403 | 397 | 2009-11-20T09:40:57Z | 20,944,666 | 15 | 2014-01-06T06:57:50Z | [
"python",
"kwargs"
] | What are the uses for `**kwargs` in Python?
I know you can do an `objects.filter` on a table and pass in a `**kwargs` argument.
Can I also do this for specifying time deltas i.e. `timedelta(hours = time1)`?
How exactly does it work? Is it classes as 'unpacking'? Like `a,b=1,2`? | **Motif: `*args` and `**kwargs` serves as a placeholder for the arguments that need to be passed to a function call**
using `*args` and `**kwargs` to call a function
```
def args_kwargs_test(arg1, arg2, arg3):
print "arg1:", arg1
print "arg2:", arg2
print "arg3:", arg3
```
Now we'll use `*args` to call t... |
Understanding kwargs in Python | 1,769,403 | 397 | 2009-11-20T09:40:57Z | 21,338,152 | 27 | 2014-01-24T16:56:02Z | [
"python",
"kwargs"
] | What are the uses for `**kwargs` in Python?
I know you can do an `objects.filter` on a table and pass in a `**kwargs` argument.
Can I also do this for specifying time deltas i.e. `timedelta(hours = time1)`?
How exactly does it work? Is it classes as 'unpacking'? Like `a,b=1,2`? | On the basis that a good sample is sometimes better than a long discourse I will write two functions using all python variable argument passing facilities (both positional and named arguments). You should easily be able to see what it does by yourself:
```
def f(a = 0, *args, **kwargs):
print("Received by f(a, *ar... |
Understanding kwargs in Python | 1,769,403 | 397 | 2009-11-20T09:40:57Z | 28,715,715 | 7 | 2015-02-25T09:45:23Z | [
"python",
"kwargs"
] | What are the uses for `**kwargs` in Python?
I know you can do an `objects.filter` on a table and pass in a `**kwargs` argument.
Can I also do this for specifying time deltas i.e. `timedelta(hours = time1)`?
How exactly does it work? Is it classes as 'unpacking'? Like `a,b=1,2`? | As an addition, you can also mix different ways of usage when calling kwargs functions:
```
def test(**kwargs):
print kwargs['a']
print kwargs['b']
print kwargs['c']
args = { 'b': 2, 'c': 3}
test( a=1, **args )
```
gives this output:
```
1
2
3
```
Note that \*\*kwargs has to be the last argument |
parse query string with urllib in Python 2.4 | 1,769,625 | 11 | 2009-11-20T10:34:03Z | 1,769,643 | 23 | 2009-11-20T10:39:02Z | [
"python",
"parsing",
"urllib"
] | Using Python2.4.5 (don't ask!) I want to parse a query string and get a dict in return. Do I have to do it "manually" like follows?
```
>>> qs = 'first=1&second=4&third=3'
>>> d = dict([x.split("=") for x in qs.split("&")])
>>> d
{'second': '4', 'third': '3', 'first': '1'}
```
Didn't find any useful method in `urlpar... | You have two options:
```
>>> cgi.parse_qs(qs)
{'second': ['4'], 'third': ['3'], 'first': ['1']}
```
or
```
>>> cgi.parse_qsl(qs)
[('first', '1'), ('second', '4'), ('third', '3')]
```
The values in the dict returned by `cgi.parse_qs()` are lists rather than strings, in order to handle the case when the same paramet... |
parse query string with urllib in Python 2.4 | 1,769,625 | 11 | 2009-11-20T10:34:03Z | 19,214,238 | 9 | 2013-10-06T21:35:22Z | [
"python",
"parsing",
"urllib"
] | Using Python2.4.5 (don't ask!) I want to parse a query string and get a dict in return. Do I have to do it "manually" like follows?
```
>>> qs = 'first=1&second=4&third=3'
>>> d = dict([x.split("=") for x in qs.split("&")])
>>> d
{'second': '4', 'third': '3', 'first': '1'}
```
Didn't find any useful method in `urlpar... | this solves the annoyance:
```
d = dict(urlparse.parse_qsl( qs ) )
```
personally i would expect there two be a built in wrapper in urlparse. in most cases i wouldn't mind to discards the redundant parameter if such exist |
General Purpose Progressbar in Django | 1,770,205 | 8 | 2009-11-20T12:38:23Z | 1,770,379 | 9 | 2009-11-20T13:19:51Z | [
"javascript",
"jquery",
"python",
"django",
"progress-bar"
] | I want to make a little web-frontend for copying (rsync) and encoding (ffmpeg) files for my Server using Django.
And I want to keep track of the progress of the processes.
I saw a few jquery-scripts, but they are designed to be used with uploads, and I don't know enough javascript to modify these scripts for my need... | See the code here <http://www.djangosnippets.org/snippets/679/>, it says "upload progress for multipart forms" but there is nothing specific to forms, you can use it anywhere with few tweaks.
General concept is:
1. Write a web-service which can return data(e.g. JSON) about the progress.
2. On client side use JavaScri... |
Run child processes as different user from a long running process | 1,770,209 | 26 | 2009-11-20T12:39:09Z | 1,770,247 | 9 | 2009-11-20T12:49:01Z | [
"python",
"fork",
"subprocess",
"setuid"
] | I've got a long running, daemonized Python process that uses subprocess to spawn new child processes when certain events occur. The long running process is started by a user with super user privileges. I need the child processes it spawns to run as a different user (e.g., "nobody") while retaining the super user privil... | There is an [`os.setuid()`](http://docs.python.org/library/os.html#os.setuid) method. You can use it to change the current user for this script.
One solution is, somewhere where the child starts, to call `os.setuid()` and `os.setgid()` to change the user and group id and after that call one of the [os.exec\*](http://d... |
Run child processes as different user from a long running process | 1,770,209 | 26 | 2009-11-20T12:39:09Z | 6,037,494 | 46 | 2011-05-17T21:41:18Z | [
"python",
"fork",
"subprocess",
"setuid"
] | I've got a long running, daemonized Python process that uses subprocess to spawn new child processes when certain events occur. The long running process is started by a user with super user privileges. I need the child processes it spawns to run as a different user (e.g., "nobody") while retaining the super user privil... | Since you mentioned a daemon, I can conclude that you are running on a Unix-like operating system. This matters, because how to do this depends on the kind operating system. This answer applies *only* to **Unix**, including Linux, and Mac OS X.
1. Define a function that will set the gid and uid of the running process.... |
Is there a sendKey for Mac in Python? | 1,770,312 | 15 | 2009-11-20T13:04:11Z | 1,770,665 | 22 | 2009-11-20T14:10:30Z | [
"python",
"osx",
"sendkeys"
] | In Mac 10.6, I want to cause an active application to become de-active, or minimized by Python
I know I could use sendKey in Windows with Python, then what about in Mac? | Here is what I found from a different question on Stack Overflow. It works pretty good for my problem.
```
import os
cmd = """
osascript -e 'tell application "System Events" to keystroke "m" using {command down}'
"""
# minimize active window
os.system(cmd)
``` |
Metaclass not being called in subclasses | 1,770,712 | 9 | 2009-11-20T14:18:55Z | 1,770,823 | 12 | 2009-11-20T14:35:24Z | [
"python",
"metaclass"
] | Here is a python session.
```
>>> class Z(type):
def __new__(cls, name, bases, attrs):
print cls
print name
return type(name, bases, attrs)
...
>>> class Y(object):
__metaclass__ = Z
...
<class '__main__.Z'>
Y
>>> class X(Y):
... pass
...
>>> class W(Y):
... __metacla... | The problem is that the `cls` argument (which is the metaclass object) is not passed on when you call `type`, therefore the class object `Y` that is created and returned does not have any reference to the metaclass `Z`.
If you replace the last line in `__new__` with
```
return super(Z, cls).__new__(cls, name, bases, ... |
Is there a more pythonic way to open a file if given one as an argument or stdin if not? | 1,770,789 | 4 | 2009-11-20T14:30:16Z | 1,770,821 | 10 | 2009-11-20T14:35:11Z | [
"python",
"unix",
"command-line"
] | I'm trying to write a python script which follows the common unix command line pattern of accepting input from stdin if no file name is given. This is what I've been using:
```
if __name__ == "__main__":
if len(sys.argv) > 1:
stream = open(sys.argv[1])
else:
stream = sys.stdin
```
Is there a m... | The [fileinput](http://docs.python.org/library/fileinput.html) module is perfect for this. |
"No such file or directory" error with Boost Python | 1,771,063 | 17 | 2009-11-20T15:08:22Z | 1,771,089 | 9 | 2009-11-20T15:13:19Z | [
"python",
"boost"
] | I've installed boost python from ubuntu 9.04 repositories. I've successfully run
[Build a Simple Program Using Boost](http://www.boost.org/doc/libs/1_41_0/more/getting_started/unix-variants.html#build-a-simple-program-using-boost) from the tutorial, so I know that boost python is installed on my system.
However, the p... | It looks like you are missing the Python headers (Python.h etc.). Make sure you insteall the -devel or -dev package for your version of Python through the operating system package manager. This should provide the header files...
[Edit: noticed you are on ubuntu so try `sudo aptitude install python-dev` ] |
"No such file or directory" error with Boost Python | 1,771,063 | 17 | 2009-11-20T15:08:22Z | 1,771,148 | 29 | 2009-11-20T15:19:13Z | [
"python",
"boost"
] | I've installed boost python from ubuntu 9.04 repositories. I've successfully run
[Build a Simple Program Using Boost](http://www.boost.org/doc/libs/1_41_0/more/getting_started/unix-variants.html#build-a-simple-program-using-boost) from the tutorial, so I know that boost python is installed on my system.
However, the p... | add `#include <Python.h>` and compile with `-I/usr/include/python2.6` or whatever your Python version is.
Do not forget to link it with `-lpython2.6 -lboost_python` |
Choosing a Path for Python File Access | 1,771,099 | 4 | 2009-11-20T15:14:22Z | 1,771,178 | 7 | 2009-11-20T15:23:24Z | [
"python",
"path"
] | One of the features of my project is to allow users to create their own little `.txt` file, put it somewhere on their HDD, which can then be used as criteria for a part of my application.
Is there a Fixed, 'generic'(?) path for *most* OSs that I could use? Or does anyone have any kind of advice or guidance that could ... | [os.path.expanduser](http://docs.python.org/library/os.path.html?highlight=home#os.path.expanduser) is a good start -- a leading `~/` expands to "the user's home directory", which is computer by reasonable heuristics on both Unix-y and Windows systems. Of course, you don't want to put your file in the home directly, bu... |
Newbie Q about Scrapy pipeline.py | 1,771,151 | 2 | 2009-11-20T15:19:33Z | 1,774,708 | 9 | 2009-11-21T06:24:05Z | [
"python",
"web-crawler",
"scrapy"
] | I am studying the Scrapy tutorial. To test the process I created a new project with these files:
[See my post in Scrapy group for links to scripts, I cannot post more than 1 link here.](http://groups.google.com/group/scrapy-users/browse%5Ffrm/thread/4d52fa8c589a412a)
The spider runs well and scrapes the text between ... | I think they address your specific question in the [Scrapy Tutorial](http://doc.scrapy.org/intro/tutorial.html#storing-the-data-using-an-item-pipeline "Storing the data (using an Item Pipeline)").
It suggest, as others have here using the CSV module. Place the following in your `pipelines.py` file.
```
import csv
cl... |
List in a dictionary, looping in Python | 1,772,068 | 3 | 2009-11-20T17:30:41Z | 1,772,095 | 7 | 2009-11-20T17:34:18Z | [
"python",
"list",
"dictionary"
] | I have the following code:
```
TYPES = {'hotmail':{'type':'hotmail', 'lookup':'mixed', 'dkim': 'no', 'signatures':['|S|Return-Path: [email protected]','|R|^Return-Path:\s*[^@]+@(?:hot|msn)','^Received: from .*hotmail.com$']},
'gmail':{'type':'gmail', 'lookup':'mixed', 'dkim': 'yes', 'signatures':... | ```
for type_key, type in TYPES.iteritems():
for sub_type_key, sub_type in type.iteritems():
for sig in sub_type['signatures']:
```
should be:
```
for type_key, type in TYPES.iteritems():
for sig in type['signatures']:
```
But 'type' is a poor name choice in this case... you don't want to shadow ... |
Call from Objective-C into Python | 1,772,491 | 4 | 2009-11-20T18:45:36Z | 1,774,565 | 12 | 2009-11-21T04:59:29Z | [
"python",
"objective-c"
] | bbum [posted](http://stackoverflow.com/questions/1308079/calling-python-from-objective-c/1308469#1308469) an outline of how to do this, but I'm unable to complete the details. Where does the Python code go, and how will my Objective-C code know about it? How would I do it compiling on the command line? | Source here:
[Calling Python From Objective-C](http://svn.red-bean.com/bbum/trunk/PyObjC/CallPythonFromObjectiveC/)
I have posted a [full explanation of how to do this to my weblog](http://www.friday.com/bbum/2009/11/21/calling-python-from-objective-c/) as it is quite a bit longer than something I would post here.
T... |
What Python features will excite the interest of a C# developer? | 1,773,063 | 20 | 2009-11-20T20:30:24Z | 1,773,082 | 14 | 2009-11-20T20:33:41Z | [
"c#",
"python",
"programming-languages"
] | For someone whoâs been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I... | Being able to type in some code and get the result back *immediately*.
(Disclaimer: I use both C# and Python regularly, and I think both have their good and bad points.) |
What Python features will excite the interest of a C# developer? | 1,773,063 | 20 | 2009-11-20T20:30:24Z | 1,773,087 | 18 | 2009-11-20T20:34:22Z | [
"c#",
"python",
"programming-languages"
] | For someone whoâs been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I... | For me its the flexibility and elegance, but there are a handful of things I wish could be pulled in from other languages though (better threading, more robust expressions).
In typical I can write a little bit of code in python and do a lot more than the same amount of lines in many other languages. Also, in python co... |
What Python features will excite the interest of a C# developer? | 1,773,063 | 20 | 2009-11-20T20:30:24Z | 1,773,224 | 10 | 2009-11-20T21:03:31Z | [
"c#",
"python",
"programming-languages"
] | For someone whoâs been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I... | I'm primarily .NET developer and using Python for me personal projects.
> What are the good things about python that developers love?
I can say for myself - Python is like a breath of fresh air.
1) It's simple to learn, took about a week for me in the evenings. I'm saying about Python + Django. Python syntax is quit... |
What Python features will excite the interest of a C# developer? | 1,773,063 | 20 | 2009-11-20T20:30:24Z | 1,773,278 | 9 | 2009-11-20T21:13:58Z | [
"c#",
"python",
"programming-languages"
] | For someone whoâs been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I... | Your question is kind of like a plumber asking why carpenters are always going on and on about hammers. After all the plumber doesn't have a hammer and has never missed it. Python (even IronPython) and C# target different types of developers and different types of programs. I am very comfortable in Python and enjoy the... |
What Python features will excite the interest of a C# developer? | 1,773,063 | 20 | 2009-11-20T20:30:24Z | 1,773,987 | 9 | 2009-11-21T00:07:22Z | [
"c#",
"python",
"programming-languages"
] | For someone whoâs been happily programming in C# for quite some time now and planning to learn a new language I find the Python community more closely knit than many others.
Personally dynamic typing puts me off, but I am fascinated by the way the Python community rallies around it. There are a lot of other things I... | I'm a very heavy user of both C# and Python; I've built very complicated applications in both languages, and I've also embedded Python scripting in my major C# application. I'm not using either to do much in the way of web work right now, but other than that I feel like I'm pretty qualified to answer the question.
The... |
Class attribute evaluation and generators | 1,773,636 | 15 | 2009-11-20T22:29:02Z | 1,773,697 | 14 | 2009-11-20T22:46:45Z | [
"python",
"class",
"attributes",
"class-attributes"
] | How exactly does Python evaluate class attributes? I've stumbled across an interesting quirk (in Python 2.5.2) that I'd like explained.
I have a class with some attributes that are defined in terms of other, previously defined attributes. When I try using a generator object, Python throws an error, but if I use a plai... | Yeah, it's a bit dodgy, this. A class doesn't really introduce a new scope, it just sort of looks a little bit like it does; constructs like this expose the difference.
The idea is that when you're using a generator expression it's equivalent to doing it with a lambda:
```
class Brie(object):
base= 2
powers= ... |
Convert ConfigParser.items('') to dictionary | 1,773,793 | 35 | 2009-11-20T23:11:28Z | 1,773,820 | 58 | 2009-11-20T23:19:00Z | [
"python"
] | How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:
```
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('conf.ini')
connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
"password='%(password)s... | Have you tried
```
print connection_string % dict(config.items('db'))
```
? |
Convert ConfigParser.items('') to dictionary | 1,773,793 | 35 | 2009-11-20T23:11:28Z | 1,773,851 | 38 | 2009-11-20T23:24:57Z | [
"python"
] | How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:
```
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('conf.ini')
connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
"password='%(password)s... | This is actually already done for you in `config._sections`. Example:
```
$ cat test.ini
[First Section]
var = value
key = item
[Second Section]
othervar = othervalue
otherkey = otheritem
```
And then:
```
>>> from ConfigParser import ConfigParser
>>> config = ConfigParser()
>>> config.read('test.ini')
>>> config._... |
Convert ConfigParser.items('') to dictionary | 1,773,793 | 35 | 2009-11-20T23:11:28Z | 23,944,270 | 8 | 2014-05-29T22:48:25Z | [
"python"
] | How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:
```
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('conf.ini')
connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
"password='%(password)s... | I know this was asked a long time ago and a solution chosen, but the solution selected does not take into account defaults and variable substitution. Since it's the first hit when searching for creating dicts from parsers, thought I'd post my solution which does include default and variable substitutions by using Confi... |
Convert ConfigParser.items('') to dictionary | 1,773,793 | 35 | 2009-11-20T23:11:28Z | 28,990,982 | 11 | 2015-03-11T15:37:26Z | [
"python"
] | How can I convert the result of a ConfigParser.items('section') to a dictionary to format a string like here:
```
import ConfigParser
config = ConfigParser.ConfigParser()
config.read('conf.ini')
connection_string = ("dbname='%(dbname)s' user='%(dbuser)s' host='%(host)s' "
"password='%(password)s... | How I did it in just one line.
```
my_config_parser_dict = {s:dict(config.items(s)) for s in config.sections()}
```
No more than other answers but when it is not the real businesses of your method and you need it just in one place use less lines and take the power of dict compression could be useful. |
How can I parse a YAML file in Python | 1,773,805 | 204 | 2009-11-20T23:16:16Z | 1,774,043 | 273 | 2009-11-21T00:23:34Z | [
"python",
"yaml"
] | How can I parse a YAML file in Python? | The easiest and pureist method without relying on C headers is PyYaml:
```
#!/usr/bin/env python
import yaml
with open("example.yaml", 'r') as stream:
try:
print(yaml.load(stream))
except yaml.YAMLError as exc:
print(exc)
```
Err.. that's it... how many lines of code would that take me in Ja... |
download a zip file to a local drive and extract all files to a destination folder using python 2.5 | 1,774,434 | 2 | 2009-11-21T03:44:57Z | 1,774,444 | 11 | 2009-11-21T03:49:40Z | [
"python",
"http",
"download",
"extract",
"unzip"
] | I am trying to download a zip file to a local drive and extract all files to a destination folder.
so i have come up with solution but it is only to "download" a file from a directory to another directory but it doesn't work for downloading files. for the extraction, I am able to get it to work in 2.6 but not for 2.5.... | [urllib.urlretrieve](http://docs.python.org/library/urllib.html?highlight=urllib#urllib.urlretrieve) can get a file (zip or otherwise;-) from a URL to a given path.
`extractall` is indeed new in 2.6, but in 2.5 you can use an explicit loop (get all names, open each name, etc). Do you need example code?
So here's the ... |
Am I supposed to use PyQT4 for programming cross-platform software in Python? | 1,774,487 | 2 | 2009-11-21T04:11:46Z | 1,774,501 | 10 | 2009-11-21T04:17:51Z | [
"python",
"qt",
"cross-platform"
] | So a user suggested getting PyQT.
A quick Google gave me this: [Link](http://www.riverbankcomputing.co.uk/software/pyqt/download)
Is this GUI Library for pay?
If my development environment is Ubuntu Linux, what should I download on that site. I have no idea.
Please provide links if the site I provided is not correc... | You may want to look at [PySide](http://www.pyside.org/) which is sponsored by Nokia, who own QT. It's also LGPL, which is a bit better of a license than the PyQT bindings. It's also a bit more pythonic in how it works. Unfortunately, it's new, so there isn't as much documentation. On their download page you can find i... |
Does a exception with just a raise have any use? | 1,774,792 | 4 | 2009-11-21T07:08:52Z | 1,774,834 | 17 | 2009-11-21T07:31:45Z | [
"python",
"exception-handling"
] | For example, here is some code from django.templates.loader.app\_directories.py.[1]
```
try:
yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
# The template dir name was a bytestring that wasn't valid UTF-8.
raise
```
If you catch an exception just to re raise it, what purpose does ... | In the code you linked to is another additional exception handler:
```
try:
yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
# The template dir name was a bytestring that wasn't valid UTF-8.
raise
except ValueError:
# The joined path was located outside of template_dir.
pass
... |
Can this be made more pythonic? | 1,775,459 | 2 | 2009-11-21T13:17:26Z | 1,775,485 | 7 | 2009-11-21T13:29:15Z | [
"python",
"primes"
] | I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability.
Thanks
```
from math import sqrt
def isprim... | Your algorithm itself may be implemented pythonically, but it's often useful to re-write algorithms in a functional way - You might end up with a completely different but more readable solution at all (which is even more pythonic).
```
def primes(upper):
n = 2; found = []
while n < upper:
# If a number... |
Using Python 3.1 with TextMate | 1,775,954 | 17 | 2009-11-21T16:34:17Z | 1,776,026 | 39 | 2009-11-21T16:56:05Z | [
"python",
"osx",
"python-3.x",
"textmate"
] | TextMate seems to use the built-in Python version I assume (sys.path doesn't work). How do you configure it to use 3.1 instead? I've already installed the 3.1 package and I can use IDLE for interactive sessions, but I need to use TextMate now.
Thanks | TextMate uses the value of the `TM_PYTHON` variable to find the path to the Python interpreter. A good solution is to take advantage of TextMate's ability to define variables like `TM_PYTHON` on a per-project basis:
1. Open a new or existing TextMate Project (`File -> New Project` or `File -> Open`)
2. De-select any f... |
Advice on Python Parser Generators | 1,776,185 | 9 | 2009-11-21T17:50:00Z | 1,776,190 | 10 | 2009-11-21T17:51:55Z | [
"python",
"parser-generator"
] | Hey guys, this is my first question here on Stack Overflow and I was wondering if I could ask the advice of people who know a bit more about Python and Parser Generators than I do.
I've been given a task where I have to create a parser for a simple C-like language. I can use any programming language and tools I wish t... | [PyParsing](http://pyparsing.wikispaces.com/) is a python tool to generate parsers. There are a [lot of interesting examples](http://pyparsing.wikispaces.com/Examples).
Easy to get started:
```
from pyparsing import Word, alphas
# define grammar
greet = Word( alphas ) + "," + Word( alphas ) + "!"
# input string
hel... |
replacing Matlab with python | 1,776,290 | 15 | 2009-11-21T18:24:26Z | 1,776,373 | 20 | 2009-11-21T18:55:34Z | [
"python",
"matlab"
] | i am a engineering student and i have to do a lot of numerical processing, plots, simulations etc. The tool that i use currently is Matlab. I use it in my university computers for most of my assignments. However, i want to know what are the free options available.
i have done some research and many have said that pyth... | On a Mac the easiest ways to get started are (in no particular order):
* [Enthought Python Distribution](http://www.enthought.com/products/epd.php) which includes most scientific packages you are likely to need. Free for academic/non-commercial use.
* [Macports](http://www.macports.org/) - up to date with latest relea... |
replacing Matlab with python | 1,776,290 | 15 | 2009-11-21T18:24:26Z | 1,777,708 | 12 | 2009-11-22T03:12:25Z | [
"python",
"matlab"
] | i am a engineering student and i have to do a lot of numerical processing, plots, simulations etc. The tool that i use currently is Matlab. I use it in my university computers for most of my assignments. However, i want to know what are the free options available.
i have done some research and many have said that pyth... | I've been programming with Matlab for about 15 years, and with Python for about 10. It usually breaks down this way:
If you can satisfy the following conditions:
1. You primarily use matrices and matrix operations
2. You have the money for a Matlab license
3. You work on a platform that mathworks supports
Then, by al... |
couchDB , python and authentication | 1,776,434 | 10 | 2009-11-21T19:15:40Z | 4,994,439 | 18 | 2011-02-14T16:16:15Z | [
"python",
"couchdb"
] | I have installed couchDB v 0.10.0, and am attempting to talk to it via python from Couch class downloaded from couchDB wiki. Problem is:
```
Create database 'mydb': {'error': 'unauthorized', 'reason': 'You are not a server admin.'}
```
I hand edited the local.ini file to include my standard osx login and password. I ... | To concour David's reply, (i.e. "This is how I do it using module CouchDB 0.8 in python 2.6 with couchdb 1.0.2")
couch = couchdb.Server(couch\_server)
couch.resource.credentials = (USERNAME, PASSWORD) |
How can a python base class tell whether a sub class has overriden its methods? | 1,776,994 | 5 | 2009-11-21T22:27:31Z | 1,777,092 | 8 | 2009-11-21T23:03:44Z | [
"python"
] | Here is my guess, which doesn't work:
```
class BaseClass(object):
def foo(self):
return 'foo'
def bar(self):
return 'bar'
def methods_implemented(self):
"""This doesn't work..."""
overriden = []
for method in ('foo', 'bar'):
this_method = getattr(self, m... | Perhaps this?
```
>>> class BaseClass(object):
... def foo(self):
... return 'foo'
... def bar(self):
... return 'bar'
... def methods_implemented(self):
... """This does work."""
... overriden = []
... for method in ('foo', 'bar'):
... this_method = geta... |
How to auto log into gmail atom feed with Python? | 1,777,081 | 10 | 2009-11-21T23:01:16Z | 1,777,142 | 13 | 2009-11-21T23:30:37Z | [
"python",
"rss",
"gmail",
"atom",
"urllib"
] | Gmail has this sweet thing going on to get an atom feed:
```
def gmail_url(user, pwd):
return "https://"+str(user)+":"+str(pwd)+"@gmail.google.com/gmail/feed/atom"
```
Now when you do this in a browser, it authenticates and forwards you. But in Python, at least what I'm trying, isn't working right.
```
url = gma... | You can use the HTTPBasicAuthHandler, I tried the following and it worked:
```
import urllib2
def get_unread_msgs(user, passwd):
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(
realm='New mail feed',
uri='https://mail.google.com',
user='%[email protected]' % user,
... |
Using python imaplib to "delete" an email from Gmail? | 1,777,264 | 12 | 2009-11-22T00:13:58Z | 1,777,290 | 15 | 2009-11-22T00:23:40Z | [
"python",
"email",
"imap"
] | Can you delete emails with imaplib? If so how? | Deleting an email over IMAP is performed in two phases:
* mark one or more items for deletion: `imap.store(msg_no, '+FLAGS', '\\Deleted')`
* expunge the mailbox: `imap.expunge()`
(`imap` is your `IMAP4` object) |
Using python imaplib to "delete" an email from Gmail? | 1,777,264 | 12 | 2009-11-22T00:13:58Z | 1,777,304 | 20 | 2009-11-22T00:30:37Z | [
"python",
"email",
"imap"
] | Can you delete emails with imaplib? If so how? | Use the [store](http://docs.python.org/library/imaplib.html?highlight=imaplib#imaplib.IMAP4.store) method (of the `IMAP4` object representing your connection) to set the `r'\Deleted'` flag on the message number you want to delete, as the example in the docs show; then the [expunge](http://docs.python.org/library/imapli... |
Using python imaplib to "delete" an email from Gmail? | 1,777,264 | 12 | 2009-11-22T00:13:58Z | 3,044,555 | 9 | 2010-06-15T11:07:43Z | [
"python",
"email",
"imap"
] | Can you delete emails with imaplib? If so how? | ```
imap.uid('STORE', list_of_msgno , '+FLAGS', '(\Deleted)')
imap.expunge()
```
i.e
```
imap.uid('STORE', '2, 4, 9, 12' , '+FLAGS', '(\Deleted)')
```
Here `(2, 4, 9, 12)` are `uid` of the messages which are going to be deleted. |
How to detect Mac OS version using Python? | 1,777,344 | 16 | 2009-11-22T00:41:06Z | 1,777,365 | 34 | 2009-11-22T00:49:10Z | [
"python",
"osx"
] | My application is assumed to be running on a Mac OS X system. However, what I need to do is figure out what version of Mac OS (or Darwin) it is running on, preferably as a number. For instance,
* "10.4.11" would return either 10.4 or 8
* "10.5.4" would return 10.5 or 9
* "10.6" would return 10.6 or 10
I found out tha... | ```
>>> import platform
>>> platform.mac_ver()
('10.5.8', ('', '', ''), 'i386')
```
As you see, the first item of the tuple [`mac_ver`](http://docs.python.org/library/platform.html?highlight=mac%5Fver#platform.mac%5Fver) returns is a string, not a number (hard to make '10.5.8' into a number!-), but it's pretty easy to... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.