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 |
|---|---|---|---|---|---|---|---|---|---|
Sorting by arbitrary lambda | 3,216,398 | 25 | 2010-07-09T20:40:26Z | 3,216,418 | 28 | 2010-07-09T20:44:06Z | [
"python",
"sorting"
] | How can I sort a list by a key described by an arbitrary function? For example, if I have:
```
mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
```
I'd like to sort "mylist" by the second element of each member, e.g.
```
sort(mylist, key=lambda x: x[1])
```
how can I do this? | You basically have it already:
```
>>> mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
>>> mylist.sort(key=lambda x: x[1])
>>> print mylist
```
gives:
```
[['bar', 0, 'b'], ['quux', 1, 'a']]
```
That will sort mylist in place.
[this para edited thanks to @Daniel's correction.] `sorted` will return a new list that is ... |
Sorting by arbitrary lambda | 3,216,398 | 25 | 2010-07-09T20:40:26Z | 3,216,507 | 9 | 2010-07-09T20:57:32Z | [
"python",
"sorting"
] | How can I sort a list by a key described by an arbitrary function? For example, if I have:
```
mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
```
I'd like to sort "mylist" by the second element of each member, e.g.
```
sort(mylist, key=lambda x: x[1])
```
how can I do this? | This is such a common need that support for it has been added to the standard library, in the form of [`operator.itemgetter`](http://docs.python.org/library/operator.html#operator.itemgetter):
```
from operator import itemgetter
mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
mylist.sort(key=itemgetter(1)) # or sorted(my... |
Which of `if x:` or `if x != 0:` is preferred in Python? | 3,216,681 | 4 | 2010-07-09T21:28:12Z | 3,216,694 | 7 | 2010-07-09T21:30:09Z | [
"python",
"coding-style",
"conditional"
] | Assuming that `x` is an integer, the construct `if x:` is functionally the same as `if x != 0:` in Python. Some languages' style guides explicitly forbid against the former -- for example, ActionScript/Flex's style guide states that you should never implicitly cast an int to bool for this sort of thing.
Does Python ha... | The construct: `if x:` is generally used to check against boolean values.
For `int`s the use of the explicit `x != 0` is preferred - along the lines of *explicit is better than implicit* ([PEP 20 - Zen of Python](http://www.python.org/dev/peps/pep-0020/)). |
If x is list, why does x += "ha" work, while x = x + "ha" throws an exception? | 3,216,706 | 46 | 2010-07-09T21:32:46Z | 3,216,728 | 33 | 2010-07-09T21:36:37Z | [
"python",
"list",
"operators"
] | From what little I know, + op for lists only requires the 2nd operand to be iterable, which "ha" clearly is.
In code:
```
>>> x = []
>>> x += "ha"
>>> x
['h', 'a']
>>> x = x + "ha"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
``` | Using `+=` with a list is like calling `extend`, not `+`.
* You can call `extend` with an iterable.
* You can only use `+` with another list.
I can only guess why this decision was made, but I imagine it is for performance reasons. Calling `+` results in a new object being created and all items being copied, whereas ... |
If x is list, why does x += "ha" work, while x = x + "ha" throws an exception? | 3,216,706 | 46 | 2010-07-09T21:32:46Z | 3,216,740 | 8 | 2010-07-09T21:40:24Z | [
"python",
"list",
"operators"
] | From what little I know, + op for lists only requires the 2nd operand to be iterable, which "ha" clearly is.
In code:
```
>>> x = []
>>> x += "ha"
>>> x
['h', 'a']
>>> x = x + "ha"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
``` | You're thinking about it backwards. You're asking why `x = x + 'ha'` throws an exception, given that `x += 'ha'` works. Really, the question is why `x += 'ha'` works at all.
Everyone agrees (I hope) that `'abc' + 'ha'` and `[1, 2, 3] + ['h', 'a']` should work. And in these cases, overloading `+=` to do in-place modifi... |
Python: Amazon AWS interface? | 3,216,791 | 3 | 2010-07-09T21:54:05Z | 3,312,582 | 20 | 2010-07-22T19:23:53Z | [
"python",
"amazon-web-services"
] | Googling reveals several Python interfaces to [Amazon Web Services (AWS)](http://aws.amazon.com/). Which are the most popular, feature-complete, etc? | I suggest [boto](http://code.google.com/p/boto/) - It's an active project, and boto's new home is now on [GitHub](https://github.com/boto/boto), so you can fork it and add/patch it as desired (not that you need to - it seems very stable).
The author recently got a job that lets him hack on this part time for work, see... |
Python: No csv.close()? | 3,216,954 | 33 | 2010-07-09T22:31:17Z | 3,216,980 | 20 | 2010-07-09T22:36:50Z | [
"python",
"csv"
] | I'm using the CSV module to read a tab delimited file. Code below:
```
z = csv.reader(open('/home/rv/ncbi-blast-2.2.23+/db/output.blast'), delimiter='\t')
```
But when I add Z.close() to end of my script i get and error stating "csv.reader' object has no attribute 'close'"
```
z.close()
```
So how do i close "Z"? | You do not close CSV readers directly; instead you should close whatever file-like object is being used. For example, in your case, you'd say:
```
f = open('/home/rv/ncbi-blast-2.2.23+/db/output.blast')
z = csv.reader(f, delimiter='\t')
...
f.close()
```
If you are using a recent version of Python, you can use the wi... |
Python: No csv.close()? | 3,216,954 | 33 | 2010-07-09T22:31:17Z | 3,216,986 | 32 | 2010-07-09T22:38:05Z | [
"python",
"csv"
] | I'm using the CSV module to read a tab delimited file. Code below:
```
z = csv.reader(open('/home/rv/ncbi-blast-2.2.23+/db/output.blast'), delimiter='\t')
```
But when I add Z.close() to end of my script i get and error stating "csv.reader' object has no attribute 'close'"
```
z.close()
```
So how do i close "Z"? | The reader is really just a parser. When you ask it for a line of data, it delegates the reading action to the underlying `file` object and just converts the result into a set of fields. So there's no need to close the reader; it'd be a meaningless operation.
You should make sure to close the underlying `file` object,... |
How do you pass a Queue reference to a function managed by pool.map_async()? | 3,217,002 | 28 | 2010-07-09T22:42:09Z | 3,232,026 | 37 | 2010-07-12T20:30:58Z | [
"python",
"queue",
"multiprocessing",
"pool"
] | I want a long-running process to return its progress over a Queue (or something similar) which I will feed to a progress bar dialog. I also need the result when the process is completed. A test example here fails with a RuntimeError: Queue objects should only be shared between processes through inheritance.
```
import... | The following code seems to work:
```
import multiprocessing, time
def task(args):
count = args[0]
queue = args[1]
for i in xrange(count):
queue.put("%d mississippi" % i)
return "Done"
def main():
manager = multiprocessing.Manager()
q = manager.Queue()
pool = multiprocessing.Pool... |
Why use argparse rather than optparse? | 3,217,673 | 183 | 2010-07-10T03:16:00Z | 3,217,681 | 30 | 2010-07-10T03:20:46Z | [
"python",
"command-line",
"optparse",
"getopt",
"argparse"
] | I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to `getopt` and `optparse` we now have `argparse`.
Why has yet another command-line parsing module been created? Why should I use it instead of `optparse`? Are there new features that I should know about? | The best source for rationale for a Python addition would be its PEP: [PEP 389: argparse - New Command Line Parsing Module](http://www.python.org/dev/peps/pep-0389/), in particular, the section entitled, [Why aren't getopt and optparse enough?](http://www.python.org/dev/peps/pep-0389/#why-aren-t-getopt-and-optparse-eno... |
Why use argparse rather than optparse? | 3,217,673 | 183 | 2010-07-10T03:16:00Z | 3,217,687 | 197 | 2010-07-10T03:22:22Z | [
"python",
"command-line",
"optparse",
"getopt",
"argparse"
] | I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to `getopt` and `optparse` we now have `argparse`.
Why has yet another command-line parsing module been created? Why should I use it instead of `optparse`? Are there new features that I should know about? | As of 2.7, optparse is deprecated, and will hopefully go away in the future.
argparse is better for all the reasons listed on its original page ([<http://code.google.com/p/argparse/>](http://code.google.com/p/argparse/)):
* handling positional arguments
* supporting sub-commands
* allowing alternative option prefixes... |
Why use argparse rather than optparse? | 3,217,673 | 183 | 2010-07-10T03:16:00Z | 3,217,926 | 50 | 2010-07-10T05:10:55Z | [
"python",
"command-line",
"optparse",
"getopt",
"argparse"
] | I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to `getopt` and `optparse` we now have `argparse`.
Why has yet another command-line parsing module been created? Why should I use it instead of `optparse`? Are there new features that I should know about? | > Why should I use it instead of
> optparse? Are their new features I
> should know about?
@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:
> Why has yet another command-line
> parsing module been created?
That's the dilemma number one when any useful module is added to ... |
Checking validity of email in django/python | 3,217,682 | 45 | 2010-07-10T03:21:15Z | 3,217,703 | 44 | 2010-07-10T03:27:03Z | [
"python",
"regex",
"django",
"validation",
"email"
] | I have written a function for adding emails to newsletter base. Until I've added checking validity of sent email it was working flawlessly. Now each time I'm getting "Wrong email" in return. Can anybody see any errors here ? The regex used is :
`\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b` and it is 100% valid (http://gskinner.com... | Ick, no, please, don't try to validate email addresses yourself. It's one of those things people never get right.
Your safest option, since you're already using Django, is to just take advantage of its form validation for email. Per the docs ( <http://docs.djangoproject.com/en/dev/ref/forms/fields/> ):
```
>>> from d... |
Checking validity of email in django/python | 3,217,682 | 45 | 2010-07-10T03:21:15Z | 3,217,737 | 7 | 2010-07-10T03:45:46Z | [
"python",
"regex",
"django",
"validation",
"email"
] | I have written a function for adding emails to newsletter base. Until I've added checking validity of sent email it was working flawlessly. Now each time I'm getting "Wrong email" in return. Can anybody see any errors here ? The regex used is :
`\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b` and it is 100% valid (http://gskinner.com... | You got it wrong, but it is a task that you can't do anyway. There is one and only one way to know if an [RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) address is valid, and that is to send mail to it and get a response. Doing anything else doesn't improve the information content of your datum by even a fractional bit... |
Checking validity of email in django/python | 3,217,682 | 45 | 2010-07-10T03:21:15Z | 3,218,128 | 118 | 2010-07-10T06:32:44Z | [
"python",
"regex",
"django",
"validation",
"email"
] | I have written a function for adding emails to newsletter base. Until I've added checking validity of sent email it was working flawlessly. Now each time I'm getting "Wrong email" in return. Can anybody see any errors here ? The regex used is :
`\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b` and it is 100% valid (http://gskinner.com... | Here is part of django.core.validators you may find interesting :)
```
class EmailValidator(RegexValidator):
def __call__(self, value):
try:
super(EmailValidator, self).__call__(value)
except ValidationError, e:
# Trivial case failed. Try for possible IDN domain-part
... |
Checking validity of email in django/python | 3,217,682 | 45 | 2010-07-10T03:21:15Z | 19,222,468 | 74 | 2013-10-07T10:29:56Z | [
"python",
"regex",
"django",
"validation",
"email"
] | I have written a function for adding emails to newsletter base. Until I've added checking validity of sent email it was working flawlessly. Now each time I'm getting "Wrong email" in return. Can anybody see any errors here ? The regex used is :
`\b[\w\.-]+@[\w\.-]+\.\w{2,4}\b` and it is 100% valid (http://gskinner.com... | ```
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
try:
validate_email("foo.bar@baz.qux")
except ValidationError as e:
print "oops! wrong email"
else:
print "hooray! email is valid"
``` |
How to pass a variable to a re.sub callback? | 3,218,283 | 2 | 2010-07-10T07:26:38Z | 3,218,311 | 9 | 2010-07-10T07:36:33Z | [
"python",
"regex",
"callback"
] | I am using a re.sub callback to replace substrings with random values, but I would like the random values to be the same across different strings. Since the re.sub callback does not allow arguments, I am not sure how to do this.
Here is a simplified version of what I'm doing:
```
def evaluate(match):
mappings = {... | The easiest way I guess is to make use of `functools.partial`, which allows you create a "partially evaluated" function:
```
from functools import partial
def evaluate(match, mappings):
return str(eval(match.group(0)[2:-1], mappings))
mappings = {'A': 1, 'B': 2} # Or whatever ...
newstring = sub(r'\#\{([^#]+)\... |
Types for which "is" keyword may be equivalent to equality operator in Python | 3,218,308 | 3 | 2010-07-10T07:35:39Z | 3,218,350 | 7 | 2010-07-10T07:46:30Z | [
"python",
"reference",
"identity",
"variable-assignment",
"immutability"
] | For some types in Python, the `is` operator seems to be equivalent to the `==` operator. For example:
```
>>> 1 is 1
True
>>> "a spoon" is "a spoon"
True
>>> (1 == 1) is (2 == 2)
True
```
However, this is not always the case:
```
>>> [] == []
True
>>> [] is []
False
```
This makes sense for mutable types such as li... | > Is the == / is equivalence related to immutability?
No.
See [*Python â==â vs âisâ comparing strings, âisâ fails sometimes, why?*](http://stackoverflow.com/questions/1504717/python-vs-is-comparing-strings-is-fails-sometimes-why/1504848#1504848) on why it works on strings, and [*Python âisâ operator b... |
Types for which "is" keyword may be equivalent to equality operator in Python | 3,218,308 | 3 | 2010-07-10T07:35:39Z | 3,218,367 | 9 | 2010-07-10T07:52:16Z | [
"python",
"reference",
"identity",
"variable-assignment",
"immutability"
] | For some types in Python, the `is` operator seems to be equivalent to the `==` operator. For example:
```
>>> 1 is 1
True
>>> "a spoon" is "a spoon"
True
>>> (1 == 1) is (2 == 2)
True
```
However, this is not always the case:
```
>>> [] == []
True
>>> [] is []
False
```
This makes sense for mutable types such as li... | The `is` operator tests if two objects are physically the same, that means if they have the same address in memory. This can also be tested using the `id()` function:
```
>>> a = 1
>>> b = 1
>>> a is b
True
>>> id(a) == id(b)
True
```
The `==` operator on the other hand, tests for semantical equality. This can also b... |
Handling large dense matrices in python | 3,218,645 | 3 | 2010-07-10T09:29:28Z | 3,315,055 | 10 | 2010-07-23T02:47:56Z | [
"python",
"matrix",
"32-bit",
"python-2.6",
"windows-xp"
] | Basically, what is the best way to go about storing and using dense matrices in python?
I have a project that generates similarity metrics between every item in an array.
Each item is a custom class, and stores a pointer to the other class and a number representing it's "closeness" to that class.
Right now, it works... | Well, I've found my solution:
[h5py](http://code.google.com/p/h5py/)
It's a library that basically presents a numpy-like interface, but uses compressed memmapped files to store arrays of arbitrary size (It's basically a wrapper for HDF5).
PyTables is built on it, and PyTables actually led me to it. However, I do no... |
generating equation png files based on mathematical input | 3,219,098 | 9 | 2010-07-10T11:56:36Z | 3,219,105 | 9 | 2010-07-10T11:58:01Z | [
"python",
"math",
"equation"
] | I was wondering what options were available to generate .png based on the kind of input one feeds a graphing calculator.. so
(y^2 + 5x + 3) / ((3x + 3) + 5y + 18)
would return

The only thing I've found so far is texvc in mediawiki, but it seems overkill to get the whole med... | The [Google Chart API](http://code.google.com/apis/chart/) has this function, it takes [TeX input](http://code.google.com/apis/chart/docs/gallery/formulas.html) and creates an output image.
> ]
```
I know that the list always contains one 1-tuple. Currently I do this:
```
>>> dummy, = t
>>> value, = dummy
>>> value
'asdf'
```
Is there a shorter and more elegant way to do this? | Try
```
(value,), = t
```
It's better than `t[0][0]` because it also asserts that your list contains exactly 1 tuple with 1 value in it. |
Unpacking a 1-tuple in a list of length 1 | 3,219,573 | 6 | 2010-07-10T14:34:10Z | 3,219,582 | 9 | 2010-07-10T14:36:53Z | [
"python",
"list",
"tuples",
"iterable-unpacking"
] | Suppose I have a tuple in a list like this:
```
>>> t = [("asdf", )]
```
I know that the list always contains one 1-tuple. Currently I do this:
```
>>> dummy, = t
>>> value, = dummy
>>> value
'asdf'
```
Is there a shorter and more elegant way to do this? | ```
>>> t = [("asdf", )]
>>> t[0][0]
'asdf'
``` |
Escaping chars in Python and sqlite | 3,220,005 | 30 | 2010-07-10T16:41:38Z | 3,220,028 | 73 | 2010-07-10T16:48:42Z | [
"python",
"sqlite",
"sqlite3"
] | I have a python script that reads raw movie text files into an sqlite database.
I use re.escape(title) to add escape chars into the strings to make them db safe before executing the inserts.
Why does this not work:
```
In [16]: c.execute("UPDATE movies SET rating = '8.7' WHERE name='\'Allo\ \'Allo\!\"\ \(1982\)'")
-... | You're doing it wrong. Literally. You should be using parameters, like this:
```
c.execute("UPDATE movies SET rating = ? WHERE name = ?", (8.7, "'Allo 'Allo! (1982)"))
```
Like that, you won't need to do *any* quoting at all and (if those values are coming from anyone untrusted) you'll be 100% safe (here) from SQL in... |
Escaping chars in Python and sqlite | 3,220,005 | 30 | 2010-07-10T16:41:38Z | 3,220,082 | 7 | 2010-07-10T17:08:09Z | [
"python",
"sqlite",
"sqlite3"
] | I have a python script that reads raw movie text files into an sqlite database.
I use re.escape(title) to add escape chars into the strings to make them db safe before executing the inserts.
Why does this not work:
```
In [16]: c.execute("UPDATE movies SET rating = '8.7' WHERE name='\'Allo\ \'Allo\!\"\ \(1982\)'")
-... | > I use re.escape(title) to add escape
> chars into the strings to make them db
> safe
Note that `re.escape` makes a string **re**-safe -- nothing to do with making it **db** safe. Rather, as @Donal says, what you need is the *parameter substitution* concept of the Python DB API -- **that** makes things "db safe" as y... |
How to filter (or replace) unicode characters that would take more than 3 bytes in UTF-8? | 3,220,031 | 26 | 2010-07-10T16:49:38Z | 3,220,210 | 24 | 2010-07-10T17:37:48Z | [
"python",
"mysql",
"django",
"unicode"
] | I'm using Python and Django, but I'm having a problem caused by a limitation of MySQL. According to the [MySQL 5.1 documentation](http://dev.mysql.com/doc/refman/5.1/en/charset-unicode-utf8.html), their `utf8` implementation does not support 4-byte characters. [MySQL 5.5](http://dev.mysql.com/doc/refman/5.5/en/charset-... | Unicode characters in the ranges \u0000-\uD7FF and \uE000-\uFFFF will have 3 byte (or less) encodings in UTF8. The \uD800-\uDFFF range is for multibyte UTF16. I do not know python, but you should be able to set up a regular expression to match outside those ranges.
```
pattern = re.compile("[\uD800-\uDFFF].", re.UNICO... |
Check if python int is too large to convert to float | 3,220,074 | 4 | 2010-07-10T17:04:58Z | 3,220,091 | 13 | 2010-07-10T17:10:11Z | [
"python",
"floating-point",
"integer"
] | Is there any way to check if a long integer is too large to convert to a float in python? | ```
>>> import sys
>>> sys.float_info.max
1.7976931348623157e+308
```
Actually, if you try to convert an integer too big to a float, an exception will be raised.
```
>>> float(2 * 10**308)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C doub... |
How do I install an old version of Django on virtualenv? | 3,220,280 | 56 | 2010-07-10T17:55:47Z | 3,220,470 | 92 | 2010-07-10T19:04:48Z | [
"python",
"django",
"setuptools",
"virtualenv"
] | This may sound like a stupid question, since the very purpose of `virtualenv` is to this exactly: Installing some specific version of a package (in this case Django) inside the virtual environment. But it's exactly what I want to do, and I can't figure it out.
I'm on Windows XP, and I created the virtual environment s... | There was never a Django 1.0.7. The 1.0 series only went up to 1.0.4. You can see all the releases in the [tags section of the Django code repository](http://code.djangoproject.com/browser/django/tags/releases).
However to answer your question, don't use `easy_install`, use `pip`. (If it's not already installed, do `e... |
How to Customize the time format for Python logging? | 3,220,284 | 69 | 2010-07-10T17:56:39Z | 3,220,312 | 79 | 2010-07-10T18:05:33Z | [
"python",
"datetime",
"logging",
"formatting"
] | I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:
```
import logging
# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)
# create console handler and se... | From the [official documentation](http://docs.python.org/2/library/logging.html#logging.Formatter) regarding the Formatter class:
> The constructor takes two optional arguments: a message format string and a date format string.
So change
```
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s... |
How to Customize the time format for Python logging? | 3,220,284 | 69 | 2010-07-10T17:56:39Z | 6,127,057 | 19 | 2011-05-25T15:34:57Z | [
"python",
"datetime",
"logging",
"formatting"
] | I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:
```
import logging
# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)
# create console handler and se... | if using logging.config.fileConfig with a configuration file use something like:
```
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S
``` |
How to Customize the time format for Python logging? | 3,220,284 | 69 | 2010-07-10T17:56:39Z | 23,874,319 | 26 | 2014-05-26T16:26:52Z | [
"python",
"datetime",
"logging",
"formatting"
] | I am new to Python's logging package and plan to use it for my project. I would like to customize the time format to my taste. Here is a short code I copied from a tutorial:
```
import logging
# create logger
logger = logging.getLogger("logging_tryout2")
logger.setLevel(logging.DEBUG)
# create console handler and se... | Using logging.basicConfig, the following example works for me:
```
logging.basicConfig(filename='HISTORYlistener.log',level=logging.DEBUG,
format='%(asctime)s.%(msecs)d %(levelname)s %(module)s - %(funcName)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S")
```
This allows you to format & config all in one line. A... |
Management form error while using modelformsets ('ManagementForm data is missing or has been tampered with') | 3,220,420 | 5 | 2010-07-10T18:43:37Z | 3,221,269 | 23 | 2010-07-10T23:45:39Z | [
"python",
"django",
"django-forms"
] | I have a models.py class as below
```
class Educational_Qualification(models.Model):
user = models.ForeignKey(User)
exam = models.CharField(max_length=40)
pass_month = models.CharField(max_length=40)
```
I have a views.py as below
```
def create_qualification(request):
QFormSet = modelformset_factory(Educa... | The error is not in your views or the models, but in the templates.
The right way to render the formset, is:
```
<form method="post" action="">
<table>
{{ formset }}
</table>
</form>
```
or
```
<form method="post" action="">
{{ formset.management_form }}
<table>
{% for form in formse... |
Read all the contents in ini file into dictionary with Python | 3,220,670 | 14 | 2010-07-10T20:06:04Z | 3,220,740 | 15 | 2010-07-10T20:31:57Z | [
"python",
"configuration-files",
"ini"
] | Normally, I code as follows for getting a particular item in a variable as follows
```
try:
config = ConfigParser.ConfigParser()
config.read(self.iniPathName)
except ConfigParser.MissingSectionHeaderError, e:
raise WrongIniFormatError(`e`)
try:
self.makeDB = config.get("DB","makeDB")
except ConfigPars... | I managed to get an answer, but I expect there should be a better one.
```
dictionary = {}
for section in config.sections():
dictionary[section] = {}
for option in config.options(section):
dictionary[section][option] = config.get(section, option)
``` |
Read all the contents in ini file into dictionary with Python | 3,220,670 | 14 | 2010-07-10T20:06:04Z | 3,220,887 | 9 | 2010-07-10T21:24:32Z | [
"python",
"configuration-files",
"ini"
] | Normally, I code as follows for getting a particular item in a variable as follows
```
try:
config = ConfigParser.ConfigParser()
config.read(self.iniPathName)
except ConfigParser.MissingSectionHeaderError, e:
raise WrongIniFormatError(`e`)
try:
self.makeDB = config.get("DB","makeDB")
except ConfigPars... | The instance data for ConfigParser is stored internally as a nested dict. Instead of recreating it, you could just copy it.
```
>>> import ConfigParser
>>> p = ConfigParser.ConfigParser()
>>> p.read("sample_config.ini")
['sample_config.ini']
>>> p.__dict__
{'_defaults': {}, '_sections': {'A': {'y': '2', '__name__': 'A... |
Read all the contents in ini file into dictionary with Python | 3,220,670 | 14 | 2010-07-10T20:06:04Z | 3,220,891 | 22 | 2010-07-10T21:26:01Z | [
"python",
"configuration-files",
"ini"
] | Normally, I code as follows for getting a particular item in a variable as follows
```
try:
config = ConfigParser.ConfigParser()
config.read(self.iniPathName)
except ConfigParser.MissingSectionHeaderError, e:
raise WrongIniFormatError(`e`)
try:
self.makeDB = config.get("DB","makeDB")
except ConfigPars... | I suggest subclassing `ConfigParser.ConfigParser` (or `SafeConfigParser`, &c) to safely access the "protected" attributes (names starting with single underscore -- "private" would be names starting with *two* underscores, not to be accessed even in subclasses...):
```
import ConfigParser
class MyParser(ConfigParser.C... |
how to find the target file's full(absolute path) of the symbolic link or soft link in python | 3,220,755 | 28 | 2010-07-10T20:36:12Z | 3,220,762 | 7 | 2010-07-10T20:39:02Z | [
"python",
"linux",
"absolute-path",
"symlink"
] | when i give
ls -l /etc/fonts/conf.d/70-yes-bitmaps.conf
```
lrwxrwxrwx <snip> /etc/fonts/conf.d/70-yes-bitmaps.conf -> ../conf.avail/70-yes-bitmaps.conf
```
so for a symbolic link or soft link, how to find the target file's full(absolute path) in python,
If i use
`os.readlink('/etc/fonts/conf.d/70-yes-bitmaps.conf'... | <http://docs.python.org/library/os.path.html#os.path.abspath>
also joinpath and normpath, depending on whether you're in the current working directory, or you're working with things elsewhere. **normpath** might be more direct for you.
Update:
specifically:
```
os.path.normpath(
os.path.join(
os.path.dirnam... |
how to find the target file's full(absolute path) of the symbolic link or soft link in python | 3,220,755 | 28 | 2010-07-10T20:36:12Z | 3,220,786 | 49 | 2010-07-10T20:46:40Z | [
"python",
"linux",
"absolute-path",
"symlink"
] | when i give
ls -l /etc/fonts/conf.d/70-yes-bitmaps.conf
```
lrwxrwxrwx <snip> /etc/fonts/conf.d/70-yes-bitmaps.conf -> ../conf.avail/70-yes-bitmaps.conf
```
so for a symbolic link or soft link, how to find the target file's full(absolute path) in python,
If i use
`os.readlink('/etc/fonts/conf.d/70-yes-bitmaps.conf'... | ```
os.path.realpath(path)
```
[os.path.realpath](http://docs.python.org/library/os.path.html#os.path.realpath) returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path. |
how to find the target file's full(absolute path) of the symbolic link or soft link in python | 3,220,755 | 28 | 2010-07-10T20:36:12Z | 9,643,181 | 8 | 2012-03-10T01:38:34Z | [
"python",
"linux",
"absolute-path",
"symlink"
] | when i give
ls -l /etc/fonts/conf.d/70-yes-bitmaps.conf
```
lrwxrwxrwx <snip> /etc/fonts/conf.d/70-yes-bitmaps.conf -> ../conf.avail/70-yes-bitmaps.conf
```
so for a symbolic link or soft link, how to find the target file's full(absolute path) in python,
If i use
`os.readlink('/etc/fonts/conf.d/70-yes-bitmaps.conf'... | As unutbu says, os.path.realpath(path) should be the right answer, returning the canonical path of the specified filename, resolving any symbolic links to their targets. But it's broken under Windows.
I've created a patch for Python 3.2 to fix this bug, and uploaded it to:
<http://bugs.python.org/issue9949>
It fixes... |
asynchronous programming in python | 3,221,314 | 44 | 2010-07-11T00:03:35Z | 3,221,320 | 32 | 2010-07-11T00:05:42Z | [
"python",
"asynchronous"
] | Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take? | Take a look here:
[Asynchronous Programming in Python](http://xph.us/2009/12/10/asynchronous-programming-in-python.html)
[An Introduction to Asynchronous Programming and Twisted](http://krondo.com/blog/?p=1247)
Worth checking out:
[asyncio (previously Tulip) has been checked into the Python default branch](https://... |
asynchronous programming in python | 3,221,314 | 44 | 2010-07-11T00:03:35Z | 3,221,334 | 48 | 2010-07-11T00:10:17Z | [
"python",
"asynchronous"
] | Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take? | What you describe (the main program flow resuming immediately while another function executes) is not what's normally called "asynchronous" (AKA "event-driven") programming, but rather "multitasking" (AKA "multithreading" or "multiprocessing"). You can get what you described with the standard library modules `threading... |
asynchronous programming in python | 3,221,314 | 44 | 2010-07-11T00:03:35Z | 3,222,561 | 11 | 2010-07-11T09:37:17Z | [
"python",
"asynchronous"
] | Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take? | The other respondents are pointing you to Twisted, which is a great and very comprehensive framework but in my opinion it has a very un-pythonic design. Also, AFAICT, you have to use the Twisted main loop, which may be a problem for you if you're already using something else that provides its own loop.
Here is a contr... |
asynchronous programming in python | 3,221,314 | 44 | 2010-07-11T00:03:35Z | 18,099,524 | 17 | 2013-08-07T09:21:50Z | [
"python",
"asynchronous"
] | Is there a generic notion of asynchronous programming in python? Could I assign a callback to a function, execute it and return to the main program flow immediately, no matter how long the execution of that function would take? | Good news everyone!
**Python 3.4 would include brand new ambitious asynchronous programming [implementation](http://www.slideshare.net/megafeihong/tulip-24190096)!**
It is currently called [tulip](https://code.google.com/p/tulip/source/list) and already has an [active following](https://groups.google.com/forum/?fromg... |
How to copy last X bits? | 3,221,387 | 2 | 2010-07-11T00:33:49Z | 3,221,430 | 8 | 2010-07-11T00:53:35Z | [
"python",
"binary",
"bit-manipulation"
] | Let's say I have two integers with the following binary representations:
```
01101010
00110101
```
And now I want to copy the last 3 bits from the first integer over the second one so that it becomes
```
00110010
```
What's the easiest way to do that?
(Actually, my goal is to shift the all the X+1 bits to the righ... | Depending on your version of python, the way you express binary literals changes, see [this question for the details](http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python).
I'm using 2.5.2, so I used this:
```
>>> a = int('01101010', 2)
>>> b = int('00110101', 2)
>>> mask = 07 # Mask ... |
Specifying number of decimal places in Python | 3,221,654 | 6 | 2010-07-11T02:42:47Z | 3,221,672 | 17 | 2010-07-11T02:53:07Z | [
"python"
] | When accepting user input with a decimal in Python I'm using:
```
#will input meal subtotal
def input_meal():
mealPrice = input('Enter the meal subtotal: $')
mealPrice = float (mealPrice)
return mealPrice
```
which returns exactly what is entered - say $43.45
but when using that value to calcula... | There's a few ways to do this depending on how you want to hold the value.
You can use basic string formatting, e.g
```
'Your Meal Price is %.2f' % mealPrice
```
You can modify the `2` to whatever precision you need.
However, since you're dealing with money you should look into the [decimal](http://docs.python.org... |
Python Threading String Arguments | 3,221,655 | 46 | 2010-07-11T02:43:52Z | 3,221,675 | 90 | 2010-07-11T02:54:36Z | [
"python",
"multithreading"
] | I have a problem with Python threading and sending a string in the arguments.
```
def processLine(line) :
print "hello";
return;
```
.
```
dRecieved = connFile.readline();
processThread = threading.Thread(target=processLine, args=(dRecieved));
processThread.start();
```
Where dRecieved is the string of one ... | You're trying to create a tuple, but you're just parenthesizing a string :)
Add an extra ',':
```
dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,)) # <- note extra ','
processThread.start()
```
Or use brackets to make a list:
```
dRecieved = connFile.readline()... |
Why are session methods unbound in sqlalchemy using sqlite? | 3,221,814 | 7 | 2010-07-11T04:01:53Z | 3,221,875 | 12 | 2010-07-11T04:36:11Z | [
"python",
"sqlite",
"sqlalchemy"
] | Code replicating the error:
```
from sqlalchemy import create_engine, Table, Column, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Message(Base):
__tablename__ = 'messages'
id = Column(Integer, primary_key=True)
me... | The return value from `sessionmaker()` [is a class](http://docs.sqlalchemy.org/en/latest/orm/session.html#getting-a-session). You need to instantiate it before using methods on the instance. |
How can I find the first occurrence of a sub-string in a python string? | 3,221,891 | 39 | 2010-07-11T04:47:56Z | 3,221,900 | 69 | 2010-07-11T04:50:40Z | [
"python",
"string"
] | So if my string is "the dude is a cool dude".
I'd like to find the first index of 'dude':
```
mystring.findfirstindex('dude') # should return 4
```
What is the python command for this?
Thanks. | [`find()`](http://docs.python.org/library/stdtypes.html#str.find)
```
>>> s = "the dude is a cool dude"
>>> s.find('dude')
4
``` |
Is it possible to get widget settings in Tkinter? | 3,221,908 | 5 | 2010-07-11T04:55:00Z | 3,222,000 | 12 | 2010-07-11T05:40:42Z | [
"python",
"get",
"settings",
"widget",
"tkinter"
] | It'd be awesome if I could get something like the below.
Pseudo Code:
```
U = widget1.SettingsGet()
Print U
```
Upon printing U something like this would be returned:
```
widget1(background='green',foreground='grey',boarderwidth=10, relief='flat')
```
It would be really useful to be able to get a widgets settings.... | Why you need all the setting at once in a single dictionary, anyway you will have to access a specific setting from that settings dictionary, so instead just use `cget` method to get values e.g.
```
from Tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
print w.cget('text')
root.mainloop()
... |
What is the simplest way to make tooltips in Tkinter? | 3,221,956 | 16 | 2010-07-11T05:19:06Z | 3,222,120 | 10 | 2010-07-11T06:37:34Z | [
"python",
"tkinter",
"tooltip"
] | For those that don't know, tooltips are those little bits of text that popup when the mouse hovers over a widget for a certain durration of time. | The [Pmw.Balloon](http://pmw.sourceforge.net/doc/Balloon.html) class from the [Pmw toolkit](http://pmw.sourceforge.net/) for Tkinter will draw tool tips.
Also take a look at this [blog post](http://www.voidspace.org.uk/python/weblog/arch_d7_2006_07_01.shtml), which adapts some code from IDLE used for displaying tool t... |
What is the simplest way to make tooltips in Tkinter? | 3,221,956 | 16 | 2010-07-11T05:19:06Z | 3,222,302 | 9 | 2010-07-11T07:57:38Z | [
"python",
"tkinter",
"tooltip"
] | For those that don't know, tooltips are those little bits of text that popup when the mouse hovers over a widget for a certain durration of time. | Since you're using Windows 7, your Python installation most probably already includes [Tix](http://tix.sourceforge.net/dist/current/docs/html/TixUser/TixUser.html). Use the Tix.Balloon widget. [Sample code](http://svn.python.org/view/python/trunk/Demo/tix/samples/Balloon.py?revision=78779&view=markup) exists in the Pyt... |
Python 2.6: Class inside a Class? | 3,222,251 | 13 | 2010-07-11T07:34:24Z | 3,222,269 | 41 | 2010-07-11T07:43:26Z | [
"python",
"class"
] | Hey everyone, my problem is that im trying to figure out how to get a class INSIDE another class.
What I am doing is I have a class for an Airplane with all its statistics as to how fast it can fly, how far it can go, fuel consumption, and so on. Then I have a Flight Class which is all the details about the flight: Di... | I think you are confusing objects and classes. A class inside a class looks like this:
```
class Foo(object):
class Bar(object):
pass
>>> foo = Foo()
>>> bar = Foo.Bar()
```
But it doesn't look to me like that's what you want. Perhaps you are after a simple containment hierarchy:
```
class Player(object... |
Python 2.6: Class inside a Class? | 3,222,251 | 13 | 2010-07-11T07:34:24Z | 3,222,289 | 19 | 2010-07-11T07:53:00Z | [
"python",
"class"
] | Hey everyone, my problem is that im trying to figure out how to get a class INSIDE another class.
What I am doing is I have a class for an Airplane with all its statistics as to how fast it can fly, how far it can go, fuel consumption, and so on. Then I have a Flight Class which is all the details about the flight: Di... | It sounds like you are talking about *aggregation*. Each instance of your `player` class can contain zero or more instances of `Airplane`, which, in turn, can contain zero or more instances of `Flight`. You can implement this in Python using the built-in `list` type to save you naming variables with numbers.
```
class... |
How do I sum the columns in 2D list? | 3,223,043 | 20 | 2010-07-11T12:30:22Z | 3,223,052 | 25 | 2010-07-11T12:35:00Z | [
"python"
] | Say I've a Python 2D list as below:
```
my_list = [ [1,2,3,4],
[2,4,5,6] ]
```
I can get the row totals with a list comprehension:
```
row_totals = [ sum(x) for x in my_list ]
```
Can I get the column totals without a double `for` loop? Ie, to get this list:
```
[3,6,8,10]
``` | Use [zip](http://docs.python.org/library/functions.html#zip)
```
col_totals = [ sum(x) for x in zip(*my_list) ]
``` |
How do I sum the columns in 2D list? | 3,223,043 | 20 | 2010-07-11T12:30:22Z | 3,223,073 | 15 | 2010-07-11T12:44:41Z | [
"python"
] | Say I've a Python 2D list as below:
```
my_list = [ [1,2,3,4],
[2,4,5,6] ]
```
I can get the row totals with a list comprehension:
```
row_totals = [ sum(x) for x in my_list ]
```
Can I get the column totals without a double `for` loop? Ie, to get this list:
```
[3,6,8,10]
``` | ```
>>> map(sum,zip(*my_list))
[3, 6, 8, 10]
```
Or the itertools equivalent
```
>>> from itertools import imap, izip
>>> imap(sum,izip(*my_list))
<itertools.imap object at 0x00D20370>
>>> list(_)
[3, 6, 8, 10]
``` |
How do I sum the columns in 2D list? | 3,223,043 | 20 | 2010-07-11T12:30:22Z | 3,225,556 | 7 | 2010-07-12T02:43:34Z | [
"python"
] | Say I've a Python 2D list as below:
```
my_list = [ [1,2,3,4],
[2,4,5,6] ]
```
I can get the row totals with a list comprehension:
```
row_totals = [ sum(x) for x in my_list ]
```
Can I get the column totals without a double `for` loop? Ie, to get this list:
```
[3,6,8,10]
``` | Solution `map(sum,zip(*my_list))` is the fastest.
However, if you need to keep the list, `[x + y for x, y in zip(*my_list)]` is the fastest.
The test was conducted in Python 3.1.2 64 bit.
```
>>> import timeit
>>> my_list = [[1, 2, 3, 4], [2, 4, 5, 6]]
>>> t1 = lambda: [sum(x) for x in zip(*my_list)]
>>> timeit.timei... |
Creating a namedtuple with a custom hash function | 3,223,236 | 11 | 2010-07-11T13:37:05Z | 3,223,262 | 14 | 2010-07-11T13:45:04Z | [
"python",
"inheritance",
"override",
"tuples"
] | Say I have a `namedtuple` like this:
```
FooTuple = namedtuple("FooTuple", "item1, item2")
```
And I want the following function to be used for hashing:
```
foo_hash(self):
return hash(self.item1) * (self.item2)
```
I want this because I want the order of `item1` and `item2` to be irrelevant (I will do the same... | I think there is something wrong with your code (my guess is that you created an instance of the tuple with the same name, so `fooTuple` is now a tuple, not a tuple class), because subclassing the named tuple like that should work. Anyway, you don't need to redefine the constructor. You can just add the hash function:
... |
how to create a temporary directory and get the path / file name in python | 3,223,604 | 57 | 2010-07-11T15:41:21Z | 3,223,615 | 98 | 2010-07-11T15:45:45Z | [
"python",
"temporary-files",
"temporary-directory"
] | how to create a temporary directory and get the path / file name in python | Use the [`mkdtemp()`](http://docs.python.org/library/tempfile.html#tempfile.mkdtemp) function from the [`tempfile`](http://docs.python.org/library/tempfile.html) module:
```
import tempfile
import shutil
dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)
``` |
how to create a temporary directory and get the path / file name in python | 3,223,604 | 57 | 2010-07-11T15:41:21Z | 33,288,373 | 9 | 2015-10-22T18:41:47Z | [
"python",
"temporary-files",
"temporary-directory"
] | how to create a temporary directory and get the path / file name in python | To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:
```
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
... |
Get a subset of a generator | 3,223,780 | 18 | 2010-07-11T16:28:55Z | 3,223,789 | 22 | 2010-07-11T16:30:37Z | [
"python",
"generator"
] | I have a generator function and want to get the first ten items from it; my first attempt was:
```
my_generator()[:10]
```
This doesn't work because generators aren't subscriptable, as the error tells me. Right now I have worked around that with:
```
list(my_generator())[:10]
```
This works since it converts the ge... | ```
import itertools
itertools.islice(mygenerator(), 10)
```
`itertools` has a number of utilities for working with iterators. `islice` takes start, stop, and step arguments to slice an iterator just as you would slice a list. |
Python Unicode Encode Error | 3,224,268 | 69 | 2010-07-11T19:00:48Z | 3,224,300 | 132 | 2010-07-11T19:10:51Z | [
"python",
"unicode",
"ascii",
"encode"
] | I'm reading and parsing an Amazon XML file and while the XML file shows a ' , when I try to print it I get the following error:
```
'ascii' codec can't encode character u'\u2019' in position 16: ordinal not in range(128)
```
From what I've read online thus far, the error is coming from the fact that the XML file is i... | Likely, your problem is that you parsed it okay, and now you're trying to print the contents of the XML and you can't because theres some foreign Unicode characters. Try to encode your unicode string as ascii first:
```
unicodeData.encode('ascii', 'ignore')
```
the 'ignore' part will tell it to just skip those charac... |
Python Unicode Encode Error | 3,224,268 | 69 | 2010-07-11T19:00:48Z | 21,030,388 | 12 | 2014-01-09T20:24:54Z | [
"python",
"unicode",
"ascii",
"encode"
] | I'm reading and parsing an Amazon XML file and while the XML file shows a ' , when I try to print it I get the following error:
```
'ascii' codec can't encode character u'\u2019' in position 16: ordinal not in range(128)
```
From what I've read online thus far, the error is coming from the fact that the XML file is i... | A better solution:
```
if type(value) == str:
# Ignore errors even if the string is not proper UTF-8 or has
# broken marker bytes.
# Python built-in function unicode() can do this.
value = unicode(value, "utf-8", errors="ignore")
else:
# Assume the value object has proper __unicode__() method
v... |
Python: Indexing a list of lists | 3,224,295 | 2 | 2010-07-11T19:09:39Z | 3,224,330 | 8 | 2010-07-11T19:20:47Z | [
"python",
"list"
] | Simple question, i have a list if lists
```
x = [['1','2','3'],['4','5','6'],['7','8','9']]
```
whats the simpliest way of indexing through each list in a single for loop? For example
```
for i in x:
print 1st_list_in_list
print 2nd_list_in_list
print 3rd_list_in_list
```
---
EDIT
Let me elaborate fur... | Try this:
```
for l in x:
print ', '.join(map(str, l))
```
Output:
```
1, 2, 3
4, 5, 6
7, 8, 9
``` |
Learning Python, is there a better way to write this? | 3,224,412 | 4 | 2010-07-11T19:50:36Z | 3,224,480 | 11 | 2010-07-11T20:14:43Z | [
"python"
] | I am learning Python (2.7) and to test what I have learned so far I wrote a temperature converter that converts Celsius to Fahrenheit and I wanted to know if my code could be written better to be faster or something more Pythonic. And could someone tell me if there is an actual name for the `if __name__ == '__main__': ... | ```
import sys
def to_f(c): # Convert celsius to fahrenheit
return (c * 9/5) + 32
def to_c(f): # Convert fahrenheit to celsius
return (f - 32) * 5/9
def convert(args):
if len(args) < 2:
return 1 # If less than two arguments
t = args[1]
if args[0] == '-f': # If the first argument is -f
... |
Matplotlib: plot multiple graphs using same figure, without them overlapping | 3,225,138 | 3 | 2010-07-11T23:59:13Z | 3,225,161 | 9 | 2010-07-12T00:06:39Z | [
"python",
"matplotlib"
] | I have a class which I use to plot things then save them to a file. Here's a simplified version of it:
```
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Test():
def __init__(self, x, y, filename):
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, y,... | You could use the figure's [clf](http://matplotlib.sourceforge.net/api/figure_api.html?highlight=clf#matplotlib.figure.Figure.clf) method to clear the figure after you're done with one. Also, [pyplot.clf](http://matplotlib.sourceforge.net/api/pyplot_api.html?highlight=clf#matplotlib.pyplot.clf) will clear the current f... |
How to check if an element of a list is a number? | 3,225,305 | 2 | 2010-07-12T01:07:27Z | 3,225,310 | 11 | 2010-07-12T01:09:50Z | [
"python"
] | How can I check if the first element of the list (below) is a number (using some sort of regular expression) in python:
```
temp = ['1', 'abc', 'XYZ', 'test', '1']
```
Many thanks. | ```
try:
i = int(temp[0])
except ValueError:
print "not an integer\n"
try:
i = float(temp[0])
except ValueError:
print "not a number\n"
```
If it must be done with a regex:
```
import re
re.match( '^[-+]?(([0-9]+([.][0-9]*)?)|(([0-9]*[.])?[0-9]+))$', temp[0] )
``` |
Google App Engine: How to use the task queue for this processing? | 3,225,470 | 3 | 2010-07-12T02:10:05Z | 3,225,533 | 9 | 2010-07-12T02:36:45Z | [
"python",
"google-app-engine",
"task-queue"
] | I'm using the Python GAE SDK.
I have some processing that needs to be done on 6000+ instances of `MyKind`. It is too slow to be done in a single request, so I'm using the task queue. If I make a single task process only one entity, then it should take only a few seconds.
The [documentation](http://code.google.com/app... | When you run code like `taskqueue.add(url='/worker', params={'cursor': cursor})` you are enqueueing a task; scheduling a request to execute out of band using the parameters you provide. You can apparently schedule up to 100 of these in one operation.
I don't think you want to, though. Task chaining would make this a l... |
mod_python for python 2.7 | 3,225,498 | 5 | 2010-07-12T02:24:54Z | 3,225,499 | 12 | 2010-07-12T02:26:40Z | [
"python",
"python-2.7",
"mod-python"
] | I recently downloaded python 2.7 on my computer (x64) and I would like to install mod\_python for it (I have apache 2.2), however, I can't find a mod\_python release supporting python 2.7. Has development stopped? If so, what should I use instead? | Development on mod\_python has stopped and its use is no longer recommended. I suggest [mod\_wsgi](http://code.google.com/p/modwsgi/)
From the [mod\_python Django documentation](https://docs.djangoproject.com/en/1.4/howto/deployment/modpython/):
> Support for mod\_python has been deprecated, and will be removed in Dj... |
How do I get Python's Mechanize to POST an ajax request? | 3,225,569 | 6 | 2010-07-12T02:46:59Z | 3,305,745 | 8 | 2010-07-22T04:16:39Z | [
"python",
"mechanize"
] | The site I'm trying to spider is using the javascript:
```
request.open("POST", url, true);
```
To pull in extra information over ajax that I need to spider. I've tried various permutations of:
```
r = mechanize.urlopen("https://site.tld/dir/" + url, urllib.urlencode({'none' : 'none'}))
```
to get Mechanize to get ... | This was what I came up with:
```
req = mechanize.Request("https://www.site.com/path/" + url, " ")
req.add_header("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.7) Gecko/20100713 Firefox/3.6.7")
req.add_header("Referer", "https://www.site.com/path")
cj.add_cookie_header(req)
res = mechanize.ur... |
How do I concatenate strings from a dictionary by identifying the last item with Python? | 3,225,594 | 2 | 2010-07-12T02:55:33Z | 3,225,605 | 15 | 2010-07-12T02:59:29Z | [
"python",
"dictionary"
] | I need to concatenate string to an existing one as follows.
```
for k,v in r.iteritems():
tableGenString += "%s %s, " % (k, what_type(v))
```
The problem is that for the last item the comma(',') should not be added.
How can I check if k,v is the last item?
## Added
The example is a simplified version of the re... | Don't build large strings with concatenation like that. Do this instead:
```
tableGenString = ', '.join('%s %s' % (k, what_type(v)) for k, v in r.iteritems())
``` |
Full text search: Whoosh Vs SOLR | 3,226,596 | 22 | 2010-07-12T07:33:56Z | 3,226,651 | 11 | 2010-07-12T07:46:03Z | [
"python",
"django",
"solr"
] | I am working on a Django project, where I need to implement full text search. I have seen SOLR and found some good comments for the same. But as its implemented in Java and would need java enviroment to be installed on the system along with Python. Looking for the python equivalent for SOLR, I have seen Whoosh but I am... | Whoosh is actually very fast for a python-only implementation. That said, it's still at least an order of magnitude slower. Depending on the amount of data you need to index and search and the requirements on the maximum allowable latency and concurrent searches, it may not be an option.
SOLR is a bit of a complicated... |
Why is using thread locals in Django bad? | 3,227,180 | 35 | 2010-07-12T09:21:48Z | 3,227,315 | 9 | 2010-07-12T09:36:09Z | [
"python",
"django",
"thread-local"
] | I am using thread locals to store the current user and request objects. This way I can have easy access to the request from anywhere in the programme (e.g. dynamic forms) without having to pass them around.
To implement the thread locals storage in a middleware, I followed a tutorial on the Django site:
<http://code.d... | Despite the fact that you could mix up data from different users, thread locals should be avoided because they hide a dependency. If you pass arguments to a method you see and know what you're passing. But a thread local is something like a hidden channel in the background and you may wonder, that a method doesn't work... |
Why is using thread locals in Django bad? | 3,227,180 | 35 | 2010-07-12T09:21:48Z | 3,227,515 | 29 | 2010-07-12T10:06:27Z | [
"python",
"django",
"thread-local"
] | I am using thread locals to store the current user and request objects. This way I can have easy access to the request from anywhere in the programme (e.g. dynamic forms) without having to pass them around.
To implement the thread locals storage in a middleware, I followed a tutorial on the Django site:
<http://code.d... | I disagree entirely. TLS is extremely useful. It should be used with care, just as globals should be used with care; but saying it shouldn't be used at all is just as ridiculous as saying globals should never be used.
For example, I store the currently active request in TLS. This makes it accessible from my logging cl... |
What is the Pythonic Way of Differentiating Between a String and a List? | 3,227,552 | 23 | 2010-07-12T10:11:57Z | 3,227,612 | 23 | 2010-07-12T10:23:40Z | [
"python"
] | For my program I have a lot of places where an object can be either a string or a list containing strings and other similar lists. These are generally read from a JSON file. They both need to be treated differently. Right now, I am just using isinstance, but that does not feel like the most pythonic way of doing it, so... | No need to import modules, `isinstance()`, `str` and `unicode` (versions before 3 -- there's no `unicode` in 3!) will do the job for you.
## Python 2.x:
```
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more informa... |
What is the Pythonic Way of Differentiating Between a String and a List? | 3,227,552 | 23 | 2010-07-12T10:11:57Z | 3,227,663 | 9 | 2010-07-12T10:30:53Z | [
"python"
] | For my program I have a lot of places where an object can be either a string or a list containing strings and other similar lists. These are generally read from a JSON file. They both need to be treated differently. Right now, I am just using isinstance, but that does not feel like the most pythonic way of doing it, so... | Since Python3 no longer has `unicode` or `basestring`, in this case ( where you are expecting either a list or a string) it's better to test against `list`
```
if isinstance(thing, list):
# treat as list
else:
# treat as str/unicode
```
as that is compatible with both Python2 and Python3 |
What is the dominant reason for Python's popularity as a systems and application programming language? | 3,227,789 | 5 | 2010-07-12T10:49:57Z | 3,227,809 | 18 | 2010-07-12T10:52:57Z | [
"python",
"programming-languages",
"prototype"
] | Coming from an enterprise systems background (think Java and Windows) - I'm surprised at the popularity of python as a prototyping language and am trying to put my finger on the precise reason for this. Examples include being listed as one of the four languages Google uses. Possible reasons include:
* enables rapid sy... | 1. Highly expressive language. People often say, "Python works the way my brain does".
2. Dynamic typing means you spend zero time appeasing the compiler.
3. A large standard library means you often have the tools you need at your fingertips.
4. An even larger stable of third-party packages (PIL, Numpy, NLTK, Django) m... |
Determine height of Coffee in the pot using Python imaging | 3,227,843 | 24 | 2010-07-12T10:57:15Z | 3,229,887 | 11 | 2010-07-12T15:46:24Z | [
"python",
"image-processing"
] | This is a bit of a funny question but...
We have a web-cam in our office kitchenette focused at our coffee maker. The coffee pot is clearly visible. Both the location of the coffee pot and the camera are static. Is it possible to calculate the height of coffee in the pot using image recognition? I've seen image recogn... | Since the coffee pot position is stationary, get a sample frame and locate a *single* column of pixels where the minimum and maximum coffee quantities can easily be seen, in a spot where there are no reflections. Check the green vertical line segment in the following picture:
[
# Atte... | Without having tried it, scaling errors are common in converting colors:
RGB is bytes 0 .. 255, e.g. yellow [255,255,0],
whereas `rgb2xyz()` etc. work on triples of floats, yellow [1.,1.,0].
(`color.py` has no range checks: `lab2rgb( rgb2lab([255,255,0]) )` is junk.)
In IPython, `%run main.py`, then print corners ... |
Python: how does inspect.ismethod work? | 3,228,680 | 8 | 2010-07-12T12:54:54Z | 3,228,931 | 7 | 2010-07-12T13:23:34Z | [
"python",
"inspect"
] | I'm trying to get the name of all methods in my class.
When testing how the inspect module works, i extraced one of my methods by `obj = MyClass.__dict__['mymethodname']`.
But now `inspect.ismethod(obj)` returns `False` while `inspect.isfunction(obj)` returns `True`, and i don't understand why. Is there some strange w... | You are seeing some effects of the behind-the-scenes machinery of Python.
When you write `f = MyClass.__dict__['mymethodname']`, you get the raw implementation of "mymethodname", which is a plain function. To call it, you need to pass in an additional parameter, class instance.
When you write `f = MyClass.mymethodnam... |
Print elements of a list to a .csv file | 3,228,740 | 2 | 2010-07-12T13:01:35Z | 3,228,776 | 7 | 2010-07-12T13:04:53Z | [
"python",
"string",
"csv"
] | I am reading in a csv file and dealing with each line as a list. At the end, I'd like to reprint to a .csv file, but the lines aren't necessarily even. I obviously cannot just go `"print row"`, since this will print it as a list. How can I print it in .csv format? | Read manual, there's a CSV writer method (with example too). Don't print the data, store them and then write them into CSV file
<http://docs.python.org/library/csv.html#csv.writer> |
Python: How do I format a number with a variable number of digits? | 3,228,865 | 20 | 2010-07-12T13:16:06Z | 3,228,882 | 18 | 2010-07-12T13:17:55Z | [
"python",
"string",
"string-formatting",
"number-formatting"
] | Say I wanted to display the number 123 with a variable number of padded zeroes on the front.
For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:
`'00123'`.
If I wanted to display it in 6 digits I would have digits = 6 giving: `'000123'`.
How would I do this in Python? | There is a string method called zfill:
```
>>> '12344'.zfill(10)
0000012344
```
It will pad the left side of the string with zeros to make the string length N (10 in this case). |
Python: How do I format a number with a variable number of digits? | 3,228,865 | 20 | 2010-07-12T13:16:06Z | 3,228,897 | 14 | 2010-07-12T13:19:41Z | [
"python",
"string",
"string-formatting",
"number-formatting"
] | Say I wanted to display the number 123 with a variable number of padded zeroes on the front.
For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:
`'00123'`.
If I wanted to display it in 6 digits I would have digits = 6 giving: `'000123'`.
How would I do this in Python? | ```
'%0*d' % (5, 123)
``` |
Python: How do I format a number with a variable number of digits? | 3,228,865 | 20 | 2010-07-12T13:16:06Z | 3,228,928 | 80 | 2010-07-12T13:23:15Z | [
"python",
"string",
"string-formatting",
"number-formatting"
] | Say I wanted to display the number 123 with a variable number of padded zeroes on the front.
For example, if I wanted to display it in 5 digits I would have digits = 5 giving me:
`'00123'`.
If I wanted to display it in 6 digits I would have digits = 6 giving: `'000123'`.
How would I do this in Python? | If you are using it in a formatted string with the `format()` method which is preferred over the older style `''%` formatting
```
>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'
```
See
<http://docs.python.org/library/st... |
pretty printing nested dictionaries in Python? | 3,229,419 | 106 | 2010-07-12T14:32:46Z | 3,229,493 | 56 | 2010-07-12T14:49:25Z | [
"python",
"dictionary"
] | How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint but it did not work:
```
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
```
I simply want an identation ("\t") for each nesting, so that I get something like this:
```
key1
value1
value2
... | I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:
```
def pretty(d, indent=0):
for key, value in d.iteritems():
print '\t' * indent + str(key)
if isinstance(value, dict):
pretty(value, indent+1)
else:
print '\t' * (inden... |
pretty printing nested dictionaries in Python? | 3,229,419 | 106 | 2010-07-12T14:32:46Z | 3,314,411 | 228 | 2010-07-22T23:49:21Z | [
"python",
"dictionary"
] | How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint but it did not work:
```
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
```
I simply want an identation ("\t") for each nesting, so that I get something like this:
```
key1
value1
value2
... | My first thought was that the JSON serializer is probably pretty good at nested dictionaries, so I'd cheat and use that:
```
>>> import json
>>> print json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
... sort_keys=True, indent=4)
{
"a": 2,
"b": {
"x": 3,
"y": {
... |
pretty printing nested dictionaries in Python? | 3,229,419 | 106 | 2010-07-12T14:32:46Z | 14,892,136 | 14 | 2013-02-15T09:58:19Z | [
"python",
"dictionary"
] | How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint but it did not work:
```
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
```
I simply want an identation ("\t") for each nesting, so that I get something like this:
```
key1
value1
value2
... | You could try [YAML](http://yaml.org) via [PyYAML](https://bitbucket.org/xi/pyyaml). Its output can be fine-tuned. I'd suggest starting with the following:
`print yaml.dump(data, allow_unicode=True, default_flow_style=False)`
The result is *very* readable; it can be also parsed back to Python if needed.
**Edit:**
E... |
pretty printing nested dictionaries in Python? | 3,229,419 | 106 | 2010-07-12T14:32:46Z | 26,209,900 | 19 | 2014-10-06T04:09:27Z | [
"python",
"dictionary"
] | How can I pretty print a dictionary with depth of ~4 in Python? I tried pretty printing with pprint but it did not work:
```
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(mydict)
```
I simply want an identation ("\t") for each nesting, so that I get something like this:
```
key1
value1
value2
... | As of what have been done, I don't see any pretty printer that at least mimics the output of the python interpreter with very simple formatting so here's mine :
```
class Formatter(object):
def __init__(self):
self.types = {}
self.htchar = '\t'
self.lfchar = '\n'
self.indent = 0
... |
Is there a way to have parallel for-each loops? | 3,229,458 | 11 | 2010-07-12T14:44:12Z | 3,229,492 | 14 | 2010-07-12T14:49:12Z | [
"python",
"foreach",
"iteration",
"parallel-processing"
] | Let's say I have 2 lists in Python and I want to loop through each one in parallel - e.g. do something with element 1 for both lists, do something with element 2 for both lists... I know that I can do this by using an index:
```
for listIndex in range(len(list1)):
doSomething(list1[listIndex])
doSomething(list2[... | Something like this?
```
for (a,b) in zip(list1, list2):
doSomething(a)
doSomething(b)
```
Though if `doSomething()` isn't doing I/O or updating global state, and it just works on one of the elements at a time, the order doesn't matter so you could just use `chain()` (from itertools):
```
for x in chain(list1, l... |
Checking whether a link is dead or not using Python without downloading the webpage | 3,229,607 | 5 | 2010-07-12T15:13:36Z | 3,229,704 | 9 | 2010-07-12T15:23:14Z | [
"python",
"urllib2"
] | For those who know `wget`, it has a option `--spider`, which allows one to check whether a link is broke or not, without actually downloading the webpage. I would like to do the same thing in Python. My problem is that I have a list of 100'000 links I want to check, at most once a day, and at least once a week. In any ... | You should use the [HEAD Request](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) for this, it asks the webserver for the headers without the body. See <http://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python> |
Python - Finding index of first non-empty item in a list | 3,229,626 | 5 | 2010-07-12T15:15:51Z | 3,229,643 | 13 | 2010-07-12T15:17:34Z | [
"python",
"list"
] | What would be the most efficient\elegant way in Python to find the index of the first non-empty item in a list?
For example, with
```
list_ = [None,[],None,[1,2],'StackOverflow',[]]
```
the correct non-empty index should be:
```
3
``` | ```
>>> lst = [None,[],None,[1,2],'StackOverflow',[]]
>>> next(i for i, j in enumerate(lst) if j)
3
```
if you don't want to raise a `StopIteration` error, just provide default value to the `next` function:
```
>>> next((i for i, j in enumerate(lst) if j == 2), 42)
42
```
P.S. don't use `list` as a variable name, it... |
How to get item list from wxpython ListBox | 3,229,749 | 3 | 2010-07-12T15:28:11Z | 3,229,965 | 10 | 2010-07-12T15:56:01Z | [
"python",
"listbox",
"wxpython",
"listboxitems"
] | Is there a single method that returns the list of items contained in a wxPython listBox?
I cant seem to find anything anywhere in the documentation or anywhere for that matter. All that I can think to do is to set the selection to all of the items and then get the selected items, though seems like an ugly roundabout w... | `wx.ListBox` is derived from `wx.ControlWithitems`. I think [GetStrings()](http://docs.wxwidgets.org/stable/wx_wxcontrolwithitems.html#wxcontrolwithitemsgetstrings) is what you need. |
Numpy minimum in (row, column) format | 3,230,067 | 14 | 2010-07-12T16:06:40Z | 3,230,123 | 30 | 2010-07-12T16:13:13Z | [
"python",
"arrays",
"numpy",
"minimum"
] | How can I know the (row, column) index of the minimum of a numpy array/matrix?
For example, if `A = array([[1, 2], [3, 0]])`, I want to get `(1, 1)`
Thanks! | Use [`unravel_index`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.unravel_index.html):
```
numpy.unravel_index(A.argmin(), A.shape)
``` |
Python list comprehension for dictionaries in dictionaries? | 3,231,250 | 10 | 2010-07-12T18:45:59Z | 3,231,303 | 24 | 2010-07-12T18:52:36Z | [
"python",
"list",
"dictionary",
"list-comprehension"
] | I just learned about list comprehension, which is a great fast way to get data in a single line of code. But something's bugging me.
In my test I have this kind of dictionaries inside the list:
```
[{'y': 72, 'x': 94, 'fname': 'test1420'}, {'y': 72, 'x': 94, 'fname': 'test277'}]
```
The list comprehension `s = [ r f... | You can do this:
```
s = dict([ (k,r) for k,r in mydict.iteritems() if r['x'] > 92 and r['x'] < 95 and r['y'] > 70 and r['y'] < 75 ])
```
This takes a dict as you specified and returns a 'filtered' dict. |
Python httplib ResponseNotReady | 3,231,543 | 23 | 2010-07-12T19:24:53Z | 3,232,999 | 32 | 2010-07-12T23:13:32Z | [
"python",
"http",
"rest",
"httplib"
] | I'm writing a REST client for elgg using python, and even when the request succeeds, I get this in response:
```
Traceback (most recent call last):
File "testclient.py", line 94, in <module>
result = sendMessage(token, h1)
File "testclient.py", line 46, in sendMessage
res = h1.getresponse().read()
File "... | Make sure you don't reuse the same object from a previous connection. You will hit this once the server *keep-alive* ends and the socket closes. |
Python httplib ResponseNotReady | 3,231,543 | 23 | 2010-07-12T19:24:53Z | 10,876,180 | 34 | 2012-06-04T04:03:31Z | [
"python",
"http",
"rest",
"httplib"
] | I'm writing a REST client for elgg using python, and even when the request succeeds, I get this in response:
```
Traceback (most recent call last):
File "testclient.py", line 94, in <module>
result = sendMessage(token, h1)
File "testclient.py", line 46, in sendMessage
res = h1.getresponse().read()
File "... | Previous answers are correct, but there's another case where you could get that exception:
it is if you do multiple requests without reading the intermediate response completely.
For instance:
```
conn.request('PUT',...)
conn.request('GET',...)
# will not work: raises ResponseNotReady
conn.request('PUT,...)
r = conn... |
Weird Python behaviour - or am I missing something | 3,231,832 | 4 | 2010-07-12T20:05:42Z | 3,231,861 | 19 | 2010-07-12T20:09:15Z | [
"python",
"oop"
] | The following code:
```
class House:
links = []
class Link:
pass
class Villa(House):
pass
if __name__ == '__main__':
house = House()
villa = Villa()
link = Link()
house.links.append(link)
print house.links
print villa.links
```
results in this output:
```
[<__main__.Link insta... | It is another instance, but you have defined `links` as a class variable rather than an instance variable.
An instance variable would be defined as such:
```
class House(object): # Always use new-style classes except for backward compatibility
def __init__(self):
self.links = []
```
Note that in Python, unlik... |
a list > a list of lists | 3,231,894 | 6 | 2010-07-12T20:13:40Z | 3,231,976 | 17 | 2010-07-12T20:25:34Z | [
"python"
] | In python, how can I split a long list into a list of lists wherever I come across '-'. For example, how can I convert:
```
['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
```
to
```
[['1', 'a', 'b'],['2','c','d'],['3','123','e'],['4']]
```
Many thanks in advance. | ```
In [17]: import itertools
# putter around 22 times
In [39]: l=['1', 'a', 'b','---', '2','c','d','---','3','123','e','---','4']
In [40]: [list(g) for k,g in itertools.groupby(l,'---'.__ne__) if k]
Out[40]: [['1', 'a', 'b'], ['2', 'c', 'd'], ['3', '123', 'e'], ['4']]
``` |
Python ftplib can't get size of file before download? | 3,231,910 | 6 | 2010-07-12T20:17:17Z | 5,241,914 | 15 | 2011-03-09T05:51:55Z | [
"python",
"ftplib"
] | I'm using ftplib to transfer files. Everything is working great. Now I'm trying to get the size of the target file before downloading.
1. First, I tried just getting size with ftp.size(filename). Server complained that I can't do that in ascii mode.
2. Then I tried setting binary mode using ftp.sendcmd("binary") and f... | Very late reply, but here's the correct answer. This works with ProFTPD.
```
ftp.sendcmd("TYPE i") # Switch to Binary mode
ftp.size("/some/file") # Get size of file
``` |
Introspection to get decorator names on a method? | 3,232,024 | 20 | 2010-07-12T20:30:32Z | 3,232,189 | 17 | 2010-07-12T20:53:11Z | [
"python",
"decorator",
"introspection"
] | I am trying to figure out how to get the names of all decorators on a method. I can already get the method name and docstring, but cannot figure out how to get a list of decorators. | If you can change the way you call the decorators from
```
class Foo(object):
@many
@decorators
@here
def bar(self):
pass
```
to
```
class Foo(object):
@register(many,decos,here)
def bar(self):
pass
```
then you could register the decorators this way:
```
def register(*decor... |
How do I convert a padded string to an integer while preserving padding? | 3,232,256 | 3 | 2010-07-12T21:03:08Z | 3,232,264 | 9 | 2010-07-12T21:05:05Z | [
"python",
"string",
"padding",
"integer"
] | I followed the great example at [Python: Nicest way to pad zeroes to string (4)](http://stackoverflow.com/questions/339007/python-nicest-way-to-pad-zeroes-to-string)
but now I need to turn that padded string to a padded integer.
I tried:
```
list_padded=['0001101', '1100101', '0011011', '0011011', '1101111',
... | Applying idea of padding to integers is meaningless. If you want to print/represent them you need strings, integers just don't have padding. |
multiple instances of django on a single domain | 3,232,349 | 7 | 2010-07-12T21:17:07Z | 3,240,190 | 15 | 2010-07-13T18:23:59Z | [
"python",
"django",
"apache"
] | I'm looking for a good way to install multiple completely different Django projects on the same server using only a single domain name. The point is that I want to browse to something like:
<http://192.168.0.1/gallery/> # a Django photo gallery project
<http://192.168.0.1/blog/> # a blogging project
This way, I can... | I've been in situations where I couldn't use subdomains, and the way to handle this with Django is pretty simple actually.
Pretty much everything in your settings file will be just like a regular Django app, with the exception of making sure these settings include your project path:
```
MEDIA_URL = 'http://192.168.0.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.