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 |
|---|---|---|---|---|---|---|---|---|---|
Parallel processing from a command queue on Linux (bash, python, ruby... whatever) | 463,963 | 42 | 2009-01-21T02:54:45Z | 464,038 | 38 | 2009-01-21T03:58:50Z | [
"python",
"ruby",
"bash",
"shell",
"parallel-processing"
] | I have a list/queue of 200 commands that I need to run in a shell on a Linux server.
I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer.
When a process finishes I want the next command to be "popped"... | I would imagine you could do this using make and the make -j xx command.
Perhaps a makefile like this
```
all : usera userb userc....
usera:
imapsync usera
userb:
imapsync userb
....
```
make -j 10 -f makefile |
Parallel processing from a command queue on Linux (bash, python, ruby... whatever) | 463,963 | 42 | 2009-01-21T02:54:45Z | 628,543 | 12 | 2009-03-10T00:31:35Z | [
"python",
"ruby",
"bash",
"shell",
"parallel-processing"
] | I have a list/queue of 200 commands that I need to run in a shell on a Linux server.
I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer.
When a process finishes I want the next command to be "popped"... | For this kind of job PPSS is written: Parallel processing shell script. Google for this name and you will find it, I won't linkspam. |
Parallel processing from a command queue on Linux (bash, python, ruby... whatever) | 463,963 | 42 | 2009-01-21T02:54:45Z | 2,148,784 | 24 | 2010-01-27T17:00:56Z | [
"python",
"ruby",
"bash",
"shell",
"parallel-processing"
] | I have a list/queue of 200 commands that I need to run in a shell on a Linux server.
I only want to have a maximum of 10 processes running (from the queue) at once. Some processes will take a few seconds to complete, other processes will take much longer.
When a process finishes I want the next command to be "popped"... | [Parallel](https://savannah.nongnu.org/projects/parallel/) is made exatcly for this purpose.
```
cat userlist | parallel imapsync
```
One of the beauties of [Parallel](https://savannah.nongnu.org/projects/parallel/) compared to other solutions is that it makes sure output is not mixed. Doing `traceroute` in [Parallel... |
How are POST and GET variables handled in Python? | 464,040 | 103 | 2009-01-21T03:59:03Z | 464,087 | 25 | 2009-01-21T04:31:44Z | [
"python",
"post",
"get"
] | In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string) variables. What's the equivalent in Python? | They are stored in the CGI fieldstorage object.
```
import cgi
form = cgi.FieldStorage()
print "The user entered %s" % form.getvalue("uservalue")
``` |
How are POST and GET variables handled in Python? | 464,040 | 103 | 2009-01-21T03:59:03Z | 464,977 | 187 | 2009-01-21T11:53:01Z | [
"python",
"post",
"get"
] | In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string) variables. What's the equivalent in Python? | suppose you're posting a html form with this:
```
<input type="text" name="username">
```
If using [raw cgi](http://docs.python.org/library/cgi.html):
```
import cgi
form = cgi.FieldStorage()
print form["username"]
```
If using [Django](http://docs.djangoproject.com/), [Pylons](http://pylonshq.com/), [Flask](http:/... |
How are POST and GET variables handled in Python? | 464,040 | 103 | 2009-01-21T03:59:03Z | 11,353,284 | 21 | 2012-07-05T22:15:06Z | [
"python",
"post",
"get"
] | In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string) variables. What's the equivalent in Python? | I've found nosklo's answer very extensive and useful! For those, like myself, who might find accessing the raw request data directly also useful, I would like to add the way to do that:
```
import os, sys
# the query string, which contains the raw GET data
# (For example, for http://example.com/myscript.py?a=b&c=d&e
... |
How are POST and GET variables handled in Python? | 464,040 | 103 | 2009-01-21T03:59:03Z | 27,893,309 | 13 | 2015-01-11T23:26:51Z | [
"python",
"post",
"get"
] | In PHP you can just use `$_POST` for POST and `$_GET` for GET (Query string) variables. What's the equivalent in Python? | I know this is an old question. Yet it's surprising that no good answer was given.
First of all the question is completely valid without mentioning the framework. The CONTEXT is PHP language equivalence. Although there are many ways to get the query string parameters in Python, the framework variables are just conveni... |
Combining two sorted lists in Python | 464,342 | 46 | 2009-01-21T07:33:47Z | 464,350 | 24 | 2009-01-21T07:36:52Z | [
"python",
"list",
"sorting"
] | I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python? | This is simply merging. Treat each list as if it were a stack, and continuously pop the smaller of the two stack heads, adding the item to the result list, until one of the stacks is empty. Then add all remaining items to the resulting list. |
Combining two sorted lists in Python | 464,342 | 46 | 2009-01-21T07:33:47Z | 464,538 | 81 | 2009-01-21T09:14:08Z | [
"python",
"list",
"sorting"
] | I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python? | People seem to be over complicating this.. Just combine the two lists, then sort them:
```
>>> l1 = [1, 3, 4, 7]
>>> l2 = [0, 2, 5, 6, 8, 9]
>>> l1.extend(l2)
>>> sorted(l1)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
..or shorter (and without modifying `l1`):
```
>>> sorted(l1 + l2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
```
..eas... |
Combining two sorted lists in Python | 464,342 | 46 | 2009-01-21T07:33:47Z | 464,767 | 10 | 2009-01-21T10:36:56Z | [
"python",
"list",
"sorting"
] | I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python? | There is a slight flaw in [ghoseb's](http://stackoverflow.com/questions/464342/combining-two-sorted-lists-in-python#464454) solution, making it O(n\*\*2), rather than O(n).
The problem is that this is performing:
```
item = l1.pop(0)
```
With linked lists or deques this would be an O(1) operation, so wouldn't affec... |
Combining two sorted lists in Python | 464,342 | 46 | 2009-01-21T07:33:47Z | 465,043 | 68 | 2009-01-21T12:16:08Z | [
"python",
"list",
"sorting"
] | I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python? | > is there a smarter way to do this in Python
This hasn't been mentioned, so I'll go ahead - there is a [merge stdlib function](http://svn.python.org/view/python/trunk/Lib/heapq.py?view=markup) in the heapq module of python 2.6+. If all you're looking to do is getting things done, this might be a better idea. Of cours... |
Combining two sorted lists in Python | 464,342 | 46 | 2009-01-21T07:33:47Z | 482,848 | 44 | 2009-01-27T10:09:03Z | [
"python",
"list",
"sorting"
] | I have two lists of objects. Each list is already sorted by a property of the object that is of the datetime type. I would like to combine the two lists into one sorted list. Is the best way just to do a sort or is there a smarter way to do this in Python? | Long story short, unless `len(l1 + l2) ~ 1000000` use:
```
L = l1 + l2
L.sort()
```

Description of the figure and source code can be found [here](http://stackoverflow.com/questions/464960/code-golf-combining-multiple-sorted-lists-into-a-single-sorted-l... |
Python regular expressions - how to capture multiple groups from a wildcard expression? | 464,736 | 29 | 2009-01-21T10:29:31Z | 464,755 | 34 | 2009-01-21T10:33:24Z | [
"python",
"regex",
"lexical-analysis"
] | I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example:
`re.search("(\w)*", "abcdefg").groups`()
this returns the list ('g',)
I need it to return ('a','b','c','d','e','f','g',)
Is that pos... | ```
re.findall(r"\w","abcdefg")
``` |
Python regular expressions - how to capture multiple groups from a wildcard expression? | 464,736 | 29 | 2009-01-21T10:29:31Z | 464,879 | 23 | 2009-01-21T11:19:08Z | [
"python",
"regex",
"lexical-analysis"
] | I have a Python regular expression that contains a group which can occur zero or many times - but when I retrieve the list of groups afterwards, only the last one is present. Example:
`re.search("(\w)*", "abcdefg").groups`()
this returns the list ('g',)
I need it to return ('a','b','c','d','e','f','g',)
Is that pos... | In addition to [Douglas Leeder's solution](http://stackoverflow.com/questions/464736/python-regular-expressions-how-to-capture-multiple-groups-from-a-wildcard-expre#464755), here is the explanation:
In regular expressions the group count is fixed. Placing a quantifier behind a group does not increase group count (imag... |
Python code to pick out all possible combinations from a list? | 464,864 | 123 | 2009-01-21T11:13:40Z | 464,882 | 146 | 2009-01-21T11:20:04Z | [
"python",
"combinations"
] | I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found [some code](http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/) (by googling) that apparently does what I'm looking for, bu... | Have a look at [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations):
> ```
> itertools.combinations(iterable, r)
> ```
>
> Return r length subsequences of elements from
> the input iterable.
>
> Combinations are emitted in lexicographic sort order. So, if the
> input iterable ... |
Python code to pick out all possible combinations from a list? | 464,864 | 123 | 2009-01-21T11:13:40Z | 5,898,031 | 327 | 2011-05-05T12:56:24Z | [
"python",
"combinations"
] | I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found [some code](http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/) (by googling) that apparently does what I'm looking for, bu... | [This answer](http://stackoverflow.com/questions/464864/python-code-to-pick-out-all-possible-combinations-from-a-list/464882#464882) missed one aspect: the OP asked for ALL combinations... not just combinations of length "r".
So you'd either have to loop through all lengths "L":
```
import itertools
stuff = [1, 2, 3... |
Python code to pick out all possible combinations from a list? | 464,864 | 123 | 2009-01-21T11:13:40Z | 6,542,458 | 23 | 2011-07-01T00:21:10Z | [
"python",
"combinations"
] | I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found [some code](http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/) (by googling) that apparently does what I'm looking for, bu... | Here's a lazy one-liner, also using itertools:
```
def combinations(items):
return ( set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)) )
# alternative: ...in product([0,1], repeat=len(items)) )
```
Main idea behind this answer: there are 2^N combinations -- same as the nu... |
Python code to pick out all possible combinations from a list? | 464,864 | 123 | 2009-01-21T11:13:40Z | 7,173,919 | 11 | 2011-08-24T10:24:55Z | [
"python",
"combinations"
] | I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found [some code](http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/) (by googling) that apparently does what I'm looking for, bu... | I agree with Dan H that Ben indeed asked for **all** combinations. `itertools.combinations()` does not give all combinations.
Another issue is, if the input iterable is big, it is perhaps better to return a generator instead of everything in a list:
```
iterable = range(10)
for s in xrange(len(iterable)+1):
for com... |
Python code to pick out all possible combinations from a list? | 464,864 | 123 | 2009-01-21T11:13:40Z | 23,743,696 | 8 | 2014-05-19T17:25:51Z | [
"python",
"combinations"
] | I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found [some code](http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/) (by googling) that apparently does what I'm looking for, bu... | Here is one using recursion:
```
>>> import copy
>>> def combinations(target,data):
... for i in range(len(data)):
... new_target = copy.copy(target)
... new_data = copy.copy(data)
... new_target.append(data[i])
... new_data = data[i+1:]
... print new_target
... comb... |
Python code to pick out all possible combinations from a list? | 464,864 | 123 | 2009-01-21T11:13:40Z | 24,402,296 | 12 | 2014-06-25T07:08:01Z | [
"python",
"combinations"
] | I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found [some code](http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/) (by googling) that apparently does what I'm looking for, bu... | This one-liner gives you all the combinations (between `0` and `n` items if the original list/set contains `n` distinct elements) and uses the native method [`itertools.combinations`](https://docs.python.org/2/library/itertools.html#itertools.combinations):
```
from itertools import combinations
input = ['a', 'b', 'c... |
Python code to pick out all possible combinations from a list? | 464,864 | 123 | 2009-01-21T11:13:40Z | 29,092,176 | 8 | 2015-03-17T05:52:28Z | [
"python",
"combinations"
] | I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found [some code](http://desk.stinkpot.org:8080/tricks/index.php/2008/04/get-all-possible-combinations-of-a-lists-elements-in-python/) (by googling) that apparently does what I'm looking for, bu... | **You can generating all combinations of a list in python using this simple code**
```
import itertools
a = [1,2,3,4]
for i in xrange(0,len(a)+1):
print list(itertools.combinations(a,i))
```
**Result would be :**
```
[()]
[(1,), (2,), (3,), (4,)]
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
[(1, 2, 3), (1, 2... |
Writing unit tests in Django / Python | 465,065 | 28 | 2009-01-21T12:22:24Z | 465,242 | 9 | 2009-01-21T13:12:53Z | [
"python",
"django",
"unit-testing"
] | I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how.
I'm writing a Django application, and so far have only created the models (and customi... | I'm not exactly sure of the specifics of what you're trying to test here, I'd need more code snippets for this, but I can give you some general advice.
First, read the unit testing chapter of "Dive into Python" (it's free online! <http://diveintopython3.ep.io/unit-testing.html>), it's a great explanation of unit testi... |
Writing unit tests in Django / Python | 465,065 | 28 | 2009-01-21T12:22:24Z | 465,684 | 36 | 2009-01-21T15:08:38Z | [
"python",
"django",
"unit-testing"
] | I've not used Unit Tests before other than a quick introduction in a Uni course. I'm currently writing an application though and would like to teach myself TDD in the process. The problem is, I've no idea what to test or really how.
I'm writing a Django application, and so far have only created the models (and customi... | **Is a function to test each model within the ModelTests class a good way of writing tests?**
No.
**What exactly should I be testing for?**
* That creating a model with all of the fields completed works?
* That a half complete model fails?
* That any special cases are tested (like a null and is\_required=False)?
* I... |
How can I print over the current line in a command line application? | 465,348 | 10 | 2009-01-21T13:43:17Z | 465,475 | 16 | 2009-01-21T14:15:10Z | [
"python",
"windows",
"command-line"
] | On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).
Can I achieve the same effect in a Windows command line from a Python script?
I tried the curses module but it doesn't seem to be available on Windows. | yes:
```
import sys
import time
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()
``` |
How can I print over the current line in a command line application? | 465,348 | 10 | 2009-01-21T13:43:17Z | 21,672,188 | 7 | 2014-02-10T08:28:27Z | [
"python",
"windows",
"command-line"
] | On Unix, I can either use \r (carriage return) or \b (backspace) to print over text already visible in the shell (i.e. overwrite the current line again).
Can I achieve the same effect in a Windows command line from a Python script?
I tried the curses module but it doesn't seem to be available on Windows. | ```
import sys
import time
for i in range(10):
print '\r', # print is Ok, and comma is needed.
time.sleep(0.3)
print i,
sys.stdout.flush() # flush is needed.
```
And if on the IPython-notebook, just like this:
```
import time
from IPython.display import clear_output
for i in range(10):
... |
How do I take the output of one program and use it as the input of another? | 465,421 | 4 | 2009-01-21T14:01:11Z | 465,466 | 10 | 2009-01-21T14:12:23Z | [
"python",
"ruby",
"io"
] | I've looked at [this](http://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another) and it wasn't much help.
I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any l... | ```
p = subprocess.Popen(['ruby', 'ruby_program.rb'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
ruby_question = p.stdout.readline()
answer = calculate_answer(ruby_question)
p.stdin.write(answer)
print p.communicate()[0] # prints further info ruby may show.
```
The last ... |
What is a simple way to generate keywords from a text? | 465,795 | 17 | 2009-01-21T15:43:36Z | 465,909 | 16 | 2009-01-21T16:14:29Z | [
"python",
"perl",
"metadata"
] | I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.
Has anyone done anything like that? Do you k... | The name for the "high frequency English words" is [stop words](http://en.wikipedia.org/wiki/Stop_words) and there are many lists available. I'm not aware of any python or perl libraries, but you could encode your stop word list in a binary tree or hash (or you could use python's frozenset), then as you read each word ... |
What is a simple way to generate keywords from a text? | 465,795 | 17 | 2009-01-21T15:43:36Z | 466,037 | 9 | 2009-01-21T16:44:49Z | [
"python",
"perl",
"metadata"
] | I suppose I could take a text and remove high frequency English words from it. By keywords, I mean that I want to extract words that are most the characterizing of the content of the text (tags ) . It doesn't have to be perfect, a good approximation is perfect for my needs.
Has anyone done anything like that? Do you k... | You could try using the perl module [Lingua::EN::Tagger](http://search.cpan.org/~acoburn/Lingua-EN-Tagger-0.15/Tagger.pm) for a quick and easy solution.
A more complicated module [Lingua::EN::Semtags::Engine](http://code.google.com/p/lingua-en-semtags-engine/) uses Lingua::EN::Tagger with a WordNet database to get a m... |
How to make a model instance read-only after saving it once? | 466,135 | 3 | 2009-01-21T17:11:14Z | 466,641 | 7 | 2009-01-21T19:29:25Z | [
"python",
"django",
"django-models",
"django-admin",
"django-signals"
] | One of the functionalities in a Django project I am writing is sending a newsletter. I have a model, `Newsletter` and a function, `send_newsletter`, which I have registered to listen to `Newsletter`'s `post_save` signal. When the newsletter object is saved via the admin interface, `send_newsletter` checks if `created` ... | You can check if it is creation or update in the model's `save` method:
```
def save(self, *args, **kwargs):
if self.pk:
raise StandardError('Can\'t modify bla bla bla.')
super(Payment, self).save(*args, **kwargs)
```
Code above will raise an exception if you try to save an existing object. **Objects ... |
How can I hide the console window in a PyQt app running on Windows? | 466,203 | 12 | 2009-01-21T17:25:38Z | 466,222 | 17 | 2009-01-21T17:28:34Z | [
"python",
"windows",
"command-line",
"pyqt"
] | Surely this is possible? I have been hunting through PyQt tutorials and documentation but cannot find the answer to it. Probably I just need to phrase my search query differently.
[Edit]
Thanks PEZ for the answer - more details including use of the `.pyw` extension in [Python Programming on Win32 chapter 20](http://w... | I think you should be able to run your app with pythonw.exe. |
How can I hide the console window in a PyQt app running on Windows? | 466,203 | 12 | 2009-01-21T17:25:38Z | 466,279 | 14 | 2009-01-21T17:39:19Z | [
"python",
"windows",
"command-line",
"pyqt"
] | Surely this is possible? I have been hunting through PyQt tutorials and documentation but cannot find the answer to it. Probably I just need to phrase my search query differently.
[Edit]
Thanks PEZ for the answer - more details including use of the `.pyw` extension in [Python Programming on Win32 chapter 20](http://w... | An easy way to do this is to give your script a .pyw extension instead of the usual .py.
This has the same effect as PEZ's answer (runs the script using pythonw.exe). |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 466,366 | 433 | 2009-01-21T18:07:17Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | Check out [strptime](http://docs.python.org/2/library/time.html#time.strptime) in the [time](http://docs.python.org/2/library/time.html) module. It is the inverse of [strftime](http://docs.python.org/2/library/time.html#time.strftime). |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 466,376 | 1,383 | 2009-01-21T18:08:52Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | ```
from datetime import datetime
date_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
```
[Link to the Python documentation for strptime](https://docs.python.org/2/library/datetime.html#datetime.datetime.strptime)
[and a link for the strftime format mask](https://docs.python.org/2/library/datet... |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 470,303 | 399 | 2009-01-22T18:27:18Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | Use the third party [dateutil](http://labix.org/python-dateutil) library:
```
from dateutil import parser
dt = parser.parse("Aug 28 1999 12:00AM")
```
It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.
It very ... |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 7,761,860 | 17 | 2011-10-14T00:13:28Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | Something that isn't mentioned here and is useful: adding a suffix to the day. I decoupled the suffix logic so you can use it for any number you like, not just dates.
```
import time
def num_suffix(n):
'''
Returns the suffix for any given int
'''
suf = ('th','st', 'nd', 'rd')
n = abs(n) # wise guy... |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 22,128,786 | 50 | 2014-03-02T14:22:44Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | I have put together a project that can convert some really neat expressions. Check out **[timestring](http://github.com/stevepeak/timestring)**.
## Here are some examples below:
[`pip install timestring`](http://github.com/stevepeak/timestring)
```
>>> import timestring
>>> timestring.Range('next week')
<timestring.... |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 22,223,725 | 24 | 2014-03-06T11:53:05Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | Many timestamps have an implied timezone. To ensure that your code will work in every timezone, you should use UTC internally and attach a timezone each time a foreign object enters the system.
Python 3.2+:
```
>>> datetime.datetime.strptime(
... "March 5, 2014, 20:13:50", "%B %d, %Y, %H:%M:%S"
... ).replace(tzin... |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 27,401,685 | 14 | 2014-12-10T13:00:49Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | You string representation of datetime is
`Jun 1 2005 1:33PM`
which is equals to
`%b %d %Y %I:%M%p`
> %b Month as localeâs abbreviated name(Jun)
>
> %d Day of the month as a zero-padded decimal number(1)
>
> %Y Year with century as a decimal number(2015)
>
> %I Hour (12-hour clock) as a zero-padded decimal number(... |
Converting string into datetime | 466,345 | 826 | 2009-01-21T18:00:29Z | 34,377,575 | 7 | 2015-12-20T03:03:25Z | [
"python",
"datetime"
] | Short and simple. I've got a huge list of date-times like this as strings:
```
Jun 1 2005 1:33PM
Aug 28 1999 12:00AM
```
I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.
Any help (even if it's just a kick in the right direction) would b... | Here is a solution using Pandas to convert dates formatted as strings into datetime.date objects.
```
import pandas as pd
dates = ['2015-12-25', '2015-12-26']
>>> [d.date() for d in pd.to_datetime(dates)]
[datetime.date(2015, 12, 25), datetime.date(2015, 12, 26)]
```
And here is how to convert the OP's original dat... |
Why do I have to specify my own class when using super(), and is there a way to get around it? | 466,611 | 12 | 2009-01-21T19:20:58Z | 466,638 | 7 | 2009-01-21T19:28:33Z | [
"python",
"multiple-inheritance"
] | When using Python's `super()` to do method chaining, you have to explicitly specify your own class, for example:
```
class MyDecorator(Decorator):
def decorate(self):
super(MyDecorator, self).decorate()
```
I have to specify the name of my class `MyDecorator` as an argument to `super()`. This is not DRY. ... | The BDFL agrees. See [Pep 367 - New Super](http://www.python.org/dev/peps/pep-0367/) for 2.6 and [PEP 3135 - New Super](http://www.python.org/dev/peps/pep-3135/) for 3.0. |
Why do I have to specify my own class when using super(), and is there a way to get around it? | 466,611 | 12 | 2009-01-21T19:20:58Z | 466,647 | 10 | 2009-01-21T19:31:04Z | [
"python",
"multiple-inheritance"
] | When using Python's `super()` to do method chaining, you have to explicitly specify your own class, for example:
```
class MyDecorator(Decorator):
def decorate(self):
super(MyDecorator, self).decorate()
```
I have to specify the name of my class `MyDecorator` as an argument to `super()`. This is not DRY. ... | Your wishes come true:
Just use python 3.0. In it you just use `super()` and it does `super(ThisClass, self)`.
Documentation [here](http://docs.python.org/3.0/library/functions.html#super). Code sample from the documentation:
```
class C(B):
def method(self, arg):
super().method(arg)
# This d... |
How can I return system information in Python? | 466,684 | 23 | 2009-01-21T19:40:34Z | 467,291 | 16 | 2009-01-21T22:25:02Z | [
"python",
"operating-system"
] | Using Python, how can information such as CPU usage, memory usage (free, used, etc), process count, etc be returned in a generic manner so that the same code can be run on Linux, Windows, BSD, etc?
Alternatively, how could this information be returned on all the above systems with the code specific to that OS being ru... | Regarding cross-platform: your best bet is probably to write platform-specific code, and then import it conditionally. e.g.
```
import sys
if sys.platform == 'win32':
import win32_sysinfo as sysinfo
elif sys.platform == 'darwin':
import mac_sysinfo as sysinfo
elif 'linux' in sys.platform:
import linux_sysinfo as... |
Python piping on Windows: Why does this not work? | 466,801 | 10 | 2009-01-21T20:20:05Z | 466,849 | 23 | 2009-01-21T20:30:27Z | [
"python",
"windows",
"piping"
] | I'm trying something like this
Output.py
```
print "Hello"
```
Input.py
```
greeting = raw_input("Give me the greeting. ")
print "The greeting is:", greeting
```
At the cmd line
```
Output.py | Input.py
```
But it returns an *EOFError*. Can someone tell me what I am doing wrong?
Thanks for your help.
**EDIT** ... | I tested this on my Windows machine and it works if you specify the Python exe:
```
C:\>C:\Python25\python.exe output.py | C:\Python25\python.exe input.py
Give me the greeting. The greeting is: hello
```
But I get an EOFError also if running the commands directly as:
```
output.py | input.py
```
I'm not sure exactl... |
python: list comprehension tactics | 467,094 | 8 | 2009-01-21T21:27:47Z | 467,102 | 19 | 2009-01-21T21:30:19Z | [
"python",
"list-comprehension"
] | I'm looking to take a string and create a list of strings that build up the original string.
e.g.:
```
"asdf" => ["a", "as", "asd", "asdf"]
```
I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done? | One possibility:
```
>>> st = 'asdf'
>>> [st[:n+1] for n in range(len(st))]
['a', 'as', 'asd', 'asdf']
``` |
python: list comprehension tactics | 467,094 | 8 | 2009-01-21T21:27:47Z | 467,161 | 16 | 2009-01-21T21:47:34Z | [
"python",
"list-comprehension"
] | I'm looking to take a string and create a list of strings that build up the original string.
e.g.:
```
"asdf" => ["a", "as", "asd", "asdf"]
```
I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done? | If you're going to be looping over the elements of your "list", you may be better off using a generator rather than list comprehension:
```
>>> text = "I'm a little teapot."
>>> textgen = (text[:i + 1] for i in xrange(len(text)))
>>> textgen
<generator object <genexpr> at 0x0119BDA0>
>>> for item in textgen:
... i... |
Implementing a "rules engine" in Python | 467,738 | 16 | 2009-01-22T01:11:24Z | 468,737 | 52 | 2009-01-22T11:22:15Z | [
"python",
"parsing",
"rules"
] | I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages.
It needs to feature:
* Regular expression matching for the message itself
* Arithmetic comparisons for message severity/priority
* Boolean operators
I envision An example rule would pr... | Do not invent yet another rules language.
Either use Python or use some other existing, already debugged and working language like BPEL.
Just write your rules in Python, import them and execute them. Life is simpler, far easier to debug, and you've actually solved the actual log-reading problem without creating anoth... |
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)? | 467,800 | 6 | 2009-01-22T01:52:54Z | 467,820 | 13 | 2009-01-22T02:04:14Z | [
"python",
"regex",
"perl",
"iterator"
] | In Python compiled regex patterns [have a `findall` method](http://docs.python.org/library/re.html#re.findall) that does the following:
> Return all non-overlapping matches of
> pattern in string, as a list of
> strings. The string is scanned
> left-to-right, and matches are
> returned in the order found. If one or
> ... | Use the `/g` modifier in your match. From the `perlop` manual:
> The "`/g`" modifier specifies global pattern matching--that is, matching as many times as possible within the string. How it behaves depends on the context. In list context, it returns a list of the substrings matched by any capturing parentheses in the ... |
Is there a Perl equivalent of Python's re.findall/re.finditer (iterative regex results)? | 467,800 | 6 | 2009-01-22T01:52:54Z | 467,874 | 7 | 2009-01-22T02:35:09Z | [
"python",
"regex",
"perl",
"iterator"
] | In Python compiled regex patterns [have a `findall` method](http://docs.python.org/library/re.html#re.findall) that does the following:
> Return all non-overlapping matches of
> pattern in string, as a list of
> strings. The string is scanned
> left-to-right, and matches are
> returned in the order found. If one or
> ... | To build on Chris' response, it's probably most relevant to encase the `//g` regex in a `while` loop, like:
```
my @matches;
while ( 'foobarbaz' =~ m/([aeiou])/g )
{
push @matches, $1;
}
```
Pasting some quick Python I/O:
```
>>> import re
>>> re.findall(r'([aeiou])([nrs])','I had a sandwich for lunch')
[('a', '... |
In what situation should the built-in 'operator' module be used in python? | 467,920 | 21 | 2009-01-22T03:03:46Z | 467,937 | 16 | 2009-01-22T03:15:07Z | [
"python",
"operators"
] | I'm speaking of this module:
<http://docs.python.org/library/operator.html>
From the article:
> The operator module exports a set of
> functions implemented in C
> corresponding to the intrinsic
> operators of Python. For example,
> operator.add(x, y) is equivalent to
> the expression x+y. The function names
> are th... | One example is in the use of the `reduce()` function:
```
>>> import operator
>>> a = [2, 3, 4, 5]
>>> reduce(lambda x, y: x + y, a)
14
>>> reduce(operator.add, a)
14
``` |
In what situation should the built-in 'operator' module be used in python? | 467,920 | 21 | 2009-01-22T03:03:46Z | 467,945 | 22 | 2009-01-22T03:19:40Z | [
"python",
"operators"
] | I'm speaking of this module:
<http://docs.python.org/library/operator.html>
From the article:
> The operator module exports a set of
> functions implemented in C
> corresponding to the intrinsic
> operators of Python. For example,
> operator.add(x, y) is equivalent to
> the expression x+y. The function names
> are th... | Possibly the most popular usage is operator.itemgetter. Given a list `lst` of tuples, you can sort by the ith element by: `lst.sort(key=operator.itemgetter(i))`
Certainly, you could do the same thing without operator by defining your own key function, but the operator module makes it slightly neater.
As to the rest, ... |
Tracking file load progress in Python | 468,238 | 3 | 2009-01-22T06:44:52Z | 468,349 | 7 | 2009-01-22T07:46:14Z | [
"python",
"file",
"load",
"progress"
] | A lot of modules I use import entire files into memory or trickle a file's contents in while they process it. I'm wondering if there's any way to track this sort of loading progress? Possibly a wrapper class that takes a callback? | I would go by this by determining the size of the file, and then simply dividing the total by the number of bytes read. Like this:
```
import os
def show_progress(file_name, chunk_size=1024):
fh = open(file_name, "r")
total_size = os.path.getsize(file_name)
total_read = 0
while True:
chunk = f... |
Ruby equivalent of Python's "dir"? | 468,421 | 39 | 2009-01-22T08:32:05Z | 468,433 | 44 | 2009-01-22T08:39:41Z | [
"python",
"ruby",
"inspection"
] | In Python we can "dir" a module, like this:
```
>>> import re
>>> dir(re)
```
And it lists all functions in the module. Is there a similar way to do this in Ruby? | As far as I know not exactly but you get somewhere with
```
object.methods.sort
``` |
Ruby equivalent of Python's "dir"? | 468,421 | 39 | 2009-01-22T08:32:05Z | 704,557 | 15 | 2009-04-01T08:20:38Z | [
"python",
"ruby",
"inspection"
] | In Python we can "dir" a module, like this:
```
>>> import re
>>> dir(re)
```
And it lists all functions in the module. Is there a similar way to do this in Ruby? | I like to have this in my .irbrc:
```
class Object
def local_methods
(methods - Object.instance_methods).sort
end
end
```
So when I'm in irb:
```
>> Time.now.local_methods
=> ["+", "-", "<", "<=", "<=>", ">", ">=", "_dump", "asctime", "between?", "ctime", "day", "dst?", "getgm", "getlocal", "getutc", "gmt?"... |
How can I listen for 'usb device inserted' events in Linux, in Python? | 469,243 | 28 | 2009-01-22T14:09:59Z | 469,433 | 7 | 2009-01-22T14:59:36Z | [
"python",
"linux",
"usb"
] | I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good examp... | I haven't tried writing such a program myself, however I've just looked at the following two links (thanks Google!), which I think will be of help:
* [dbus-python tutorial](http://dbus.freedesktop.org/doc/dbus-python/doc/tutorial.html) (which talks about how to use Python to access D-Bus)
* [HAL 0.5.10 Specification](... |
How can I listen for 'usb device inserted' events in Linux, in Python? | 469,243 | 28 | 2009-01-22T14:09:59Z | 471,099 | 45 | 2009-01-22T22:27:58Z | [
"python",
"linux",
"usb"
] | I'd like to write a Python script for Amarok in Linux to automatically copy the stackoverflow podcast to my player. When I plug in the player, it would mount the drive, copy any pending podcasts, and eject the player. How can I listen for the "plugged in" event? I have looked through hald but couldn't find a good examp... | **Update**: As said in comments, Hal is not supported in recent distributions, the standard now is udev, Here is a small example that makes use of glib loop and **udev**, I keep the Hal version for historical reasons.
This is basically the [example in the pyudev documentation](http://pyudev.readthedocs.org/en/latest/a... |
problem using an instance in a with_statement | 469,950 | 4 | 2009-01-22T16:58:42Z | 469,992 | 12 | 2009-01-22T17:08:38Z | [
"python",
"with-statement"
] | I've recently started to learn python , and I reached the **with** statement . I've tried to use it with a class instance , but I think I'm doing something wrong . Here is the code :
```
from __future__ import with_statement
import pdb
class Geo:
def __init__(self,text):
self.text = text
def __enter__(self)... | Your `__enter__` method needs to return the object that should be used for the "`as g`" part of the with statement. See the [documentation](http://docs.python.org/reference/compound_stmts.html#with), where it states:
* If a target was included in the with statement, the return value from `__enter__()` is assigned to i... |
Why does 1+++2 = 3 in python? | 470,139 | 16 | 2009-01-22T17:41:44Z | 470,156 | 47 | 2009-01-22T17:46:08Z | [
"python",
"evaluation"
] | I am from C background and I just started learning python...
while trying some programs, I got this doubt...
how python evaluates the expression 1+++2?
No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior
and for 1--2 it is printing 3 and for 1--... | Your expression is the same as:
```
1+(+(+2))
```
Any numeric expression can be preceded by `-` to make it negative, or `+` to do nothing (the option is present for symmetry). With negative signs:
```
1-(-(2)) = 1-(-2)
= 1+2
= 3
```
and
```
1-(-(-2)) = 1-(2)
= -1
```
I see you clarifie... |
Why does 1+++2 = 3 in python? | 470,139 | 16 | 2009-01-22T17:41:44Z | 470,162 | 11 | 2009-01-22T17:47:04Z | [
"python",
"evaluation"
] | I am from C background and I just started learning python...
while trying some programs, I got this doubt...
how python evaluates the expression 1+++2?
No matter how many number of '+' I put in between, it is printing 3 as the answer. Please can anyone explain this behavior
and for 1--2 it is printing 3 and for 1--... | The extra +'s are not incrementors (like ++a or a++ in c++). They are just showing that the number is positive.
There is no such ++ operator. There is a unary + operator and a unary - operator though. The unary + operator has no effect on its argument. The unary - operator negates its operator or mulitplies it by -1.
... |
Jython and python modules | 471,000 | 18 | 2009-01-22T21:57:46Z | 471,143 | 7 | 2009-01-22T22:39:59Z | [
"java",
"python",
"interop",
"jython"
] | I've just started using the `PythonInterpreter` from within my Java classes, and it works great! However, if I try to include python modules (`re`, `HTMLParser`, etc.), I'm receiving the following exception (for `re`):
```
Exception in thread "main" Traceback (innermost last):
File "", line 1, in ?
ImportError: no m... | According to the [FAQ](http://www.jython.org/Project/userfaq.html#jython-modules):
> ## 4.1 What parts of the Python library are supported?
>
> The good news is that Jython now supports a large majority of the standard Python library. The bad news is that this has moved so rapidly, it's hard to keep the documentation ... |
Jython and python modules | 471,000 | 18 | 2009-01-22T21:57:46Z | 483,165 | 14 | 2009-01-27T12:09:48Z | [
"java",
"python",
"interop",
"jython"
] | I've just started using the `PythonInterpreter` from within my Java classes, and it works great! However, if I try to include python modules (`re`, `HTMLParser`, etc.), I'm receiving the following exception (for `re`):
```
Exception in thread "main" Traceback (innermost last):
File "", line 1, in ?
ImportError: no m... | You embed jython and you will use some Python-Modules somewere:
if you want to set the path (sys.path) in your Java-Code :
```
public void init() {
interp = new PythonInterpreter(null, new PySystemState());
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString(rootPath));
... |
Why compile Python code? | 471,191 | 160 | 2009-01-22T22:57:34Z | 471,217 | 7 | 2009-01-22T23:02:39Z | [
"python",
"compilation"
] | Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this? | There's certainly a performance difference when running a compiled script. If you run normal `.py` scripts, the machine compiles it every time it is run and this takes time. On modern machines this is hardly noticeable but as the script grows it may become more of an issue. |
Why compile Python code? | 471,191 | 160 | 2009-01-22T22:57:34Z | 471,220 | 8 | 2009-01-22T23:03:26Z | [
"python",
"compilation"
] | Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this? | There is a performance increase in running compiled python. However when you run a .py file as an imported module, python will compile and store it, and as long as the .py file does not change it will always use the compiled version.
With any interpeted language when the file is used the process looks something like t... |
Why compile Python code? | 471,191 | 160 | 2009-01-22T22:57:34Z | 471,227 | 175 | 2009-01-22T23:06:13Z | [
"python",
"compilation"
] | Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this? | It's compiled to bytecode which can be used much, much, much faster.
The reason some files aren't compiled is that the main script, which you invoke with `python main.py` is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.
*Important addition by [Ben Blank](http:... |
Why compile Python code? | 471,191 | 160 | 2009-01-22T22:57:34Z | 471,242 | 7 | 2009-01-22T23:09:53Z | [
"python",
"compilation"
] | Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this? | As already mentioned, you can get a performance increase from having your python code compiled into bytecode. This is usually handled by python itself, for imported scripts only.
Another reason you might want to compile your python code, could be to protect your intellectual property from being copied and/or modified.... |
Why compile Python code? | 471,191 | 160 | 2009-01-22T22:57:34Z | 471,252 | 57 | 2009-01-22T23:14:33Z | [
"python",
"compilation"
] | Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this? | The .pyc file is Python that has already been compiled to byte-code. Python automatically runs a .pyc file if it finds one with the same name as a .py file you invoke.
"An Introduction to Python" [says](http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html) this about compiled Python files:
> A program ... |
Why compile Python code? | 471,191 | 160 | 2009-01-22T22:57:34Z | 23,256,357 | 20 | 2014-04-23T22:26:10Z | [
"python",
"compilation"
] | Why would you compile a Python script? You can run them directly from the .py file and it works fine, so is there a performance advantage or something?
I also notice that some files in my application get compiled into .pyc while others do not, why is this? | **Pluses:**
First: mild, defeatable obfuscation.
Second: if compilation results in a significantly smaller file, you will get faster load times. Nice for the web.
Third: Python can skip the compilation step. Faster at intial load. Nice for the CPU and the web.
Fourth: the more you comment, the smaller the `.pyc` or... |
Is there a Term::ANSIScreen equivalent for Python? | 471,463 | 3 | 2009-01-23T00:43:24Z | 1,977,010 | 8 | 2009-12-29T21:18:25Z | [
"python",
"perl",
"ansi"
] | Perl has the excellent module `Term::ANSIScreen` for doing all sorts of fancy cursor movement and terminal color control. I'd like to reimplement a program that's currently in Perl in Python instead, but the terminal ANSI colors are key to its function. Is anyone aware of an equivalent? | If you only need colors You may want to borrow the implementation from pygments. IMO it's much cleaner than the one from ActiveState
<http://dev.pocoo.org/hg/pygments-main/file/b2deea5b5030/pygments/console.py> |
Any way to override the and operator in Python? | 471,546 | 18 | 2009-01-23T01:36:42Z | 471,561 | 14 | 2009-01-23T01:42:34Z | [
"python"
] | I tried overriding `__and__`, but that is for the & operator, not *and* - the one that I want. Can I override *and*? | You cannot override the `and`, `or`, and `not` boolean operators. |
Any way to override the and operator in Python? | 471,546 | 18 | 2009-01-23T01:36:42Z | 471,567 | 29 | 2009-01-23T01:44:25Z | [
"python"
] | I tried overriding `__and__`, but that is for the & operator, not *and* - the one that I want. Can I override *and*? | No you can't override `and` and `or`. With the behavior that these have in Python (i.e. short-circuiting) they are more like control flow tools than operators and overriding them would be more like overriding `if` than + or -.
You *can* influence the truth value of your objects (i.e. whether they evaluate as true or f... |
Customizing an Admin form in Django while also using autodiscover | 471,550 | 22 | 2009-01-23T01:38:17Z | 471,661 | 43 | 2009-01-23T02:22:18Z | [
"python",
"django",
"forms",
"django-admin",
"customization"
] | I want to modify a few tiny details of Django's built-in `django.contrib.auth` module. Specifically, I want a different form that makes username an email field (and email an alternate email address. (I'd rather not modify `auth` any more than necessary -- a simple form change *seems* to be all that's needed.)
When I u... | None of the above. Just use admin.site.unregister(). Here's how I recently added filtering Users on is\_active in the admin (**n.b.** is\_active filtering is now on the User model by default in Django core; still works here as an example), all DRY as can be:
```
from django.contrib import admin
from django.contrib.aut... |
Pros and cons of IronPython and IronPython Studio | 471,712 | 16 | 2009-01-23T02:49:32Z | 472,312 | 8 | 2009-01-23T09:06:35Z | [
"python",
"ironpython",
"ironpython-studio"
] | We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we believe IronPython is a good platform for us because it... | There are a lot of reasons why you want to switch from C# to python, i did this myself recently. After a lot of investigating, here are the reasons why i stick to CPython:
* Performance: There are some articles out there stating that there are always cases where ironpython is slower, so if performance is an issue
* Ta... |
Pros and cons of IronPython and IronPython Studio | 471,712 | 16 | 2009-01-23T02:49:32Z | 472,355 | 17 | 2009-01-23T09:29:31Z | [
"python",
"ironpython",
"ironpython-studio"
] | We are ready in our company to move everything to Python instead of C#, we are a consulting company and we usually write small projects in C# we don't do huge projects and our work is more based on complex mathematical models not complex software structures. So we believe IronPython is a good platform for us because it... | My company, Resolver Systems, develops what is probably the biggest application written in IronPython yet. (It's called Resolver One, and it's a Pythonic spreadsheet). We are also hosting the Ironclad project (to run CPython extensions under IronPython) and that is going well (we plan to release a beta of Resolver One ... |
Way to have compiled python files in a separate folder? | 471,928 | 25 | 2009-01-23T05:02:12Z | 471,985 | 16 | 2009-01-23T05:26:17Z | [
"python",
"file",
"compiled"
] | Is it possible to have Python save the `.pyc` files to a separate folder location that is in `sys.path`?
```
/code
foo.py
foo.pyc
bar.py
bar.pyc
```
To:
```
/code
foo.py
bar.py
/code_compiled
foo.pyc
bar.pyc
```
I would like this because I feel it'd be more organized. Thanks for any help... | There is [PEP 304: Controlling Generation of Bytecode Files](http://www.python.org/dev/peps/pep-0304/). Its status is `Withdrawn` and corresponding [patch](http://bugs.python.org/issue677103) rejected. Therefore there might be no direct way to do it.
If you don't need source code then you may just delete `*.py` files.... |
Way to have compiled python files in a separate folder? | 471,928 | 25 | 2009-01-23T05:02:12Z | 16,476,434 | 7 | 2013-05-10T06:30:04Z | [
"python",
"file",
"compiled"
] | Is it possible to have Python save the `.pyc` files to a separate folder location that is in `sys.path`?
```
/code
foo.py
foo.pyc
bar.py
bar.pyc
```
To:
```
/code
foo.py
bar.py
/code_compiled
foo.pyc
bar.pyc
```
I would like this because I feel it'd be more organized. Thanks for any help... | *In the dark and ancient days of 2003, PEP 304 came forth to challenge this problem. Its patch was found wanting. Environment variable platform dependencies and version skews ripped it to shreds and left its bits scattered across the wastelands.*
*After years of suffering, a new challenger rose in the last days of 200... |
Usage of __slots__? | 472,000 | 306 | 2009-01-23T05:37:23Z | 472,017 | 105 | 2009-01-23T05:50:21Z | [
"python"
] | What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python â especially with respect to when would I want to use it and when not? | You would want to use `__slots__` if you are going to instantiate a lot (hundreds, thousands) of objects of the same class. `__slots__` only exists as a memory optimization tool.
It's highly discouraged to use `__slots__` for constraining attribute creation, and in general you want to avoid it because it breaks pickle... |
Usage of __slots__? | 472,000 | 306 | 2009-01-23T05:37:23Z | 472,024 | 243 | 2009-01-23T05:54:46Z | [
"python"
] | What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python â especially with respect to when would I want to use it and when not? | Quoting [Jacob Hallen](http://code.activestate.com/lists/python-list/531365/):
> The proper use of `__slots__` is to save space in objects. Instead of having
> a dynamic dict that allows adding attributes to objects at anytime,
> there is a static structure which does not allow additions after creation.
> This saves t... |
Usage of __slots__? | 472,000 | 306 | 2009-01-23T05:37:23Z | 472,899 | 48 | 2009-01-23T13:38:21Z | [
"python"
] | What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python â especially with respect to when would I want to use it and when not? | Each python object has a `__dict__` atttribute which is a dictionary containing all other attributes. e.g. when you type `self.attr` python is actually doing `self.__dict__['attr']`. As you can imagine using a dictionary to store attribute takes some extra space & time for accessing it.
However, when you use `__slots_... |
Usage of __slots__? | 472,000 | 306 | 2009-01-23T05:37:23Z | 13,547,906 | 10 | 2012-11-25T03:06:11Z | [
"python"
] | What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python â especially with respect to when would I want to use it and when not? | Slots are very useful for library calls to eliminate the "named method dispatch" when making function calls. This is mentioned in the SWIG [documentation](http://www.swig.org/Doc2.0/Python.html#Python_builtin_types). For high performance libraries that want to reduce function overhead for commonly called functions usin... |
Usage of __slots__? | 472,000 | 306 | 2009-01-23T05:37:23Z | 28,059,785 | 119 | 2015-01-21T04:46:42Z | [
"python"
] | What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python â especially with respect to when would I want to use it and when not? | > # In Python, what is the purpose of `__slots__` and what are the cases one should avoid this?
## TLDR:
The special attribute `__slots__` allows you to explicitly state in your code which instance attributes you expect your object instances to have, with the expected results:
1. **faster** attribute access.
2. pote... |
Usage of __slots__? | 472,000 | 306 | 2009-01-23T05:37:23Z | 30,613,834 | 13 | 2015-06-03T07:43:05Z | [
"python"
] | What is the purpose of [`__slots__`](https://docs.python.org/3/reference/datamodel.html#slots) in Python â especially with respect to when would I want to use it and when not? | In addition to the other answers, here is an example of using `__slots__`:
```
>>> class Test(object): #Must be new-style class!
... __slots__ = ['x', 'y']
...
>>> pt = Test()
>>> dir(pt)
['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__',
'__init__', '__module__', '__new__', '__reduce__', '_... |
How to read the header with pycurl | 472,179 | 16 | 2009-01-23T07:21:48Z | 472,243 | 22 | 2009-01-23T08:13:57Z | [
"python",
"curl",
"pycurl"
] | How do I read the response headers returned from a PyCurl request? | There are several solutions (by default, they are dropped). Here is an
example using the option HEADERFUNCTION which lets you indicate a
function to handle them.
Other solutions are options WRITEHEADER (not compatible with
WRITEFUNCTION) or setting HEADER to True so that they are transmitted
with the body.
```
#!/usr... |
How to specify uniqueness for a tuple of field in a Django model | 472,392 | 15 | 2009-01-23T09:50:59Z | 472,688 | 31 | 2009-01-23T12:16:04Z | [
"python",
"django",
"django-models"
] | Is there a way to specify a Model in Django such that is ensures that pair of fields in unique in the table, in a way similar to the "unique=True" attribute for similar field?
Or do I need to check this constraint in the clean() method? | There is a META option called unique\_together. For example:
```
class MyModel(models.Model):
field1 = models.BlahField()
field2 = models.FooField()
field3 = models.BazField()
class Meta:
unique_together = ("field1", "field2")
```
More info on the Django [documentation](http://docs.djangoproj... |
select single item from a collection : Python | 472,575 | 2 | 2009-01-23T11:16:35Z | 473,337 | 12 | 2009-01-23T15:35:10Z | [
"python",
"iterator",
"generator"
] | I created a utility function to return the expected single item from an generator expression
```
print one(name for name in ('bob','fred') if name=='bob')
```
Is this a good way to go about it?
```
def one(g):
try:
val = g.next()
try:
g.next()
except StopIteration:
... | A simpler solution is to use tuple unpacking. This will already do everything you want, including checking that it contains exactly one item.
Single item:
```
>>> name, = (name for name in ('bob','fred') if name=='bob')
>>> name
'bob'
```
Too many items:
```
>>> name, = (name for name in ('bob','bob') if name=='... |
Binary data with pyserial(python serial port) | 472,977 | 15 | 2009-01-23T14:02:43Z | 473,057 | 9 | 2009-01-23T14:25:28Z | [
"python",
"binary",
"serial-port",
"pyserial"
] | serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?
I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem... | You need to convert your data to a string
```
"\xc0\x04\x00"
```
Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte `"\x00"`.
One way to do this:
```
>>> import array
>>> array.array('B', [0xc0, 0x04, 0x00]).tostring()
'\xc0\x04\x00'
``` |
Binary data with pyserial(python serial port) | 472,977 | 15 | 2009-01-23T14:02:43Z | 1,281,992 | 12 | 2009-08-15T14:19:51Z | [
"python",
"binary",
"serial-port",
"pyserial"
] | serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?
I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem... | An alternative method, without using the `array` module:
```
def a2s(arr):
""" Array of integer byte values --> binary string
"""
return ''.join(chr(b) for b in arr)
``` |
Check if a given key already exists in a dictionary and increment it | 473,099 | 163 | 2009-01-23T14:35:39Z | 473,108 | 182 | 2009-01-23T14:38:49Z | [
"python",
"dictionary"
] | Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
```
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
```
I.e., I want to increment the value if there's already one there, or set it to 1 ot... | You are looking for [`collections.defaultdict`](http://docs.python.org/library/collections.html#defaultdict) (available for Python 2.5+). This
```
from collections import defaultdict
my_dict = defaultdict(int)
my_dict[key] += 1
```
will do what you want.
For regular Python `dict`s, if there is no value for a given ... |
Check if a given key already exists in a dictionary and increment it | 473,099 | 163 | 2009-01-23T14:35:39Z | 473,114 | 41 | 2009-01-23T14:41:38Z | [
"python",
"dictionary"
] | Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
```
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
```
I.e., I want to increment the value if there's already one there, or set it to 1 ot... | You need the `key in dict` idiom for that.
```
if key in my_dict and not (my_dict[key] is None):
# do something
else:
# do something else
```
However, you should probably consider using `defaultdict` (as dF suggested). |
Check if a given key already exists in a dictionary and increment it | 473,099 | 163 | 2009-01-23T14:35:39Z | 473,227 | 8 | 2009-01-23T15:09:59Z | [
"python",
"dictionary"
] | Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
```
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
```
I.e., I want to increment the value if there's already one there, or set it to 1 ot... | Agreed with cgoldberg. How I do it is:
```
try:
dict[key] += 1
except KeyError:
dict[key] = 1
```
So either do it as above, or use a default dict as others have suggested. Don't use if statements. That's not Pythonic. |
Check if a given key already exists in a dictionary and increment it | 473,099 | 163 | 2009-01-23T14:35:39Z | 473,344 | 152 | 2009-01-23T15:39:05Z | [
"python",
"dictionary"
] | Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
```
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
```
I.e., I want to increment the value if there's already one there, or set it to 1 ot... | I prefer to do this in one line of code.
```
my_dict = {}
my_dict[some_key] = my_dict.get(some_key, 0) + 1
```
Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the k... |
Check if a given key already exists in a dictionary and increment it | 473,099 | 163 | 2009-01-23T14:35:39Z | 473,501 | 10 | 2009-01-23T16:17:20Z | [
"python",
"dictionary"
] | Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
```
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
```
I.e., I want to increment the value if there's already one there, or set it to 1 ot... | As you can see from the many answers, there are several solutions. One instance of LBYL (look before you leap) has not been mentioned yet, the has\_key() method:
```
my_dict = {}
def add (key):
if my_dict.has_key(key):
my_dict[key] += 1
else:
my_dict[key] = 1
if __name__ == '__main__':
ad... |
Check if a given key already exists in a dictionary and increment it | 473,099 | 163 | 2009-01-23T14:35:39Z | 2,198,921 | 9 | 2010-02-04T10:32:38Z | [
"python",
"dictionary"
] | Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
```
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
```
I.e., I want to increment the value if there's already one there, or set it to 1 ot... | To answer the question "*how can I find out if a given index in that dict has already been set to a non-None value*", I would prefer this:
```
try:
nonNone = my_dict[key] is not None
except KeyError:
nonNone = False
```
This conforms to the already invoked concept of EAFP (easier to ask forgiveness then permissio... |
Check if a given key already exists in a dictionary and increment it | 473,099 | 163 | 2009-01-23T14:35:39Z | 7,924,128 | 14 | 2011-10-28T01:03:34Z | [
"python",
"dictionary"
] | Given a dictionary, how can I find out if a given key in that dictionary has already been set to a non-None value?
I.e., I want to do this:
```
my_dict = {}
if (my_dict[key] != None):
my_dict[key] = 1
else:
my_dict[key] += 1
```
I.e., I want to increment the value if there's already one there, or set it to 1 ot... | I personally like using `setdefault()`
```
my_dict = {}
my_dict.setdefault(some_key, 0)
my_dict[some_key] += 1
``` |
How do you create a daemon in Python? | 473,620 | 185 | 2009-01-23T16:48:06Z | 473,702 | 114 | 2009-01-23T17:06:11Z | [
"python",
"daemon"
] | [Searching on Google](http://www.google.co.uk/search?q=python+daemon) reveals x2 code snippets. The first result is to [this code recipe](http://code.activestate.com/recipes/278731/) which has a lot of documentation and explanation, along with some useful discussion underneath.
However, [another code sample](http://ww... | Sander Marechal's [code sample](http://web.archive.org/web/20131017130434/http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/) is superior to the original, which was originally posted in 2004. I once contributed a daemonizer for Pyro, but would probably use Sander's code if I had to do it over. |
How do you create a daemon in Python? | 473,620 | 185 | 2009-01-23T16:48:06Z | 688,448 | 133 | 2009-03-27T03:38:06Z | [
"python",
"daemon"
] | [Searching on Google](http://www.google.co.uk/search?q=python+daemon) reveals x2 code snippets. The first result is to [this code recipe](http://code.activestate.com/recipes/278731/) which has a lot of documentation and explanation, along with some useful discussion underneath.
However, [another code sample](http://ww... | There are **many fiddly things** to take care of when becoming a [well-behaved daemon process](http://www.python.org/dev/peps/pep-3143/#correct-daemon-behaviour):
* prevent core dumps (many daemons run as root, and core dumps can contain sensitive information)
* behave correctly inside a `chroot` gaol
* set UID, GID, ... |
How do you create a daemon in Python? | 473,620 | 185 | 2009-01-23T16:48:06Z | 5,412,949 | 38 | 2011-03-23T23:28:03Z | [
"python",
"daemon"
] | [Searching on Google](http://www.google.co.uk/search?q=python+daemon) reveals x2 code snippets. The first result is to [this code recipe](http://code.activestate.com/recipes/278731/) which has a lot of documentation and explanation, along with some useful discussion underneath.
However, [another code sample](http://ww... | Note the [python-daemon](http://pypi.python.org/pypi/python-daemon/) package which solves a lot of problems behind daemons out of the box.
Among other features it enables to (from Debian package description):
* Detach the process into its own process group.
* Set process environment appropriate for running inside a c... |
How do you create a daemon in Python? | 473,620 | 185 | 2009-01-23T16:48:06Z | 9,047,339 | 74 | 2012-01-28T17:33:44Z | [
"python",
"daemon"
] | [Searching on Google](http://www.google.co.uk/search?q=python+daemon) reveals x2 code snippets. The first result is to [this code recipe](http://code.activestate.com/recipes/278731/) which has a lot of documentation and explanation, along with some useful discussion underneath.
However, [another code sample](http://ww... | Here's my basic 'Howdy World' Python daemon that I start with, when I'm developing a new daemon application.
```
#!/usr/bin/python
import time
from daemon import runner
class App():
def __init__(self):
self.stdin_path = '/dev/null'
self.stdout_path = '/dev/tty'
self.stderr_path = '/dev/tty... |
How do you create a daemon in Python? | 473,620 | 185 | 2009-01-23T16:48:06Z | 17,255,175 | 17 | 2013-06-22T20:50:01Z | [
"python",
"daemon"
] | [Searching on Google](http://www.google.co.uk/search?q=python+daemon) reveals x2 code snippets. The first result is to [this code recipe](http://code.activestate.com/recipes/278731/) which has a lot of documentation and explanation, along with some useful discussion underneath.
However, [another code sample](http://ww... | An alternative -- create a normal, non-daemonized Python program then externally daemonize it using [supervisord](http://supervisord.org/ "supervisord"). This can save a lot of headaches, and is \*nix- and language-portable. |
Shuffle an array with python, randomize array item order with python | 473,973 | 120 | 2009-01-23T18:34:29Z | 473,983 | 242 | 2009-01-23T18:37:27Z | [
"python",
"arrays",
"random",
"order"
] | What's the easiest way to shuffle an array with python? | ```
import random
random.shuffle(array)
``` |
Shuffle an array with python, randomize array item order with python | 473,973 | 120 | 2009-01-23T18:34:29Z | 473,988 | 75 | 2009-01-23T18:38:14Z | [
"python",
"arrays",
"random",
"order"
] | What's the easiest way to shuffle an array with python? | ```
import random
random.shuffle(array)
``` |
Shuffle an array with python, randomize array item order with python | 473,973 | 120 | 2009-01-23T18:34:29Z | 8,582,589 | 16 | 2011-12-20T22:05:30Z | [
"python",
"arrays",
"random",
"order"
] | What's the easiest way to shuffle an array with python? | The other answers are the easiest, however it's a bit annoying that the `random.shuffle` method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:
```
import random
def my_shuffle(array):
random... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.