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 |
|---|---|---|---|---|---|---|---|---|---|
How to re import an updated package while in Python Interpreter? | 684,171 | 252 | 2009-03-26T01:19:41Z | 684,186 | 206 | 2009-03-26T01:25:34Z | [
"python"
] | I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. | "Reload is no longer a function in Python 3. Use imp.reload() instead" copied from comments
Use the `reload` builtin function:
<https://docs.python.org/2/library/functions.html#reload>
> When `reload(module)` is executed:
>
> * Python modulesâ code is recompiled and the module-level code reexecuted, defining a new... |
How to re import an updated package while in Python Interpreter? | 684,171 | 252 | 2009-03-26T01:19:41Z | 684,229 | 29 | 2009-03-26T01:46:28Z | [
"python"
] | I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. | > So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me.
Yes, just saying `import` again gives you the existing copy of the module from `sys.modules`.
You can say `reload(module)` to update `sys.modules` and get a new copy of that single module, but if an... |
How to re import an updated package while in Python Interpreter? | 684,171 | 252 | 2009-03-26T01:19:41Z | 685,004 | 9 | 2009-03-26T09:04:43Z | [
"python"
] | I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. | Basically [reload](http://docs.python.org/library/functions.html#reload) as in allyourcode's asnwer. But it won't change underlying the code of already instantiated object or referenced functions. Extending from his answer:
```
#Make a simple function that prints "version 1"
shell1$ echo 'def x(): print "version 1"' >... |
How to re import an updated package while in Python Interpreter? | 684,171 | 252 | 2009-03-26T01:19:41Z | 8,637,233 | 10 | 2011-12-26T15:58:19Z | [
"python"
] | I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. | Short answer:
try using [reimport: a full featured reload for Python](https://bitbucket.org/petershinners/reimport).
Longer answer:
It looks like this question was asked/answered prior to the release of [reimport](https://bitbucket.org/petershinners/reimport), which bills itself as a "full featured reload for Python... |
How to re import an updated package while in Python Interpreter? | 684,171 | 252 | 2009-03-26T01:19:41Z | 13,121,908 | 20 | 2012-10-29T12:45:24Z | [
"python"
] | I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. | In Python 3, the behaviour changes.
```
>>> import my_stuff
```
... do something with my\_stuff, then later:
```
>>>> import imp
>>>> imp.reload(my_stuff)
```
and you get a brand new, reloaded my\_stuff. |
How to re import an updated package while in Python Interpreter? | 684,171 | 252 | 2009-03-26T01:19:41Z | 22,894,171 | 102 | 2014-04-06T12:41:19Z | [
"python"
] | I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. | All the answers above about reload() or imp.reload() are deprecated.
reload() is no longer a builtin function in python 3 and imp.reload() is marked deprecated (see help(imp)).
It's better to use [`importlib.reload()`](https://docs.python.org/3.4/library/importlib.html#importlib.reload) instead. |
How to re import an updated package while in Python Interpreter? | 684,171 | 252 | 2009-03-26T01:19:41Z | 36,375,742 | 7 | 2016-04-02T16:22:16Z | [
"python"
] | I often test my module in the Python Interpreter, and when I see an error, I quickly update the .py file. But how do I make it reflect on the Interpreter ? So, far I have been exiting and reentering the Interpreter because re importing the file again is not working for me. | No matter how many times you import a module, you'll get the same copy of the module from `sys.modules` - which was loaded at first `import mymodule`
I am answering this late, as each of the above/previous answer has a bit of the answer, so I am attempting to sum it all up in a single answer.
**Using built-in functio... |
Is it safe to yield from within a "with" block in Python (and why)? | 685,046 | 33 | 2009-03-26T09:24:56Z | 685,157 | 17 | 2009-03-26T10:12:08Z | [
"python",
"resources",
"coroutine"
] | The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.
The basic question is whether or not something like this works:
```
def coroutine():
with open(path, 'r') as fh:
for line in fh:
yield line
```
Which it does. (You ca... | I don't really understand what conflict you're asking about, nor the problem with the example: it's fine to have two coexisting, independent handles to the same file.
One thing I didn't know that I learned in response to your question it that there is a new close() method on generators:
> `close()` raises a new `Gene... |
Is it safe to yield from within a "with" block in Python (and why)? | 685,046 | 33 | 2009-03-26T09:24:56Z | 685,248 | 8 | 2009-03-26T10:44:15Z | [
"python",
"resources",
"coroutine"
] | The combination of coroutines and resource acquisition seems like it could have some unintended (or unintuitive) consequences.
The basic question is whether or not something like this works:
```
def coroutine():
with open(path, 'r') as fh:
for line in fh:
yield line
```
Which it does. (You ca... | I don't think there is a real conflict. You just have to be aware that the generator is just like any other object that holds resources, so it is the creator's responsibility to make sure it is properly finalized (and to avoid conflicts/deadlock with the resources held by the object). The only (minor) problem I see her... |
separate threads in pygtk application | 685,224 | 4 | 2009-03-26T10:36:01Z | 686,045 | 8 | 2009-03-26T14:31:59Z | [
"python",
"multithreading",
"pygtk"
] | I'm having some problems threading my pyGTK application. I give the thread some time to complete its task, if there is a problem I just continue anyway but warn the user. However once I continue, this thread stops until gtk.main\_quit is called. This is confusing me.
The relevant code:
```
class MTP_Connection(thread... | Firstly, don't subclass `threading.Thread`, use `Thread(target=callable).start()`.
Secondly, and probably the cause of your apparent block is that `gtk.main_iteration` takes a parameter `block`, which defaults to `True`, so your call to `gtk.main_iteration` will actually block when there are no events to iterate on. W... |
python convert microsoft office docs to plain text on linux | 685,533 | 11 | 2009-03-26T12:24:44Z | 685,562 | 9 | 2009-03-26T12:32:11Z | [
"python",
"linux",
"ms-office"
] | Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office. | You can access [OpenOffice via Python API](http://wiki.services.openoffice.org/wiki/Python).
Try using this as a base: <http://wiki.services.openoffice.org/wiki/Odt2txt.py> |
python convert microsoft office docs to plain text on linux | 685,533 | 11 | 2009-03-26T12:24:44Z | 687,876 | 8 | 2009-03-26T22:57:39Z | [
"python",
"linux",
"ms-office"
] | Any recomendations on a method to convert .doc, .ppt, and .xls to plain text on linux using python? Really any method of conversion would be useful. I have already looked at using Open Office but, I would like a solution that does not require having to install Open Office. | I'd go for the command line-solution (and then use the [Python subprocess module](http://docs.python.org/library/subprocess.html) to run the tools from Python).
Convertors for msword (**catdoc**), excel (**xls2csv**) and ppt (**catppt**) can be found (in source form) here: <http://vitus.wagner.pp.ru/software/catdoc/>.... |
Pythonic ways to use 'else' in a for loop | 685,758 | 13 | 2009-03-26T13:22:32Z | 686,145 | 15 | 2009-03-26T14:56:44Z | [
"for-loop",
"python"
] | I have hardly ever noticed a python program that uses else in a for loop.
I recently used it to perform an action based on the loop variable condition while exiting; as it is in the scope.
What is the pythonic way to use an else in a for loop? Are there any notable use cases?
And, yea. I dislike using break statemen... | What could be more pythonic than PyPy?
Look at what I discovered starting at line 284 in ctypes\_configure/configure.py:
```
for i in range(0, info['size'] - csize + 1, info['align']):
if layout[i:i+csize] == [None] * csize:
layout_addfield(layout, i, ctype, '_alignment')
break
... |
mysqldb on python 2.6+ (win32) | 685,869 | 10 | 2009-03-26T13:45:56Z | 686,631 | 11 | 2009-03-26T16:50:17Z | [
"python",
"mysql"
] | I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6? | There are versions of mysqldb for python 2.6, they're just not available on the official site. It took me a while (and unfortunately I lost the link) but you can search google and find people who have compiled and released 2.6 versions of mysqldb for windows x64 and x32.
EDIT:
<http://sourceforge.net/forum/forum.php?... |
mysqldb on python 2.6+ (win32) | 685,869 | 10 | 2009-03-26T13:45:56Z | 1,603,137 | 7 | 2009-10-21T19:42:56Z | [
"python",
"mysql"
] | I am currently using python 2.6 and I would like to use the win32 mysqldb module. Unfortunately it seems it needs the 2.5 version of Python. Is there any way to get rid of this mismatch in the version numbers and install mysqldb with python 2.6? | This one has both 32 and 64 versions for 2.6:
<http://www.codegood.com/archives/4> |
Writing binary data to a socket (or file) with Python | 686,296 | 9 | 2009-03-26T15:33:57Z | 686,314 | 11 | 2009-03-26T15:38:37Z | [
"python"
] | Let's say I have a socket connection, and the 3rd party listener on the other side expects to see data flowing in a very structured manner. For example, it looks for an unsigned byte that denotes a type of message being sent, followed by an unsigned integer that denotes the length of message, then another unsigned byte... | Use the [struct](http://docs.python.org/library/struct.html) module to build a buffer and write that. |
Python: Why can't I modify the current scope within a function using locals()? | 686,715 | 2 | 2009-03-26T17:10:21Z | 686,730 | 7 | 2009-03-26T17:15:32Z | [
"python",
"scope",
"introspection"
] | Why does creating/modifying a member of locals() not work within a function?
```
Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # Here's an example of what I expect to be possi... | Why would it? It's designed to return a representation, and was never intended for editing the locals. It's not ever guaranteed to work as a tool for such, as the [documentation](http://docs.python.org/library/functions.html#locals) warns. |
Python, Convert 9 tuple UTC date to MySQL datetime format | 686,717 | 10 | 2009-03-26T17:10:34Z | 686,728 | 20 | 2009-03-26T17:14:59Z | [
"python",
"sql",
"mysql",
"datetime",
"tuples"
] | I am parsing RSS feeds with the format as specified here: <http://www.feedparser.org/docs/date-parsing.html>
date tuple (2009, 3, 23, 13, 6, 34, 0, 82, 0)
I am a bit stumped at how to get this into the MySQL datetime format (Y-m-d H:M:S)? | ```
tup = (2009, 3, 23, 13, 6, 34, 0, 82, 0)
import datetime
d = datetime.datetime(*(tup[0:6]))
#two equivalent ways to format it:
dStr = d.isoformat(' ')
#or
dStr = d.strftime('%Y-%m-%d %H:%M:%S')
``` |
How to get the root node of an xml file in Python? | 687,177 | 3 | 2009-03-26T19:19:53Z | 687,184 | 10 | 2009-03-26T19:23:18Z | [
"python",
"xml"
] | Basically I am using:
from xml.etree import ElementTree as ET
```
path = 'C:\cool.xml'
et = ET.parse ( path )
```
But I am not sure how to get the root from et? | You probably want:
```
et.getroot()
```
Have a look at the official docs for ElementTree from the [effbot site](http://effbot.org/zone/element-index.htm). Note that Python 2.5 (the first version of Python to include ElementTree out of the box) uses ElementTree 1.2, not the more recent 1.3. There aren't many differenc... |
Is there a function in Python to list the attributes and methods of a particular object? | 687,239 | 15 | 2009-03-26T19:34:05Z | 687,251 | 9 | 2009-03-26T19:35:53Z | [
"python"
] | Is there a function in Python to list the attributes and methods of a particular object?
Something like:
```
ShowAttributes ( myObject )
-> .count
-> .size
ShowMethods ( myObject )
-> len
-> parse
``` | Don't dir() and vars() suit you? |
Is there a function in Python to list the attributes and methods of a particular object? | 687,239 | 15 | 2009-03-26T19:34:05Z | 687,252 | 33 | 2009-03-26T19:36:33Z | [
"python"
] | Is there a function in Python to list the attributes and methods of a particular object?
Something like:
```
ShowAttributes ( myObject )
-> .count
-> .size
ShowMethods ( myObject )
-> len
-> parse
``` | You want to look at the [`dir()`](http://diveintopython.net/power_of_introspection/built_in_functions.html) function:
```
>>> li = []
>>> dir(li)
['append', 'count', 'extend', 'index', 'insert',
'pop', 'remove', 'reverse', 'sort']
```
> `li` is a list, so `dir(li)` returns a list of all the methods of a list. N... |
Is there a function in Python to list the attributes and methods of a particular object? | 687,239 | 15 | 2009-03-26T19:34:05Z | 687,442 | 7 | 2009-03-26T20:25:25Z | [
"python"
] | Is there a function in Python to list the attributes and methods of a particular object?
Something like:
```
ShowAttributes ( myObject )
-> .count
-> .size
ShowMethods ( myObject )
-> len
-> parse
``` | and for a more human-readable way, you can use [see](http://github.com/inky/see/tree/master):
```
In [1]: from see import see
In [2]: x = "hello world!"
In [3]: see(x)
Out[3]:
[] in + * % < <= == != > >= hash() help() len()
repr() str() .capitalize() .center() .count() .decode(... |
How do I do a not equal in Django queryset filtering? | 687,295 | 348 | 2009-03-26T19:47:45Z | 1,154,977 | 372 | 2009-07-20T17:58:38Z | [
"python",
"django",
"django-models",
"django-queryset"
] | In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparitive values, but is there a `__ne`/`!=`/`<>` (**not equals**?)
I want to filter out using a not equals:
Example:
```
Model:
bool a;
int x;
```
I want
```
results = Model.objects.exclude(a=true, x!=5)
```
The `!=` is not correct ... | Maybe [Q objects](http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) could be of help for this problem. I've never used them but it seems they can be negated and combined much like normal python expressions.
Update: I Just tried it out, it seems to work pretty well:
```
>>> from m... |
How do I do a not equal in Django queryset filtering? | 687,295 | 348 | 2009-03-26T19:47:45Z | 1,155,013 | 77 | 2009-07-20T18:07:02Z | [
"python",
"django",
"django-models",
"django-queryset"
] | In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparitive values, but is there a `__ne`/`!=`/`<>` (**not equals**?)
I want to filter out using a not equals:
Example:
```
Model:
bool a;
int x;
```
I want
```
results = Model.objects.exclude(a=true, x!=5)
```
The `!=` is not correct ... | the `field=value` syntax in queries is a shorthand for `field__exact=value`. That is to say that [Django puts query operators on query fields in the identifiers](http://docs.djangoproject.com/en/dev/ref/models/querysets/#id7). Django supports the following operators:
```
exact
iexact
contains
icontains
in
gt
gte
lt
lt... |
How do I do a not equal in Django queryset filtering? | 687,295 | 348 | 2009-03-26T19:47:45Z | 4,139,956 | 342 | 2010-11-09T23:56:13Z | [
"python",
"django",
"django-models",
"django-queryset"
] | In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparitive values, but is there a `__ne`/`!=`/`<>` (**not equals**?)
I want to filter out using a not equals:
Example:
```
Model:
bool a;
int x;
```
I want
```
results = Model.objects.exclude(a=true, x!=5)
```
The `!=` is not correct ... | Your query appears to have a double negative, you want to exclude all rows where x is not 5, so in other words you want to include all rows where x IS 5. I believe this will do the trick.
```
results = Model.objects.filter(x=5).exclude(a=true)
```
To answer your specific question, there is no "not equal to" but that'... |
How do I do a not equal in Django queryset filtering? | 687,295 | 348 | 2009-03-26T19:47:45Z | 4,725,256 | 33 | 2011-01-18T14:34:16Z | [
"python",
"django",
"django-models",
"django-queryset"
] | In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparitive values, but is there a `__ne`/`!=`/`<>` (**not equals**?)
I want to filter out using a not equals:
Example:
```
Model:
bool a;
int x;
```
I want
```
results = Model.objects.exclude(a=true, x!=5)
```
The `!=` is not correct ... | While with the Models, you can filter with `=`, `__gt`, `__gte`, `__lt`, `__lte`, you cannot use `ne`, `!=` or `<>`. However, you can achieve better filtering on using the Q object.
You can avoid chaining `QuerySet.filter()` and `QuerySet.exlude()`, and use this:
```
from django.db.models import Q
object_list = Query... |
How do I do a not equal in Django queryset filtering? | 687,295 | 348 | 2009-03-26T19:47:45Z | 29,227,603 | 27 | 2015-03-24T08:07:27Z | [
"python",
"django",
"django-models",
"django-queryset"
] | In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparitive values, but is there a `__ne`/`!=`/`<>` (**not equals**?)
I want to filter out using a not equals:
Example:
```
Model:
bool a;
int x;
```
I want
```
results = Model.objects.exclude(a=true, x!=5)
```
The `!=` is not correct ... | It's easy to create a custom lookup with Django 1.7. There's an `__ne` lookup example in [Django official documentation](https://docs.djangoproject.com/en/1.7/howto/custom-lookups/#a-simple-lookup-example).
You need to create the lookup itself first:
```
from django.db.models import Lookup
class NotEqual(Lookup):
... |
How do I do a not equal in Django queryset filtering? | 687,295 | 348 | 2009-03-26T19:47:45Z | 32,778,343 | 9 | 2015-09-25T08:52:02Z | [
"python",
"django",
"django-models",
"django-queryset"
] | In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparitive values, but is there a `__ne`/`!=`/`<>` (**not equals**?)
I want to filter out using a not equals:
Example:
```
Model:
bool a;
int x;
```
I want
```
results = Model.objects.exclude(a=true, x!=5)
```
The `!=` is not correct ... | You should use `filter` and `exclude` like this
```
results = Model.objects.exclude(a=true).filter(x=5)
``` |
How do I do a not equal in Django queryset filtering? | 687,295 | 348 | 2009-03-26T19:47:45Z | 35,603,223 | 8 | 2016-02-24T13:12:47Z | [
"python",
"django",
"django-models",
"django-queryset"
] | In Django model QuerySets, I see that there is a `__gt` and `__lt` for comparitive values, but is there a `__ne`/`!=`/`<>` (**not equals**?)
I want to filter out using a not equals:
Example:
```
Model:
bool a;
int x;
```
I want
```
results = Model.objects.exclude(a=true, x!=5)
```
The `!=` is not correct ... | In **django1.9** you basically have three options.
1. Chain `exclude` and `filter` ([exclude docs](https://docs.djangoproject.com/es/1.9/topics/db/queries/#retrieving-specific-objects-with-filters)
```
results = Model.objects.exclude(a=true).filter(x=5)
```
2. Use [`Q() objects`](https://docs.djangoproject.c... |
Python game programming: is my IO object a legitimate candidate for being a global variable? | 687,703 | 5 | 2009-03-26T21:52:07Z | 687,777 | 9 | 2009-03-26T22:20:35Z | [
"python",
"io",
"global-variables"
] | I'm programming a game in Python, where all IO activities are done by an IO object (in the hope that it will be easy to swap that object out for another which implements a different user interface). Nearly all the other objects in the game need to access the IO system at some point (e.g. printing a message, updating th... | Yes, this is a legitimate use of a global variable. If you'd rather not, passing around a context object that is equivalent to this global is another option, as you mentioned.
Since I assume you're using multiple files (modules), why not do something like:
```
import io
io.print('hello, world')
io.clear()
```
This i... |
Is there a better Python bundle for textmate than the one in the bundle repository? | 688,245 | 17 | 2009-03-27T01:57:33Z | 2,353,554 | 8 | 2010-03-01T02:20:14Z | [
"python",
"textmate",
"textmatebundles"
] | At this time Textmate's official Python bundle is really bare bones, especially in comparison to the Ruby bundle. Does anyone know of a Python bundle that is more complete?
EDIT:
I am fully aware that there are editors and environments that are better suited to Python development, but I am really just interested to s... | I took a look and noticed that there has been a lot of work on Python-related bundles recently. Also, it seems I missed the memo on the best [new way](http://al3x.net/2008/12/03/how-i-use-textmate.html) to get bundles:
[Install GetBundles](http://solutions.treypiepmeier.com/2009/02/25/installing-getbundles-on-a-fresh-... |
How do I make a command line text editor? | 688,302 | 15 | 2009-03-27T02:19:14Z | 688,311 | 18 | 2009-03-27T02:28:44Z | [
"python",
"text-editor",
"tui"
] | I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries... | try python [curses](http://docs.python.org/howto/curses.html) module , it is a command-line graphic operation library. |
How do I make a command line text editor? | 688,302 | 15 | 2009-03-27T02:19:14Z | 688,312 | 9 | 2009-03-27T02:29:02Z | [
"python",
"text-editor",
"tui"
] | I have gotten to know my way around a few programming languages, and I'd like to try my hand at making a command-line text editor -- something that runs in the terminal, like vim/emacs/nano, but is pure text (no guis, please). Preferably, I'd like to do this in python. Where do I start? Are there any (python) libraries... | Take a look at [Curses Programming in Python](http://docs.python.org/howto/curses.html) and [this](http://docs.python.org/library/curses.html) as well. |
How to Make sure the code is still working after refactoring ( Dynamic language) | 688,740 | 7 | 2009-03-27T06:36:30Z | 688,756 | 17 | 2009-03-27T06:46:53Z | [
"php",
"python",
"dynamic-languages"
] | How to make sure that code is still working after refactoring ( i.e, after variable name change)?
In static language, if a class is renamed but other referring class is not, then I will get a compilation error.
But in dynamic language there is no such safety net, and your code can break during refactoring **if you ar... | Before you start refactoring you should create tests that will be able to test what you're going to change - if you say unit tests will not be enought, or they will be hard to create, then by all means create higher level tests possibly even excersising the whole of your product.
If you have code coverage tools for yo... |
How to Make sure the code is still working after refactoring ( Dynamic language) | 688,740 | 7 | 2009-03-27T06:36:30Z | 688,771 | 10 | 2009-03-27T06:55:07Z | [
"php",
"python",
"dynamic-languages"
] | How to make sure that code is still working after refactoring ( i.e, after variable name change)?
In static language, if a class is renamed but other referring class is not, then I will get a compilation error.
But in dynamic language there is no such safety net, and your code can break during refactoring **if you ar... | I've been teaching a class on unit tests, refactoring and so forth, and this is probably the thing that most people get wrong. Refactoring is *not* just changing the code. It is changing the code without changing the external functional behavior. That is a very important point.
In other words, you need to have some wa... |
How to prevent every malicious file upload on my server? (check file type)? | 690,108 | 5 | 2009-03-27T14:58:35Z | 690,122 | 7 | 2009-03-27T15:03:00Z | [
"php",
"python",
"security",
"file",
"types"
] | my proble is to avoid that users upload some malicious file on my web-server.
Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
```
function checkFile($nomeFile, $myExt = false){
if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_... | Users shouldn't be able to execute the files they upload. Remove their permission to execute. |
How to prevent every malicious file upload on my server? (check file type)? | 690,108 | 5 | 2009-03-27T14:58:35Z | 690,128 | 7 | 2009-03-27T15:04:10Z | [
"php",
"python",
"security",
"file",
"types"
] | my proble is to avoid that users upload some malicious file on my web-server.
Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
```
function checkFile($nomeFile, $myExt = false){
if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_... | You're going to need to validate that the uploaded file is actually the type that the extension indicates it is. You can do that through various methods, probably the easiest is via the `file` command. I don't know if it has an API. You can try it out yourself in the shell. For your example of file.exe that was renamed... |
How to prevent every malicious file upload on my server? (check file type)? | 690,108 | 5 | 2009-03-27T14:58:35Z | 850,857 | 7 | 2009-05-12T02:13:40Z | [
"php",
"python",
"security",
"file",
"types"
] | my proble is to avoid that users upload some malicious file on my web-server.
Im working on linux environment (debian).
Actually the uploads are handled via php by this code:
```
function checkFile($nomeFile, $myExt = false){
if($myExt != false){ $goodExt = "_$myExt"."_"; }else{ $goodExt = "_.jpg_.bmp_.zip_.pdf_.gif_... | I'm afraid to say that the answer you selected as correct is not correct. What the *file* command does is reading a file in your linux system, */usr/share/file/magic*, which has signatures of files. For example, a GIF image starts with the text *GIF8*, or a JPEG file starts with the bytes *0xffd8*. You just need to hav... |
Why isn't keyword DateField.input_formats recognized in django 1.0.2 and Python 2.5? | 690,171 | 3 | 2009-03-27T15:17:13Z | 701,155 | 12 | 2009-03-31T14:11:30Z | [
"python",
"django"
] | With django 1.0.2 and Python 2.5, when I use the keyword `DateField.input_formats`, I get the error that `__init__()` got an unexpected keyword argument `'input_formats'`. When I look in the `__init__` file, I don't see `input_formats` as one of the acceptable keyword arguments.
I thought that `input_formats` had been... | Having looked at the docs, like you suspected, [models.DateField](http://docs.djangoproject.com/en/dev/ref/models/fields/#datefield) doesn't have an input\_formats, but [forms.DateField](http://docs.djangoproject.com/en/dev/ref/forms/fields/#datefield) does (as does forms.DateTimeField) |
Is it ever polite to put code in a python configuration file? | 690,221 | 9 | 2009-03-27T15:26:56Z | 690,253 | 11 | 2009-03-27T15:36:19Z | [
"python",
"django"
] | One of my favorite features about python is that you can write configuration files in python that are very simple to read and understand. If you put a few boundaries on yourself, you can be pretty confident that non-pythonistas will know exactly what you mean and will be perfectly capable of reconfiguring your program.... | There is a Django wiki page, which addresses exactly the thing you're asking.
<http://code.djangoproject.com/wiki/SplitSettings>
Do not reinvent the wheel. Use [configparser](http://docs.python.org/library/configparser.html) and INI files. Python files are to easy to break by someone, who doesn't know Python. |
What's a standard way to do a no-op in python? | 690,622 | 70 | 2009-03-27T17:04:19Z | 690,625 | 150 | 2009-03-27T17:05:17Z | [
"python"
] | I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the c... | Use [pass](http://docs.python.org/reference/simple%5Fstmts.html#the-pass-statement) for no-op:
```
if x == 0:
pass
else:
print "x not equal 0"
```
And here's another example:
```
def f():
pass
```
Or:
```
class c:
pass
``` |
What's a standard way to do a no-op in python? | 690,622 | 70 | 2009-03-27T17:04:19Z | 690,627 | 20 | 2009-03-27T17:05:35Z | [
"python"
] | I often find myself writing if / elif / else constructs in python, and I want to include options which can occur, but for which the corresponding action is to do nothing. I realise I could just exclude those if statements, but for readability I find it helps to include them all, so that if you are looking through the c... | How about `pass`? |
Log all errors to console or file on Django site | 690,723 | 13 | 2009-03-27T17:30:45Z | 691,252 | 13 | 2009-03-27T19:51:37Z | [
"python",
"django",
"facebook"
] | How can I get Django 1.0 to write **all** errors to the console or a log file when running runserver in debug mode?
I've tried using a middleware class with process\_exception function as described in the accepted answer to this question:
<http://stackoverflow.com/questions/238081/how-do-you-log-server-errors-on-djan... | It's a bit extreme, but for debugging purposes, you can turn on the [`DEBUG_PROPAGATE_EXCEPTIONS`](http://docs.djangoproject.com/en/dev/ref/settings/#debug-propagate-exceptions) setting. This will allow you to set up your own error handling. The easiest way to set up said error handling would be to override [sys.except... |
How do you determine if an IP address is private, in Python? | 691,045 | 16 | 2009-03-27T18:51:53Z | 691,057 | 27 | 2009-03-27T18:55:23Z | [
"python",
"network-programming",
"ip-address"
] | In Python, what is the best way to determine if an IP address (e.g., `'127.0.0.1'` or `'10.98.76.6'`) is on a [private network](http://en.wikipedia.org/wiki/Private%5Fnetwork)? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to conside... | Check out the [IPy](http://pypi.python.org/pypi/IPy/) module. If has a function `iptype()` that seems to do what you want:
```
>>> from IPy import IP
>>> ip = IP('127.0.0.0/30')
>>> ip.iptype()
'PRIVATE'
``` |
How do you determine if an IP address is private, in Python? | 691,045 | 16 | 2009-03-27T18:51:53Z | 8,339,939 | 18 | 2011-12-01T10:36:41Z | [
"python",
"network-programming",
"ip-address"
] | In Python, what is the best way to determine if an IP address (e.g., `'127.0.0.1'` or `'10.98.76.6'`) is on a [private network](http://en.wikipedia.org/wiki/Private%5Fnetwork)? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to conside... | You can check that yourself using
<http://tools.ietf.org/html/rfc1918> and <http://tools.ietf.org/html/rfc3330>. If you have 127.0.0.1 you just need to `&` it with the mask (lets say `255.0.0.0`) and see if the value matches any of the private network's [network address](http://en.wikipedia.org/wiki/Network_address). S... |
How do you determine if an IP address is private, in Python? | 691,045 | 16 | 2009-03-27T18:51:53Z | 31,036,423 | 11 | 2015-06-24T20:30:24Z | [
"python",
"network-programming",
"ip-address"
] | In Python, what is the best way to determine if an IP address (e.g., `'127.0.0.1'` or `'10.98.76.6'`) is on a [private network](http://en.wikipedia.org/wiki/Private%5Fnetwork)? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to conside... | Since Python 3.3 there is an [ipaddress module](https://docs.python.org/3/library/ipaddress.html) in the stdlib that you can use.
```
>>> import ipaddress
>>> ipaddress.ip_address('192.168.0.1').is_private
True
```
If using Python 2.6 or higher I would strongly recommend to use [a backport of this module](https://pyp... |
Pythonic way to implement a tokenizer | 691,148 | 11 | 2009-03-27T19:20:43Z | 691,169 | 28 | 2009-03-27T19:24:07Z | [
"python",
"coding-style",
"tokenize"
] | I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?
I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.
Listing Token Types:
In Java, for example, I would have a ... | Python takes a "we're all consenting adults" approach to information hiding. It's OK to use variables as though they were constants, and trust that users of your code won't do something stupid. |
Pythonic way to implement a tokenizer | 691,148 | 11 | 2009-03-27T19:20:43Z | 691,230 | 10 | 2009-03-27T19:45:28Z | [
"python",
"coding-style",
"tokenize"
] | I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?
I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.
Listing Token Types:
In Java, for example, I would have a ... | In many situations, exp. when parsing long input streams, you may find it more useful to implement you tokenizer as a generator function. This way you can easily iterate over all the tokens without the need for lots of memory to build the list of tokens first.
For generator see the [original proposal](http://www.pytho... |
Pythonic way to implement a tokenizer | 691,148 | 11 | 2009-03-27T19:20:43Z | 691,591 | 7 | 2009-03-27T21:48:18Z | [
"python",
"coding-style",
"tokenize"
] | I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?
I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.
Listing Token Types:
In Java, for example, I would have a ... | Thanks for your help, I've started to bring these ideas together, and I've come up with the following. Is there anything terribly wrong with this implementation (particularly I'm concerned about passing a file object to the tokenizer):
```
class Tokenizer(object):
def __init__(self,file):
self.file = file
d... |
Pythonic way to implement a tokenizer | 691,148 | 11 | 2009-03-27T19:20:43Z | 693,818 | 46 | 2009-03-29T00:01:04Z | [
"python",
"coding-style",
"tokenize"
] | I'm going to implement a tokenizer in Python and I was wondering if you could offer some style advice?
I've implemented a tokenizer before in C and in Java so I'm fine with the theory, I'd just like to ensure I'm following pythonic styles and best practices.
Listing Token Types:
In Java, for example, I would have a ... | There's an undocumented class in the `re` module called `re.Scanner`. It's very straightforward to use for a tokenizer:
```
import re
scanner=re.Scanner([
(r"[0-9]+", lambda scanner,token:("INTEGER", token)),
(r"[a-z_]+", lambda scanner,token:("IDENTIFIER", token)),
(r"[,.]+", lambda scanner,token:("PUN... |
Passing functions which have multiple return values as arguments in Python | 691,267 | 9 | 2009-03-27T19:55:29Z | 691,274 | 17 | 2009-03-27T19:56:57Z | [
"python",
"return-value",
"function-calls"
] | So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.
```
a = [[1,2],[3,4]]
def cord():
return 1, 1
def printa(y,x):
print a[y][x]
printa(cord())
```
...but it's not. I'm aware that you can do the same thing by... | ```
printa(*cord())
```
The `*` here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.
It's basically the reverse of the `*` you might use to capture all ... |
Handling output of python socket recv | 691,345 | 3 | 2009-03-27T20:26:51Z | 691,365 | 8 | 2009-03-27T20:32:52Z | [
"python",
"sockets"
] | Apologies for the noob Python question but I've been stuck on this for far too long.
I'm using python sockets to receive some data from a server. I do this:
```
data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)
```
The output on the console is this:
> data is
> repr(data) is '\... | You probably want to use [struct](http://docs.python.org/library/struct.html#module-struct).
The code would look something like:
```
import struct
data = self.socket.recv(4)
print "data is ", data
print "repr(data) is ", repr(data)
myint = struct.unpack("!i", data)[0]
``` |
Is it bad form to call a classmethod as a method from an instance? | 692,040 | 20 | 2009-03-28T02:21:05Z | 692,388 | 20 | 2009-03-28T07:35:40Z | [
"python",
"class-method"
] | Ex.
If I have something like this:
```
class C(object):
@classmethod
def f(cls, x):
return x + x
```
This will work:
```
c = C()
c.f(2)
4
```
But is that bad form?
Should I only call
```
C.f()
```
or
```
c.__class__.f()
```
Obviously, this would only make sense in cases where f doesn't interact... | If you are tempted to call a class method from an instance you probably don't need a class method.
In the example you gave a static method would be more appropriate precisely because of your last remark (no self/cls interaction).
```
class C(object):
@staticmethod
def f(x):
return x + x
```
this way i... |
How can you find unused functions in Python code? | 693,070 | 37 | 2009-03-28T16:42:42Z | 693,183 | 19 | 2009-03-28T17:39:45Z | [
"python",
"refactoring",
"dead-code"
] | So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?
I've seen these two references: [Find unused code](http://stackoverflow.com/questions/245963) and [Tool to find unused functions in php project](http://stackoverflow.com/questions/11532), but they seem sp... | [pylint](http://www.logilab.org/857) can do what you want. |
How can you find unused functions in Python code? | 693,070 | 37 | 2009-03-28T16:42:42Z | 9,824,998 | 29 | 2012-03-22T15:06:44Z | [
"python",
"refactoring",
"dead-code"
] | So you've got some legacy code lying around in a fairly hefty project. How can you find and delete dead functions?
I've seen these two references: [Find unused code](http://stackoverflow.com/questions/245963) and [Tool to find unused functions in php project](http://stackoverflow.com/questions/11532), but they seem sp... | In python you can find unused code by using dynamic or static code analyzers. Two examples for dynamic analyzers are **coverage** and **figleaf**. They have the drawback that you have to run all possible branches of your code in order to find unused parts, but they also have the advantage that you get very reliable res... |
Alter all values in a Python list of lists? | 693,630 | 4 | 2009-03-28T22:15:04Z | 693,834 | 11 | 2009-03-29T00:09:02Z | [
"python"
] | Let's say I have a list like:
```
my_list = [[1,2,3],[4,5,6],[7,8,9]]
```
How do I alter every value in the list without doing?:
```
for x in range(0, 3):
for y in range(0, 3):
my_list[x][y] = -my_list[x][y]
```
I have tried to simplify this by doing
```
my_list = [[[-a, -b, -c] for [a, b, c] in d] for... | Another option is to use the built-in `map` function:
```
>>> my_list = [[1,2,3],[4,5,6],[7,8,9]]
>>> neg = lambda x: -x
>>> f = lambda x: map(neg, x)
>>> map(f, my_list)
[[-1, -2, -3], [-4, -5, -6], [-7, -8, -9]]
``` |
Alter all values in a Python list of lists? | 693,630 | 4 | 2009-03-28T22:15:04Z | 693,876 | 7 | 2009-03-29T00:37:37Z | [
"python"
] | Let's say I have a list like:
```
my_list = [[1,2,3],[4,5,6],[7,8,9]]
```
How do I alter every value in the list without doing?:
```
for x in range(0, 3):
for y in range(0, 3):
my_list[x][y] = -my_list[x][y]
```
I have tried to simplify this by doing
```
my_list = [[[-a, -b, -c] for [a, b, c] in d] for... | Many answers are about creating altered *copy* of list, but literal meaning of question is about in-place modification of list.
Here is my version of best-of-breed in-place list altering solution:
```
def alter_elements(lst, func):
for i, item in enumerate(lst):
if isinstance(item, list):
alter_elements(i... |
why doesn't subprocess.Popen(...) always return? | 694,000 | 5 | 2009-03-29T02:18:09Z | 694,074 | 8 | 2009-03-29T03:47:51Z | [
"python",
"subprocess"
] | I hope this is a simple python question.
When I try the following in the python interpreter:
```
>>> import process
>>> def test(cmd):
... p = subprocess.Popen(cmd)
...
>>> test(['ls', '-l'])
```
It will run the `ls -l`, but I need to hit "return" to get a new >>> prompt.
However, when I try the following:
```
>... | In the first variation, `test()` returns immediately after starting the process, but before its output is sent to the console.
If you look at the output you *do* get the prompt, immediately before the output of `ls`.
```
>>> test(['ls', '-l'])
>>> total 0 <----- test() returns, new propmpt
... |
Understanding Python Class instances | 694,002 | 2 | 2009-03-29T02:19:23Z | 694,020 | 10 | 2009-03-29T02:32:52Z | [
"python",
"class",
"sum"
] | I'm working on a problem which uses a python class and has a constructor function to give the number of sides to one die and a function to roll the die with a random number returned based on the number of sides. I realize the code is very basic, but I'm having troubles understanding how to sum up the total of three rol... | You can store the results in a list:
```
rolls = [Die(n).roll_die() for n in (6, 4, 12)]
```
then you can show the individual results
```
>>> print rolls
[5, 2, 6]
```
or sum them
```
>>> print sum(rolls)
13
```
Or, instead, you could keep a running total:
```
total = 0
for n in (6, 4, 12):
value = Die(n).ro... |
How can I make this recursive crawl function iterative? | 694,366 | 4 | 2009-03-29T09:13:29Z | 694,369 | 11 | 2009-03-29T09:16:53Z | [
"python",
"recursion",
"web-crawler"
] | For academic and performance sake, given this crawl recursive web-crawling function (which crawls only within the given domain) what would be the best approach to make it run iteratively? Currently when it runs, by the time it finishes python has climbed to using over 1GB of memory which isn't acceptable for running in... | Use a BFS instead of crawling recursively (DFS): <http://en.wikipedia.org/wiki/Breadth_first_search>
You can use an external storage solution (such as a database) for BFS queue to free up RAM.
The algorithm is:
```
//pseudocode:
var urlsToVisit = new Queue(); // Could be a queue (BFS) or stack(DFS). (probably with a... |
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x? | 695,370 | 26 | 2009-03-29T21:01:56Z | 695,428 | 32 | 2009-03-29T21:37:41Z | [
"python",
"multicore",
"llvm",
"unladen-swallow"
] | Google is sponsoring an Open Source project to increase the speed of Python by 5x.
[Unladen-Swallow](http://code.google.com/p/unladen-swallow/) seems to have a [good project plan](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)
Why is concurrency such a hard problem?
Is LLVM going to solve the concurren... | [LLVM](http://llvm.org/) is several things together - kind of a virtual machine/optimizing compiler, combined with different frontends that take the input in a particular language and output the result in an intermediate language. This intermediate output can be run with the virtual machine, or can be used to generate ... |
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x? | 695,370 | 26 | 2009-03-29T21:01:56Z | 695,433 | 17 | 2009-03-29T21:39:59Z | [
"python",
"multicore",
"llvm",
"unladen-swallow"
] | Google is sponsoring an Open Source project to increase the speed of Python by 5x.
[Unladen-Swallow](http://code.google.com/p/unladen-swallow/) seems to have a [good project plan](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)
Why is concurrency such a hard problem?
Is LLVM going to solve the concurren... | The switch to LLVM itself isn't solving the concurrency problem. That's being solved separately, by getting rid of the [Global Interpreter Lock](http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock).
I'm not sure how I feel about that; I use threads mainly to deal with blocking I/O, not ... |
What is LLVM and How is replacing Python VM with LLVM increasing speeds 5x? | 695,370 | 26 | 2009-03-29T21:01:56Z | 695,479 | 15 | 2009-03-29T22:07:58Z | [
"python",
"multicore",
"llvm",
"unladen-swallow"
] | Google is sponsoring an Open Source project to increase the speed of Python by 5x.
[Unladen-Swallow](http://code.google.com/p/unladen-swallow/) seems to have a [good project plan](http://code.google.com/p/unladen-swallow/wiki/ProjectPlan)
Why is concurrency such a hard problem?
Is LLVM going to solve the concurren... | LLVM takes care of the nitty-gritty of code generation, so it lets them rewrite Psyco in a way that's more general, portable, maintainable. That in turn allows them to rewrite the CPython core, which lets them experiment with alternate GCs and other things needed to improve python's support for concurrency.
In other w... |
How to distinguish between a function and a class method? | 695,679 | 4 | 2009-03-30T00:16:10Z | 695,694 | 11 | 2009-03-30T00:29:51Z | [
"python",
"reflection",
"metaprogramming"
] | If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example.
eg.
```
def get_info(function_or_method) :
print function_or_method
class Foo(... | You can distinguish between the two by checking the type:
```
>>> type(bar)
<type 'function'>
>>> type(Foo.__init__)
<type 'instancemethod'>
```
or
```
>>> import types
>>> isinstance(bar, types.FunctionType)
True
>>> isinstance(bar, types.UnboundMethodType)
True
```
which is the way you'd do it in an `if` statemen... |
How to distinguish between a function and a class method? | 695,679 | 4 | 2009-03-30T00:16:10Z | 695,704 | 8 | 2009-03-30T00:42:17Z | [
"python",
"reflection",
"metaprogramming"
] | If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example.
eg.
```
def get_info(function_or_method) :
print function_or_method
class Foo(... | At the time you are calling `get_info(__init__)` (inside class definition) the `__init__` is an ordinary function.
```
def get_info(function_or_method):
print function_or_method
class Foo(object):
def __init__(self):
pass
get_info(__init__) # function
def bar():
pass
get_info(Foo.__init__)... |
more efficient way to pickle a string | 695,794 | 9 | 2009-03-30T01:48:21Z | 695,858 | 23 | 2009-03-30T02:40:30Z | [
"python",
"numpy",
"pickle",
"space-efficiency"
] | The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following
```
z = numpy.zeros(1000, numpy.uint8)
len(z.dumps())
len(cPickle.dumps(z.dumps()))
```
The lengths are 1133 characters and 4249 characters respectively.
z.dumps() reveals some... | Try using a later version of the pickle protocol with the protocol parameter to `pickle.dumps()`. The default is 0 and is an ASCII text format. Ones greater than 1 (I suggest you use pickle.HIGHEST\_PROTOCOL). Protocol formats 1 and 2 (and 3 but that's for py3k) are binary and should be more space conservative. |
more efficient way to pickle a string | 695,794 | 9 | 2009-03-30T01:48:21Z | 696,716 | 8 | 2009-03-30T10:38:05Z | [
"python",
"numpy",
"pickle",
"space-efficiency"
] | The pickle module seems to use string escape characters when pickling; this becomes inefficient e.g. on numpy arrays. Consider the following
```
z = numpy.zeros(1000, numpy.uint8)
len(z.dumps())
len(cPickle.dumps(z.dumps()))
```
The lengths are 1133 characters and 4249 characters respectively.
z.dumps() reveals some... | Solution:
```
import zlib, cPickle
def zdumps(obj):
return zlib.compress(cPickle.dumps(obj,cPickle.HIGHEST_PROTOCOL),9)
def zloads(zstr):
return cPickle.loads(zlib.decompress(zstr))
>>> len(zdumps(z))
128
``` |
Re-raise exception with a different type and message, preserving existing information | 696,047 | 41 | 2009-03-30T05:04:34Z | 696,087 | 8 | 2009-03-30T05:38:00Z | [
"python",
"exception-handling",
"polymorphism"
] | I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a `FooError` abstract class for all the `foo` module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many... | You could create your own exception type that extends [whichever exception](http://docs.python.org/library/exceptions.html) you've caught.
```
class NewException(CaughtException):
def __init__(self, caught):
self.caught = caught
try:
...
except CaughtException as e:
...
raise NewException(e)
`... |
Re-raise exception with a different type and message, preserving existing information | 696,047 | 41 | 2009-03-30T05:04:34Z | 696,095 | 21 | 2009-03-30T05:40:08Z | [
"python",
"exception-handling",
"polymorphism"
] | I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a `FooError` abstract class for all the `foo` module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many... | You can use sys.exc\_info() to get the traceback, and raise your new exception with said traceback (as the PEP mentions). If you want to preserve the old type and message, you can do so on the exception, but that's only useful if whatever catches your exception looks for it.
For example
```
import sys
def failure():... |
Re-raise exception with a different type and message, preserving existing information | 696,047 | 41 | 2009-03-30T05:04:34Z | 792,163 | 38 | 2009-04-27T03:25:42Z | [
"python",
"exception-handling",
"polymorphism"
] | I'm writing a module and want to have a unified exception hierarchy for the exceptions that it can raise (e.g. inheriting from a `FooError` abstract class for all the `foo` module's specific exceptions). This allows users of the module to catch those particular exceptions and handle them distinctly, if needed. But many... | **Python 3** introduced **exception chaining** (as described in [PEP 3134](http://www.python.org/dev/peps/pep-3134/)). This allows raising an exception, citing an existing exception as the âcauseâ:
```
try:
frobnicate()
except KeyError as exc:
raise ValueError("Bad grape") from exc
```
In **Python 2**, it... |
Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument? | 696,345 | 7 | 2009-03-30T07:56:27Z | 696,838 | 8 | 2009-03-30T11:26:52Z | [
"python",
"windows",
"windows-xp",
"subprocess",
"python-2.6"
] | Is there a way to terminate a process started with the subprocess.Popen class with the "shell" argument set to "True"? In the working minimal example below (uses wxPython) you can open and terminate a Notepad process happily, however if you change the Popen "shell" argument to "True" then the Notepad process doesn't te... | Why are you using `shell=True`?
Just don't do it. You don't need it, it invokes the shell and that is useless.
I don't accept it has to be `True`, because it doesn't. Using `shell=True` only brings you problems and no benefit. Just avoid it at all costs. Unless you're running some shell internal command, you don't ne... |
What is the pythonic way to share common files in multiple projects? | 696,792 | 4 | 2009-03-30T11:12:51Z | 696,825 | 8 | 2009-03-30T11:24:34Z | [
"python"
] | Lets say I have projects x and y in brother directories: projects/x and projects/y.
There are some utility funcs common to both projects in myutils.py and some db stuff in mydbstuff.py, etc.
Those are minor common goodies, so I don't want to create a single package for them.
Questions arise about the whereabouts o... | The pythonic way is to create a single extra package for them.
Why don't you want to create a package? You can distribute this package with both projects, and the effect would be the same.
You'll never do it right for all instalation scenarios and platforms if you do it by mangling with PYTHONPATH and custom imports.... |
Populate a list in python | 696,874 | 4 | 2009-03-30T11:39:52Z | 696,885 | 8 | 2009-03-30T11:46:32Z | [
"python",
"list",
"tuples"
] | I have a series of Python tuples representing coordinates:
```
tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]
```
I want to create the following list:
```
l = []
for t in tuples:
l[ t[0] ][ t[1] ] = something
```
I get an IndexError: list index out of range.
My background is in PHP and I expected that in Python yo... | No, you cannot create list with gaps. But you can create a dictionary with tuple keys:
```
tuples = [(1,1), (0,1), (1,0), (0,0), (2,1)]
l = {}
for t in tuples:
l[t] = something
```
**Update:**
Try using [NumPy](http://numpy.scipy.org/), it provides wide range of operations over matrices and array. Cite from free ... |
How do I configure Eclipse to launch a browser when Run or Debug is selected using Pydev plugin | 697,142 | 13 | 2009-03-30T13:14:05Z | 1,182,231 | 7 | 2009-07-25T14:50:33Z | [
"python",
"eclipse",
"eclipse-plugin",
"pydev"
] | I'm learning Python and Django using the Eclipse Pydev plugin. I want the internal or external browser to launch or refresh with the URL http:/127.0.0.1 when I press Run or Debug. I've seen it done with the PHP plugins but not Pydev. | Here are the steps to set up an external launch configuration to launch IE:
1. Select **Run**->**External Tools**->**External Tools Configurations...**
2. In the left hand pane, select **Program** then the new icon (left-most icon above the pane).
3. In the right hand pane, select the **Main** tab.
4. Enter **launch\_... |
Importing in Python | 697,281 | 2 | 2009-03-30T13:46:55Z | 697,693 | 7 | 2009-03-30T15:26:43Z | [
"python",
"import"
] | In Python 2.5, I import modules by changing environment variables. It works, but using site-packages does not. Is there another way to import modules in directories other than C:\Python25 ? | On way is with [**`PYTHONPATH`**](http://docs.python.org/using/cmdline.html#envvar-PYTHONPATH) environment variable. Other one is to add path to [**`sys.path`**](http://docs.python.org/library/sys.html#sys.path) either directly by **`sys.path.append(path)`** or by defining **`.pth`** files and add them to with [**`site... |
How do I get the filepath for a class in Python? | 697,320 | 40 | 2009-03-30T13:58:59Z | 697,356 | 19 | 2009-03-30T14:05:42Z | [
"python",
"class",
"introspection"
] | Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.
The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that use... | try:
```
import sys, os
os.path.abspath(sys.modules[LocationArtifact.__module__].__file__)
``` |
How do I get the filepath for a class in Python? | 697,320 | 40 | 2009-03-30T13:58:59Z | 697,395 | 57 | 2009-03-30T14:14:55Z | [
"python",
"class",
"introspection"
] | Given a class C in Python, how can I determine which file the class was defined in? I need something that can work from either the class C, or from an instance off C.
The reason I am doing this, is because I am generally a fan off putting files that belong together in the same folder. I want to create a class that use... | You can use the [inspect](http://docs.python.org/library/inspect.html#inspect.getfile) module, like this:
```
import inspect
inspect.getfile(C.__class__)
``` |
abstracting the conversion between id3 tags, m4a tags, flac tags | 697,776 | 13 | 2009-03-30T15:49:59Z | 699,218 | 8 | 2009-03-30T22:04:09Z | [
"python",
"bash",
"mp3",
"m4a"
] | I'm looking for a resource in python or bash that will make it easy to take, for example, mp3 file X and m4a file Y and say "copy X's tags to Y".
Python's "mutagen" module is great for manupulating tags in general, but there's no abstract concept of "artist field" that spans different types of tag; I want a library th... | I needed this exact thing, and I, too, realized quickly that mutagen is not a distant enough abstraction to do this kind of thing. Fortunately, the authors of mutagen needed it for their media player [QuodLibet](http://code.google.com/p/quodlibet/).
I had to dig through the QuodLibet source to find out how to use it, ... |
Dilemma: Should I learn Seaside or a Python framework? | 697,866 | 9 | 2009-03-30T16:11:14Z | 697,920 | 8 | 2009-03-30T16:23:23Z | [
"python",
"frameworks",
"seaside"
] | I know it's kinda subjective but, if you were to put yourself in my shoes **which would you invest the time in learning?**
I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phon... | I'd say take a look at [Django](http://www.djangoproject.com). It's a Python framework with a ready-made authentication system that's independent of the hosting OS, which means that compromises are limited to the app that was compromised (barring some exploit against the web server hosting the Python process). |
Dilemma: Should I learn Seaside or a Python framework? | 697,866 | 9 | 2009-03-30T16:11:14Z | 697,940 | 10 | 2009-03-30T16:26:44Z | [
"python",
"frameworks",
"seaside"
] | I know it's kinda subjective but, if you were to put yourself in my shoes **which would you invest the time in learning?**
I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phon... | Forget about mod\_python, there is [WSGI](http://www.python.org/dev/peps/pep-0333/).
I'd recommend [Django](http://www.djangoproject.com/). It runs on any [WSGI](http://www.python.org/dev/peps/pep-0333/) server, there are a lot to choose from. There is [mod\_wsgi](http://code.google.com/p/modwsgi/) for Apache, [wsgire... |
Dilemma: Should I learn Seaside or a Python framework? | 697,866 | 9 | 2009-03-30T16:11:14Z | 698,677 | 10 | 2009-03-30T19:28:25Z | [
"python",
"frameworks",
"seaside"
] | I know it's kinda subjective but, if you were to put yourself in my shoes **which would you invest the time in learning?**
I want to write a web app which deals securely with relatively modest amounts of peoples private data, a few thousand records of a few Kb each but stuff that needs to be kept safe, addresses, phon... | Disclaimer: I really don't like PHP, Python is nice, but doesn't come close to Smalltalk in my book. But I am a biased Smalltalker. Some answers about Seaside/Squeak:
Q: Which I guess runs on a squeak app server?
Seaside runs in several different Smalltalks (VW, Gemstone, Squeak etc). The term "app server" is not rea... |
How to send a session message to an anonymous user in a Django site? | 697,902 | 5 | 2009-03-30T16:19:00Z | 698,934 | 7 | 2009-03-30T20:45:38Z | [
"python",
"django",
"session",
"django-views"
] | I often show messages about user actions to logged in users in my Django app views using:
```
request.user.message_set.create("message to user")
```
How could I do the same for anonymous (not logged in) users? There is no request.user for anonymous users, but the Django documentation says that using the "session" mid... | This is what I do, using context processors:
`project/application/context.py` (check for messages and add them to the context):
```
def messages(request):
messages = {}
if 'message' in request.session:
message_type = request.session.get('message_type', 'error')
messages = {'message': request.s... |
How can I parse a time string containing milliseconds in it with python? | 698,223 | 110 | 2009-03-30T17:36:53Z | 698,279 | 160 | 2009-03-30T17:49:33Z | [
"python",
"date",
"time"
] | I am able to parse strings containing date/time with **time.strptime**
```
>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)
```
How can I parse a time string that contains milliseconds?
```
>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')... | Python 2.6 added a new strftime/strptime macro `%f`, which does microseconds. Not sure if this is documented anywhere. But if you're using 2.6 or 3.0, you can do this:
```
time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S.%f')
```
Edit: I never really work with the `time` module, so I didn't notice this at fi... |
How can I parse a time string containing milliseconds in it with python? | 698,223 | 110 | 2009-03-30T17:36:53Z | 3,916,106 | 12 | 2010-10-12T15:09:19Z | [
"python",
"date",
"time"
] | I am able to parse strings containing date/time with **time.strptime**
```
>>> import time
>>> time.strptime('30/03/09 16:31:32', '%d/%m/%y %H:%M:%S')
(2009, 3, 30, 16, 31, 32, 0, 89, -1)
```
How can I parse a time string that contains milliseconds?
```
>>> time.strptime('30/03/09 16:31:32.123', '%d/%m/%y %H:%M:%S')... | I know this is an older question but I'm still using Python 2.4.3 and I needed to find a better way of converting the string of data to a datetime.
The solution if datetime doesn't support %f and without needing a try/except is:
```
(dt, mSecs) = row[5].strip().split(".")
dt = datetime.datetime(*time.strptim... |
Python tkinter label won't change at beginning of function | 698,707 | 2 | 2009-03-30T19:38:01Z | 699,069 | 10 | 2009-03-30T21:16:58Z | [
"python",
"function",
"label",
"tkinter",
"statusbar"
] | I'm using tkinter with Python to create a user interface for a program that converts Excel files to CSV.
I created a label to act as a status bar, and set statusBarText as a StringVar() as the textvariable. inputFileEntry and outputFileEntry are textvariables that contain the input and output file paths.
```
def conv... | Since you're doing all of this in a single method call, the GUI never gets a chance to update before you start your sub process. Check out update\_idletasks() call...
from <http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html>
**`w.update_idletasks()`**
Some tasks in updating the display, such as resizing and... |
Python: Do Python Lists keep a count for len() or does it count for each call? | 699,177 | 35 | 2009-03-30T21:50:45Z | 699,191 | 41 | 2009-03-30T21:54:32Z | [
"python"
] | If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background? | Don't worry: Of course it saves the count and thus `len()` on lists is a pretty cheap operation. Same is true for strings, dictionaries and sets, by the way! |
Python: Do Python Lists keep a count for len() or does it count for each call? | 699,177 | 35 | 2009-03-30T21:50:45Z | 699,192 | 9 | 2009-03-30T21:54:41Z | [
"python"
] | If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background? | Write your program so that it's **optimised for clarity and easily maintainable**. Is your program clearer with a call to `len(foo)`? Then do that.
Are you worried about the time taken? Use the [`timeit` module in the standard library](https://docs.python.org/3/library/timeit) to *measure* the time taken, and see whet... |
Python: Do Python Lists keep a count for len() or does it count for each call? | 699,177 | 35 | 2009-03-30T21:50:45Z | 699,260 | 19 | 2009-03-30T22:17:54Z | [
"python"
] | If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background? | And one more way to find out how it's done is ~~[to look it up on Google Code Search](http://www.google.com/codesearch/p?hl=en#ggVSD6_h0Ho/Python-2.5/Objects/listobject.c&q=package:python-2.5%20listobject.c%20lang:c&l=370)~~ [look at the source on GitHub](https://github.com/python/cpython/blob/2.5/Objects/listobject.c#... |
Python: Do Python Lists keep a count for len() or does it count for each call? | 699,177 | 35 | 2009-03-30T21:50:45Z | 699,275 | 11 | 2009-03-30T22:23:13Z | [
"python"
] | If I keep calling len() on a very long list, am I wasting time, or does it keep an int count in the background? | [`len` is an O(1) operation](http://books.google.com/books?id=JnR9hQA3SncC&pg=PA478&dq=Python%2Blen%2Bbig%2BO&ei=JUbRSYPqGofqkwTy9%5FihAQ). |
Suppress output in Python calls to executables | 699,325 | 44 | 2009-03-30T22:39:14Z | 699,342 | 8 | 2009-03-30T22:44:20Z | [
"python",
"redirect"
] | I have a binary named `A` that generates output when called. If I call it from a Bash shell, most of the output is suppressed by `A > /dev/null`. All of the output is suppressed by `A &> /dev/null`
I have a python script named `B` that needs to call `A`. I want to be able to generate output from `B`, while suppressing... | As the os.system() docs mention, use the [subprocess](http://docs.python.org/library/subprocess.html) module, and, if you like, set stdout=open(os.devnull, 'w') (and perhaps the same for stderr) when you open the subprocess. |
Suppress output in Python calls to executables | 699,325 | 44 | 2009-03-30T22:39:14Z | 699,365 | 57 | 2009-03-30T22:49:56Z | [
"python",
"redirect"
] | I have a binary named `A` that generates output when called. If I call it from a Bash shell, most of the output is suppressed by `A > /dev/null`. All of the output is suppressed by `A &> /dev/null`
I have a python script named `B` that needs to call `A`. I want to be able to generate output from `B`, while suppressing... | If you have Python 2.4, you can use [the subprocess module](http://docs.python.org/library/subprocess.html):
```
>>> import subprocess
>>> s = subprocess.Popen(['cowsay', 'hello'], \
stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0]
>>> print s
_______
< hello >
-------
\ ^__^
... |
Suppress output in Python calls to executables | 699,325 | 44 | 2009-03-30T22:39:14Z | 699,374 | 102 | 2009-03-30T22:53:27Z | [
"python",
"redirect"
] | I have a binary named `A` that generates output when called. If I call it from a Bash shell, most of the output is suppressed by `A > /dev/null`. All of the output is suppressed by `A &> /dev/null`
I have a python script named `B` that needs to call `A`. I want to be able to generate output from `B`, while suppressing... | ```
import os
import subprocess
command = ["executable", "argument_1", "argument_2"]
with open(os.devnull, "w") as fnull:
result = subprocess.call(command, stdout = fnull, stderr = fnull)
```
If the command doesn't have any arguments, you can just provide it as a simple string.
If your command relies on shell f... |
Suppress output in Python calls to executables | 699,325 | 44 | 2009-03-30T22:39:14Z | 2,728,111 | 12 | 2010-04-28T09:15:37Z | [
"python",
"redirect"
] | I have a binary named `A` that generates output when called. If I call it from a Bash shell, most of the output is suppressed by `A > /dev/null`. All of the output is suppressed by `A &> /dev/null`
I have a python script named `B` that needs to call `A`. I want to be able to generate output from `B`, while suppressing... | If your search engine lead you to this old question (like me), be aware that using PIPE may lead to **deadlocks**.
Indeed, because pipes are buffered, you can write a certain number of bytes in a pipe, even if no one read it. However the size of buffer is finite. And consequently if your program A has an output larger ... |
Suppress output in Python calls to executables | 699,325 | 44 | 2009-03-30T22:39:14Z | 7,594,585 | 21 | 2011-09-29T08:37:55Z | [
"python",
"redirect"
] | I have a binary named `A` that generates output when called. If I call it from a Bash shell, most of the output is suppressed by `A > /dev/null`. All of the output is suppressed by `A &> /dev/null`
I have a python script named `B` that needs to call `A`. I want to be able to generate output from `B`, while suppressing... | In Python 3.3 and higher, `subprocess` supports [an option for redirecting to `/dev/null`](http://docs.python.org/3.3/library/subprocess.html#subprocess.DEVNULL). To use it, when calling `.Popen` and friends, specify `stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,` as keyword arguments.
So DNS's answer, rewritt... |
What's the best way to tell if a Python program has anything to read from stdin? | 699,390 | 23 | 2009-03-30T22:58:26Z | 699,446 | 49 | 2009-03-30T23:16:13Z | [
"python"
] | I want a program to do one thing if executed like this:
```
cat something | my_program.py
```
and do another thing if run like this
```
my_program.py
```
But if I read from stdin, then it will wait for user input, so I want to see if there is anything to read before trying to read from stdin. | If you want to detect if someone is piping data into your program, or running it interactively you can use isatty to see if stdin is a terminal:
```
$ python -c 'import sys; print sys.stdin.isatty()'
True
$ echo | python -c 'import sys; print sys.stdin.isatty()'
False
``` |
Python/Django: Creating a simpler list from values_list() | 699,462 | 17 | 2009-03-30T23:24:00Z | 699,472 | 56 | 2009-03-30T23:27:40Z | [
"python",
"django"
] | Consider:
```
>>>jr.operators.values_list('id')
[(1,), (2,), (3,)]
```
How does one simplify further to:
```
['1', '2', '3']
```
The purpose:
```
class ActivityForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ActivityForm, self).__init__(*args, **kwargs)
if self.initial['job_re... | Use the `flat=True` construct of the django queryset: <https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values_list>
From the example in the docs:
```
>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]
``` |
Python HTML sanitizer / scrubber / filter | 699,468 | 60 | 2009-03-30T23:25:29Z | 699,483 | 40 | 2009-03-30T23:35:40Z | [
"python",
"html",
"filter"
] | I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist. | Here's a simple solution using [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/):
```
from bs4 import BeautifulSoup
VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br']
def sanitize_html(value):
soup = BeautifulSoup(value)
for tag in soup.findAll(True):
if tag.name not in VALID_TAGS:
... |
Python HTML sanitizer / scrubber / filter | 699,468 | 60 | 2009-03-30T23:25:29Z | 812,785 | 34 | 2009-05-01T19:05:45Z | [
"python",
"html",
"filter"
] | I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist. | The above solutions via Beautiful Soup will not work. You might be able to hack something with Beautiful Soup above and beyond them, because Beautiful Soup provides access to the parse tree. In a while, I think I'll try to solve the problem properly, but it's a week-long project or so, and I don't have a free week soon... |
Python HTML sanitizer / scrubber / filter | 699,468 | 60 | 2009-03-30T23:25:29Z | 812,865 | 24 | 2009-05-01T19:26:54Z | [
"python",
"html",
"filter"
] | I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist. | Here is what i use in my own project. The acceptable\_elements/attributes come from [feedparser](http://pythonhosted.org/feedparser/html-sanitization.html) and BeautifulSoup does the work.
```
from BeautifulSoup import BeautifulSoup
acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
'... |
Python HTML sanitizer / scrubber / filter | 699,468 | 60 | 2009-03-30T23:25:29Z | 2,702,587 | 50 | 2010-04-23T23:43:24Z | [
"python",
"html",
"filter"
] | I'm looking for a module that will remove any HTML tags from a string that are not found in a whitelist. | Use [`lxml.html.clean`](http://lxml.de/lxmlhtml.html#cleaning-up-html)! It's VERY easy!
```
from lxml.html.clean import clean_html
print clean_html(html)
```
Suppose the following html:
```
html = '''\
<html>
<head>
<script type="text/javascript" src="evil-site"></script>
<link rel="alternate" type="text/rss"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.