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 efficient is threading in Python? | 5,128,072 | 8 | 2011-02-26T16:19:11Z | 5,128,162 | 8 | 2011-02-26T16:33:36Z | [
"python",
"multithreading"
] | I heard threading is not very efficient in Python (compared to other languages).
Is this true? If so, how can a Python programmer overcome this? | CPython uses reference counting with a cyclic garbage collector for memory management. To make this practical, it has a mechanism called the "global interpreter lock" which protects the reference counting system, along with all the other interpreter internals.
On a single-core machine, this doesn't matter - all thread... |
zc.lockfile.LockError in ZODB | 5,128,807 | 4 | 2011-02-26T18:16:38Z | 5,128,988 | 11 | 2011-02-26T18:44:07Z | [
"python",
"zodb"
] | I am trying to use ZODB 3.10.2 on my web server which is running Debian and Python 2.7.1. It seems like every time I try to access the same database from 2 different processes, I get a mysterious exception. I tried accessing a database from an interactive Python session and everything seemed to work fine:
```
>>> impo... | The ZODB does not support multi-process access. This is why you get the lock error; the ZODB file storage has been locked by one process to prevent other processes altering it.
There are several ways around this. The easiest option is to use [ZEO](http://wiki.zope.org/ZODB/guide/zeo.html). ZEO extends the ZODB machine... |
ImportError: No module named _ssl | 5,128,845 | 21 | 2011-02-26T18:21:46Z | 5,128,893 | 9 | 2011-02-26T18:28:33Z | [
"python",
"python-2.7"
] | Ubuntu Maverick w/Python 2.7:
I can't figure out what to do to resolve the following import error:
```
>>> import ssl
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/ssl.py", line 60, in <module>
import _ssl # if we can't import it, let the erro... | Did you build the Python from source? If so, you need the `--with-ssl` option while building. |
ImportError: No module named _ssl | 5,128,845 | 21 | 2011-02-26T18:21:46Z | 19,658,289 | 10 | 2013-10-29T12:31:21Z | [
"python",
"python-2.7"
] | Ubuntu Maverick w/Python 2.7:
I can't figure out what to do to resolve the following import error:
```
>>> import ssl
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/ssl.py", line 60, in <module>
import _ssl # if we can't import it, let the erro... | If you built Python from source, this is just a matter of dependencies: since you miss OpenSSL lib installed, python silently fails installing the **\_ssl** module. You can see it in the final report of the **make** command:
```
Python build finished, but the necessary bits to build these modules were not found:
_bsdd... |
ImportError: No module named _ssl | 5,128,845 | 21 | 2011-02-26T18:21:46Z | 31,643,606 | 22 | 2015-07-27T01:02:02Z | [
"python",
"python-2.7"
] | Ubuntu Maverick w/Python 2.7:
I can't figure out what to do to resolve the following import error:
```
>>> import ssl
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/ssl.py", line 60, in <module>
import _ssl # if we can't import it, let the erro... | Unrelated to the original question, but because this is the first Google result... I hit this on **Google AppEngine** and had to add:
```
libraries:
- name: ssl
version: latest
```
to ***app.yaml*** per: <https://cloud.google.com/appengine/docs/python/sockets/ssl_support>
Please NOTE: This seems to work upto Pytho... |
Python - Set class property to depend on values of other properties in the same class | 5,130,301 | 2 | 2011-02-26T23:02:10Z | 5,130,337 | 9 | 2011-02-26T23:08:22Z | [
"python",
"class",
"function",
"methods",
"properties"
] | Sorry if this already exists somewhere in the question archives, but I'm not sure how to ask it and searching didn't lead to any great revelations.
In Python (2.6.x) I have created a class
```
class timetuple(object):
def __init__(self):
self.weekday = 6
self.month = 1
self.day = 1
... | You want to actually define a property, as opposed to a variable:
```
class A(object):
def __init__(self):
self.a = 1
self.b = 1
@property
def a_plus_b(self):
return self.a + self.b
foo = A()
print foo.a_plus_b # prints "2"
foo.a = 3
print foo.a_plus_b # prints "4"
foo.b = 4
prin... |
Namedtuple like class | 5,131,044 | 6 | 2011-02-27T02:29:30Z | 5,131,130 | 8 | 2011-02-27T02:51:06Z | [
"python"
] | I find myself writing this class often in my python code when I need a quick single use class.
```
class Struct(object):
def __init__( self, **kwargs ):
for k in kwargs:
setattr(self,k,kwargs[k])
```
The basic idea is so I can do quick things like this:
```
foo = Struct( bar='one', baz=1 )
print fo... | There is a python recipe for this (It just updates the instance's dict instead of calling setattr)
[Recipe 52308](http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/?in=user-97991)
```
class Bunch(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
``` |
HTTP Basic Authentication Doesn't Seem to Work with urllib2 in python | 5,131,403 | 7 | 2011-02-27T04:12:22Z | 5,131,492 | 9 | 2011-02-27T04:40:37Z | [
"python",
"urllib2",
"basic-authentication",
"http-basic-authentication"
] | I'm trying to download a page protected with basic authentication using urllib2. I'm using python 2.7 but I also tried it on another computer with python 2.5 and encountered the exact same behavior. I followed the example given in [this guide](http://www.voidspace.org.uk/python/articles/authentication.shtml) as closely... | I think that's caused by this:
```
WWW-Authenticate: Digest
```
It appears the resource is authenticated with Digest rather than Basic. Which means you should use [urllib2.HTTPDigestAuthHandler](http://docs.python.org/library/urllib2.html#urllib2.HTTPDigestAuthHandler) instead.
The code might be
```
import urllib2
... |
multiplication result is negative zero | 5,131,428 | 3 | 2011-02-27T04:22:03Z | 5,131,462 | 7 | 2011-02-27T04:30:16Z | [
"python"
] | can someone tell me why the output of the code mentioned below is negative zero??
a \* b = -0
here 'a' is of type long, b is an object of decimal class.....and if a=-28 and b=0, then the output is -0 | From the Python [`decimal`](http://docs.python.org/library/decimal.html#special-values) docs:
> The signed zeros can result from
> calculations that underflow. They keep
> the sign that would have resulted if
> the calculation had been carried out
> to greater precision. Since their
> magnitude is zero, both positive ... |
Slicing a list in Python without generating a copy | 5,131,538 | 19 | 2011-02-27T04:54:23Z | 5,131,550 | 9 | 2011-02-27T04:58:53Z | [
"python",
"list",
"slice"
] | I have the following problem.
> Given a list of integers `L`, I need to generate all of the sublists `L[k:]` `for k in [0, len(L) - 1]`, **without generating copies**.
How do I accomplish this in Python? With a buffer object somehow? | Depending on what you're doing, you might be able to use `islice`:
<http://docs.python.org/library/itertools.html#itertools.islice>
Since it operates via iteration, it won't make new lists, but instead will simply create iterators that `yield` elements from the original list as requested for their ranges. |
Slicing a list in Python without generating a copy | 5,131,538 | 19 | 2011-02-27T04:54:23Z | 5,131,563 | 36 | 2011-02-27T05:03:52Z | [
"python",
"list",
"slice"
] | I have the following problem.
> Given a list of integers `L`, I need to generate all of the sublists `L[k:]` `for k in [0, len(L) - 1]`, **without generating copies**.
How do I accomplish this in Python? With a buffer object somehow? | Slicing lists does not generate copies of the objects in the list; it just copies the references to them.
I had a moment of uncertainty about immutable objects; but I checked and indeed, only the reference is copied:
```
>>> a = [1, 2, 3]
>>> b = a[1:3]
>>> id(a[1])
143727964
>>> id(b[0])
143727964
``` |
Python subprocess.Popen slow under uWSGI | 5,131,700 | 3 | 2011-02-27T05:55:27Z | 5,131,746 | 9 | 2011-02-27T06:08:21Z | [
"python",
"performance",
"popen",
"uwsgi"
] | I've set up a development server running Cherokee on Fedora 14, using uWSGI to interface with my WSGI application.
When the application is hit with the first request, I spawn a process like so:
```
from subprocess import Popen
Popen(['bash']) # bash is just an example; the problem happens with all programs
```
The ... | --close-on-exec
Otherwise your new process will inherith the socket
(this is a UNIX standard behaviour) |
Why urllib returns garbage from some wikipedia articles? | 5,131,985 | 3 | 2011-02-27T07:26:13Z | 5,132,254 | 8 | 2011-02-27T08:45:24Z | [
"python",
"urllib2"
] | ```
>>> import urllib2
>>> good_article = 'http://en.wikipedia.org/wiki/Wikipedia'
>>> bad_article = 'http://en.wikipedia.org/wiki/India'
>>> req1 = urllib2.Request(good_article)
>>> req2 = urllib2.Request(bad_article)
>>> req1.add_header('User-Agent', 'Mozilla/5.0')
>>> req2.add_header('User-Agent', 'Mozilla/5.0')
>... | It's not an environment, locale, or encoding problem. **The offending stream of bytes is gzip-compressed.** The `\x1f\x8B` at the start is what you get at the start of a gzip stream with the default settings.
Looks as though the server is ignoring the fact that you didn't do
`req2.add_header('Accept-encoding', 'gzip'... |
Why do we need to use rabbitmq | 5,132,648 | 28 | 2011-02-27T10:26:43Z | 5,132,740 | 12 | 2011-02-27T10:44:25Z | [
"python",
"django",
"twisted",
"rabbitmq"
] | Why do we need RabbitMQ when we have a more powerful network framework in Python called Twisted. I am trying to understand the reason why someone would want to use RabbitMQ.
Could you please provide a scenario or an example using RabbitMQ?
Also, where can I find a tutorial on how to use RabbitMQ? | Twisted is not a queue implementation. Apart from that RabbitMQ offers enterprise-level queuing features and implements the AMQP protocol which is often needed in an enterprise world. |
Why do we need to use rabbitmq | 5,132,648 | 28 | 2011-02-27T10:26:43Z | 19,206,575 | 13 | 2013-10-06T07:42:45Z | [
"python",
"django",
"twisted",
"rabbitmq"
] | Why do we need RabbitMQ when we have a more powerful network framework in Python called Twisted. I am trying to understand the reason why someone would want to use RabbitMQ.
Could you please provide a scenario or an example using RabbitMQ?
Also, where can I find a tutorial on how to use RabbitMQ? | Let me tell you a few reasons that makes using MOM (Message Oriented Middleware) probably the best choice.
## Decoupling:
It can decouple/separate the core components of the application. There is no need to bring all the benefits of the decoupled architecture here. I just want to point it out that this is one of the ... |
python: abstract base class' __init__(): initializion or validation? | 5,133,262 | 12 | 2011-02-27T12:43:41Z | 5,133,656 | 10 | 2011-02-27T14:09:52Z | [
"python",
"oop",
"software-engineering",
"abstract-class",
"software-design"
] | `class ABC` is an "abstract base class". `class X` is its subclass.
There's some work that needs to be done in any subclass of `ABC`, which is easy to forget or do incorrectly. I'd like `ABC.__init__()` to help catch such mistakes by either:
(1) starting that work, or
(2) validating it
This impacts whether `super().... | Certainly, one prefers approach 1 to approach 2 (as approach 2 relegates the base to a tag interface rather than fulfilling abstract functionality). But, approach 1 doesn't, by itself, meet your goal of preventing the subtype developer from forgetting to implement the super() call properly, ensuring initialization.
yo... |
Mercurial error *** failed to import extension hggit: No module named hggit | 5,133,641 | 24 | 2011-02-27T14:06:28Z | 5,133,779 | 18 | 2011-02-27T14:37:29Z | [
"python",
"osx",
"mercurial",
"hg-git"
] | I installed Mercurial on my Mac, and it's wonderful. For me it's easier to grasp than Git so I wanted to use it to manage git-repositories. Therefore I installed hg-git with the following instructions:
<http://hg-git.github.com/>
But each time I issue a hg command it returns this error message:
```
Mercurial error... | After installing hg-git with the following command:
```
easy_install hg-git
```
Does the following work?
```
python -c "import hggit"
```
What does this say for you:
```
head -n1 `which hg`
```
The point of the latter command is to verify that the Python hg runs under has hggit installed. In my case it says '#!/u... |
Mercurial error *** failed to import extension hggit: No module named hggit | 5,133,641 | 24 | 2011-02-27T14:06:28Z | 12,738,319 | 33 | 2012-10-05T01:31:29Z | [
"python",
"osx",
"mercurial",
"hg-git"
] | I installed Mercurial on my Mac, and it's wonderful. For me it's easier to grasp than Git so I wanted to use it to manage git-repositories. Therefore I installed hg-git with the following instructions:
<http://hg-git.github.com/>
But each time I issue a hg command it returns this error message:
```
Mercurial error... | Note for ubuntu users who install the "mercurial-git" package to get the hggit module on 12.04 some bright spark randomly renamed the module to just "git" so you need to change your ~/.hgrc to look something like
```
[extensions]
hgext.bookmarks =
git =
``` |
Tags with : in name in lxml | 5,134,658 | 5 | 2011-02-27T17:25:05Z | 5,134,787 | 9 | 2011-02-27T17:47:33Z | [
"python",
"xml",
"wordpress",
"lxml",
"elementtree"
] | I'm trying to use lxml.etree to parse a Wordpress export document (it's XML, somewhat RSS like). I'm only interested in published posts, so I'm using the following to loop through published posts:
```
for item in data.findall("item"):
if item.find("wp:post_type").text != "post":
continue
if item.find("... | The `:` is an XML namespace separator. To escape the colon in lxml, you need to replace it with the namespace URL within curly braces, as in `item.find("{http://example.org/}status").text`. |
Is it just me or something is seriously wrong with new Python futures module on windows | 5,134,668 | 4 | 2011-02-27T17:26:34Z | 5,134,730 | 8 | 2011-02-27T17:35:40Z | [
"python",
"future",
"executor",
"concurrent.futures"
] | I am on windows XP and I have problems with new Python 3.2 futures module.
It seems I am unable to get ProcessPoolExecutor to work.
Session example:
```
Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.
>>> from ... | You have to be aware that the [concurrent.future](http://docs.python.org/dev/library/concurrent.futures.html) module use [multiprocessing](http://docs.python.org/library/multiprocessing.html) module (especially when you used the `ProcessPoolExecutor`), so some functionality will not work in the interactive interpreter,... |
Importing Python classes from different files in a subdirectory | 5,134,893 | 20 | 2011-02-27T18:07:17Z | 5,135,444 | 8 | 2011-02-27T19:44:01Z | [
"python",
"import"
] | Here's the structure I'm working with.
```
directory/
script.py
subdir/
__init__.py
myclass01.py
myclass02.py
```
What I want to do is import in script.py the classes defined in myclass01.py and myclass02.py. If I do:
```
from subdir.myclass01 im... | Although the names used there are different from what's shown in your question's directory structure, you could use my answer to the question titled [Python namespacing and classes](http://stackoverflow.com/questions/5117194/python-namespacing-and-classes/5118437#5118437). The `__init__.py` shown there would have also ... |
Can you iterate a number backwards without using a list? | 5,136,344 | 3 | 2011-02-27T22:07:26Z | 5,136,569 | 11 | 2011-02-27T22:42:42Z | [
"python",
"list",
"iteration"
] | How would you iterate a number backwards without using a list in Python 3?
Using lists, I would probably do something like:
```
li = list(range(100))
for i in li[::-1]:
print(i)
```
This is a fine solution, but it does not work with huge numbers.
Right now, I'm trying to iterate a number backwards with large num... | Iterators that provide the `__reversed__()` special method also support reversed iteration. In Python 3.x, `range()` iterators have this method, so you can also use
```
for i in reversed(range(100)):
print(i)
```
In Python 2.x, `xarnge()` allows reversed iteration:
```
for i in reversed(xrange(100)):
print i... |
Capture stdout from a script in Python | 5,136,611 | 39 | 2011-02-27T22:49:33Z | 5,136,686 | 30 | 2011-02-27T23:02:39Z | [
"python",
"stdout",
"sys"
] | suppose there is a script doing something like this:
```
# module writer.py
import sys
def write():
sys.stdout.write("foobar")
```
Now suppose I want to capture the output of the `write` function and store it in a variable for further processing. The naive solution was:
```
# module mymodule.py
from writer impo... | Setting `stdout` is a reasonable way to do it. Another is to run it as another process:
```
import subprocess
proc = subprocess.Popen(["python", "-c", "import writer; writer.write()"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
print out.upper()
``` |
Capture stdout from a script in Python | 5,136,611 | 39 | 2011-02-27T22:49:33Z | 10,743,550 | 25 | 2012-05-24T18:49:31Z | [
"python",
"stdout",
"sys"
] | suppose there is a script doing something like this:
```
# module writer.py
import sys
def write():
sys.stdout.write("foobar")
```
Now suppose I want to capture the output of the `write` function and store it in a variable for further processing. The naive solution was:
```
# module mymodule.py
from writer impo... | Here is a context manager version of your code. It yields a list of two values; the first is stdout, the second is stderr.
```
import contextlib
@contextlib.contextmanager
def capture():
import sys
from cStringIO import StringIO
oldout,olderr = sys.stdout, sys.stderr
try:
out=[StringIO(), Strin... |
Django, Python Modules, and Git Submodules | 5,137,082 | 3 | 2011-02-28T00:21:54Z | 5,139,136 | 7 | 2011-02-28T07:13:25Z | [
"python",
"django",
"git",
"module",
"git-submodules"
] | I am working on a django project that has uses multiple applications (python modules). Most of those python modules are maintained by other people in their own git repositories. I use the git-submodules command to import them into my project under the 'apps' directory like so:
```
mysite/
mysite/apps
mysite/apps/djang... | This is the wrong way to do it. Don't install other people's third-party code in your own project file. Instead, create a virtualenv, and install the code directly using `pip`. |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 5,137,507 | 220 | 2011-02-28T01:53:57Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | Current Working Directory: [os.getcwd()](https://docs.python.org/2/library/os.html#os.getcwd)
And the [\_\_file\_\_ attribute](http://docs.python.org/reference/datamodel.html) can help you find out where the file you are executing is located. This SO post explains everything: [How do I get the path of the current exec... |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 5,137,509 | 1,061 | 2011-02-28T01:54:18Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | To get the full path to the directory a Python file is contained in, write this in that file:
```
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
```
(Note that the incantation above won't work if you've already used `os.chdir()` to change your current working directory, since the value of the `__fi... |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 10,293,159 | 39 | 2012-04-24T07:00:16Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | 1.To get the current directory full path
```
>>import os
>>print os.getcwd()
```
o/p:"C :\Users\admin\myfolder"
1.To get the current directory folder name alone
```
>>import os
>>str1=os.getcwd()
>>str2=str1.split('\\')
>>n=len(str2)
>>print str2[n-1]
```
o/p:"myfolder" |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 12,767,520 | 24 | 2012-10-07T09:10:44Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | If you are trying to find the current directory of the file you are currently in:
OS agnostic way:
```
dirname, filename = os.path.split(os.path.abspath(__file__))
``` |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 13,720,875 | 168 | 2012-12-05T10:18:07Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | You may find this useful as a reference:
```
import os
print("Path at terminal when executing this file")
print(os.getcwd() + "\n")
print("This file path, relative to os.getcwd()")
print(__file__ + "\n")
print("This file full path (following symlinks)")
full_path = os.path.realpath(__file__)
print(full_path + "\n")... |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 18,185,825 | 13 | 2013-08-12T11:27:46Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | If you're searching for the location of the currently executed script, you can use `sys.argv[0]` to get the full path. |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 19,269,546 | 19 | 2013-10-09T10:31:39Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | A bit late to the party, but I think the most succinct way to find just the name of your current execution context would be
```
current_folder_path, current_folder_name = os.path.split(os.getcwd())
``` |
Find current directory and file's directory | 5,137,497 | 756 | 2011-02-28T01:51:21Z | 28,637,689 | 8 | 2015-02-20T20:32:43Z | [
"python",
"directory"
] | In Python, what commands can I use to find:
1. the current directory (where I was in the terminal when I ran the Python script), and
2. where the file I am executing is? | If you're using Python 3.4, there is the brand new higher-level `pathlib` module which allows you to conveniently call `pathlib.Path.cwd()` to get a `Path` object representing your current working directory, along with many other new features.
More info on this new API can be found [here](https://docs.python.org/3.4/l... |
Setting fixed length with python | 5,138,062 | 7 | 2011-02-28T04:04:47Z | 5,138,071 | 8 | 2011-02-28T04:06:46Z | [
"python"
] | I have str that are like '60' or '100'.
I need the str to be '00060' and '00100',
How can i do this?
code is something like this:
I was using '0'+'0'+'0' as plug. now need to fix
d==0006000100
```
a4 ='60'
a5 ='100'
d=('0'+'0'+'0'+a4+'0'+'0'+a5)
``` | Like this:
```
num = 60
formatted_num = u'%05d' % num
```
See the [docs](http://docs.python.org/library/stdtypes.html#string-formatting) for more information about formatting numbers as strings.
If your number is already a string (as your updated question indicates), you can pad it with zeros to the right width usi... |
Setting fixed length with python | 5,138,062 | 7 | 2011-02-28T04:04:47Z | 5,138,105 | 19 | 2011-02-28T04:13:04Z | [
"python"
] | I have str that are like '60' or '100'.
I need the str to be '00060' and '00100',
How can i do this?
code is something like this:
I was using '0'+'0'+'0' as plug. now need to fix
d==0006000100
```
a4 ='60'
a5 ='100'
d=('0'+'0'+'0'+a4+'0'+'0'+a5)
``` | Since you are manipulating strings, [str.zfill()](http://docs.python.org/library/stdtypes.html#str.zfill) does exactly what you want.
```
>>> s1, s2 = '60', '100'
>>> print s1.zfill(5), s2.zfill(5)
00060 00100
``` |
How to compile python from source and get a clean/minimal install? | 5,138,801 | 4 | 2011-02-28T06:15:49Z | 10,181,996 | 7 | 2012-04-16T21:30:46Z | [
"python",
"installation",
"makefile"
] | If you follow the simple `configure` -> `make` -> `make install` process for compiling python from source code, you end up with a very large install that includes a whole lot of files that are not necessary for a functional python environment. eg: All `.py` files are left in the installation (not just the `.pyc` or `.p... | It may be instructive to look at Debian's `python2.7-minimal` package (`apt-get source python2.7-minimal`). When in doubt, always look to see what others, especially the experts, are doing...
From `debian/rules` there:
```
: # Move the binary and the minimal libraries into $(p_min).
dh_installdirs -p$(p_min) \
... |
python url unquote unicode | 5,139,249 | 10 | 2011-02-28T07:29:35Z | 5,139,885 | 7 | 2011-02-28T09:00:55Z | [
"python"
] | i have a unicode string like `'%C3%A7%C3%B6asd+fjkls%25asd'` and i want to decode this string.
I used urllib.unquote\_plus(str) but it works wrong.
```
- expected : 'çöasd+fjkls%asd '
- result : 'çöasd fjkls%asd'
```
double coded utf-8 characters`(%C3%A7 and %C3%B6)` are decoded wrong.
my python version i... | Using either `unquote` or `unquote_plus` will give you a byte string. If you want a Unicode string then you have to decode the byte string to unicode:
```
>>> print(urllib.unquote_plus('%C3%A7%C3%B6asd+fjkls%25asd').decode('utf8'))
çöasd fjkls%asd
>>>
```
Compared with:
```
>>> print(urllib.unquote_plus('%C3%A7%C3... |
python url unquote unicode | 5,139,249 | 10 | 2011-02-28T07:29:35Z | 5,140,525 | 24 | 2011-02-28T10:02:02Z | [
"python"
] | i have a unicode string like `'%C3%A7%C3%B6asd+fjkls%25asd'` and i want to decode this string.
I used urllib.unquote\_plus(str) but it works wrong.
```
- expected : 'çöasd+fjkls%asd '
- result : 'çöasd fjkls%asd'
```
double coded utf-8 characters`(%C3%A7 and %C3%B6)` are decoded wrong.
my python version i... | You have 3 or 4 or 5 problems ... but `repr()` and `unicodedata.name()` are your friends; they unambiguously show you exactly what you have got, without the confusion engendered by people with different console encodings communicating the results of `print fubar`.
Summary: either (a) you start with a unicode object an... |
Passing a python dictionary to a psycopg2 cursor | 5,139,700 | 4 | 2011-02-28T08:35:54Z | 5,139,737 | 8 | 2011-02-28T08:41:00Z | [
"python",
"postgresql",
"psycopg2"
] | I need to call a PostgreSQL 8.4 function which requires 17 input paramters from Python. The values are stored in a dictionary. So I can write:
```
cur.execute("SELECT add_user(%s, %s, %s, %s, %s, %s, %s, .......)", user["nr"], user['email']...)
```
Is it possible to automatically map the values in the dictionary to t... | The following syntax should do it:
```
cur.execute("SELECT add_user(%(nr)s, %(email)s, ...) ...", user)
```
*Thanks to [Thiefmaster](http://stackoverflow.com/users/298479/thiefmaster) for providing a correction to what I had here originally:* The `%(keyname)s` format for parameters is just one of those defined in the... |
Assign pass to a function in Python | 5,140,470 | 8 | 2011-02-28T09:57:52Z | 5,140,584 | 8 | 2011-02-28T10:07:00Z | [
"python",
"function",
"optional-parameters",
"optional-arguments"
] | I have a piece of code that defines a function that takes a function as an argument, like so:
```
def stuff(n, f):
f(n)
```
Now, I want to provide some default value of f that does nothing. So I figured I'd use pass, like so:
```
def stuff(n, f = None):
if(f is None):
f = pass
f(n)
```
But this does not c... | Why not simply this ?
```
def stuff(n, f=None):
if f is None:
return
return f(n)
``` |
Assign pass to a function in Python | 5,140,470 | 8 | 2011-02-28T09:57:52Z | 5,140,606 | 16 | 2011-02-28T10:08:58Z | [
"python",
"function",
"optional-parameters",
"optional-arguments"
] | I have a piece of code that defines a function that takes a function as an argument, like so:
```
def stuff(n, f):
f(n)
```
Now, I want to provide some default value of f that does nothing. So I figured I'd use pass, like so:
```
def stuff(n, f = None):
if(f is None):
f = pass
f(n)
```
But this does not c... | The `pass` is a keyword for the interpreter, a place holder for otherwise nothing. It's not an object that you can assign. You can use a no-op lambda.
```
f = lambda x: None
``` |
Filtering os.walk() dirs and files | 5,141,437 | 26 | 2011-02-28T11:36:53Z | 5,141,710 | 17 | 2011-02-28T12:02:18Z | [
"python",
"filtering",
"os.walk"
] | I'm looking for a way to include/exclude files patterns and exclude directories from a `os.walk()` call.
Here's what I'm doing by now:
```
import fnmatch
import os
includes = ['*.doc', '*.odt']
excludes = ['/home/paulo-freitas/Documents']
def _filter(paths):
matches = []
for path in paths:
append =... | From [docs.python.org](https://docs.python.org/2/library/os.html#os.walk):
> os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
>
> When topdown is True, the caller can modify the dirnames list in-place ⦠this can be used to prune the search â¦
```
for root, dirs, files in os.walk('/home/paulo-freit... |
Filtering os.walk() dirs and files | 5,141,437 | 26 | 2011-02-28T11:36:53Z | 5,141,829 | 36 | 2011-02-28T12:15:22Z | [
"python",
"filtering",
"os.walk"
] | I'm looking for a way to include/exclude files patterns and exclude directories from a `os.walk()` call.
Here's what I'm doing by now:
```
import fnmatch
import os
includes = ['*.doc', '*.odt']
excludes = ['/home/paulo-freitas/Documents']
def _filter(paths):
matches = []
for path in paths:
append =... | This solution uses `fnmatch.translate` to convert glob patterns to regular expressions (it assumes the includes only is used for files):
```
import fnmatch
import os
import os.path
import re
includes = ['*.doc', '*.odt'] # for files only
excludes = ['/home/paulo-freitas/Documents'] # for dirs and files
# transform g... |
Is there an ejabberd python library? | 5,141,462 | 5 | 2011-02-28T11:39:17Z | 11,140,574 | 8 | 2012-06-21T14:39:14Z | [
"python",
"ejabberd"
] | Is there an ejabberd python library wherein I can register user to ejabberd from python programmatically?
Right now I'm executing "ejabberdctl register" command using the python commands module. | ## XMPP XEP-0077
If you have activated [mod\_register](https://git.process-one.net/ejabberd/mainline/blobs/raw/v2.1.11/doc/guide.html#modregister) for [In-Band registration](http://xmpp.org/extensions/xep-0077.html) on your Ejabberd server, then, as pointed out by @Drake, you can use an XMPP library to register users.... |
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) | 5,141,559 | 52 | 2011-02-28T11:48:09Z | 5,141,671 | 24 | 2011-02-28T11:59:03Z | [
"python",
"google-app-engine",
"xml-parsing"
] | I want to parse my XML document. So I have stored my XML document as below
```
class XMLdocs(db.Expando):
id = db.IntegerProperty()
name=db.StringProperty()
content=db.BlobProperty()
```
Now my below is my code
```
parser = make_parser()
curHandler = BasketBallHandler()
parser.setContentHandl... | It seems you are hitting a UTF-8 byte order mark (BOM). Try using this unicode string with BOM extracted out:
```
import codecs
content = unicode(q.content.strip(codecs.BOM_UTF8), 'utf-8')
parser.parse(StringIO.StringIO(content))
```
I used `strip` instead of `lstrip` because in your case you had multiple occurences... |
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) | 5,141,559 | 52 | 2011-02-28T11:48:09Z | 5,146,914 | 100 | 2011-02-28T19:59:44Z | [
"python",
"google-app-engine",
"xml-parsing"
] | I want to parse my XML document. So I have stored my XML document as below
```
class XMLdocs(db.Expando):
id = db.IntegerProperty()
name=db.StringProperty()
content=db.BlobProperty()
```
Now my below is my code
```
parser = make_parser()
curHandler = BasketBallHandler()
parser.setContentHandl... | The actual best answer for this problem depends on your environment, specifically what encoding your terminal expects.
The quickest one-line solution is to encode everything you print to ASCII, which your terminal is almost certain to accept, while discarding characters that you cannot print:
```
print ch #fails
prin... |
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) | 5,141,559 | 52 | 2011-02-28T11:48:09Z | 7,800,489 | 27 | 2011-10-17T22:43:57Z | [
"python",
"google-app-engine",
"xml-parsing"
] | I want to parse my XML document. So I have stored my XML document as below
```
class XMLdocs(db.Expando):
id = db.IntegerProperty()
name=db.StringProperty()
content=db.BlobProperty()
```
Now my below is my code
```
parser = make_parser()
curHandler = BasketBallHandler()
parser.setContentHandl... | This worked for me:
```
from django.utils.encoding import smart_str
content = smart_str(content)
``` |
UnicodeEncodeError: 'ascii' codec can't encode character u'\xef' in position 0: ordinal not in range(128) | 5,141,559 | 52 | 2011-02-28T11:48:09Z | 18,268,929 | 37 | 2013-08-16T08:23:18Z | [
"python",
"google-app-engine",
"xml-parsing"
] | I want to parse my XML document. So I have stored my XML document as below
```
class XMLdocs(db.Expando):
id = db.IntegerProperty()
name=db.StringProperty()
content=db.BlobProperty()
```
Now my below is my code
```
parser = make_parser()
curHandler = BasketBallHandler()
parser.setContentHandl... | Just putting `.encode('utf-8')` at the end of object will do the job in recent versions of Python. |
Is there a function in Python which generates all the strings of length n over a given alphabet? | 5,141,794 | 10 | 2011-02-28T12:11:52Z | 5,141,849 | 38 | 2011-02-28T12:17:32Z | [
"python",
"algorithm",
"string"
] | I need a function `generateAllStrings(n, alphabet)` to do something like this:
```
generateAllStrings(4, ['a','b'])
>>> ["aaaa", "aaab", "aaba", "aabb", "abaa", .... , "bbba", "bbbb"]
```
In other words, `generateAllStrings(n, alphabet)` should return all the possible strings of length n over the chars in the list al... | ```
>>> [''.join(i) for i in itertools.product("ab",repeat=4)]
['aaaa', 'aaab', 'aaba', 'aabb', 'abaa', 'abab', 'abba', 'abbb', 'baaa', 'baab', 'baba', 'babb', 'bbaa', 'bbab', 'bbba', 'bbbb']
``` |
What is the use of "assert" in Python? | 5,142,418 | 274 | 2011-02-28T13:11:45Z | 5,142,453 | 315 | 2011-02-28T13:15:33Z | [
"python",
"assert",
"assertions"
] | I have been reading some source code and in several places I have seen the usage of `assert`.
What does it mean exactly? What is its usage? | The `assert` statement exists in almost every programming language. When you do...
```
assert condition
```
... you're telling the program to test that condition, and trigger an error if the condition is false.
In Python, it's roughly equivalent to this:
```
if not condition:
raise AssertionError()
```
Try it ... |
What is the use of "assert" in Python? | 5,142,418 | 274 | 2011-02-28T13:11:45Z | 5,142,462 | 8 | 2011-02-28T13:16:38Z | [
"python",
"assert",
"assertions"
] | I have been reading some source code and in several places I have seen the usage of `assert`.
What does it mean exactly? What is its usage? | From docs:
```
Assert statements are a convenient way to insert debugging assertions into a program
```
Here you can read more: <http://docs.python.org/release/2.5.2/ref/assert.html> |
What is the use of "assert" in Python? | 5,142,418 | 274 | 2011-02-28T13:11:45Z | 5,142,480 | 26 | 2011-02-28T13:18:19Z | [
"python",
"assert",
"assertions"
] | I have been reading some source code and in several places I have seen the usage of `assert`.
What does it mean exactly? What is its usage? | Others have already given you links to documentation.
You can try the following in a interactive shell:
```
>>> assert 5 > 2
>>> assert 2 > 5
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
builtins.AssertionError:
```
The first try does nothing, while the second raises and exception. Thi... |
What is the use of "assert" in Python? | 5,142,418 | 274 | 2011-02-28T13:11:45Z | 5,143,044 | 68 | 2011-02-28T14:10:37Z | [
"python",
"assert",
"assertions"
] | I have been reading some source code and in several places I have seen the usage of `assert`.
What does it mean exactly? What is its usage? | As other answers have noted, `assert` is similar to throwing an exception if a given condition isn't true. An important difference is that assert statements get ignored if you compile your code with the optimization option. The [documentation](http://docs.python.org/reference/simple_stmts.html#the-assert-statement) say... |
What is the use of "assert" in Python? | 5,142,418 | 274 | 2011-02-28T13:11:45Z | 17,560,982 | 11 | 2013-07-10T01:21:45Z | [
"python",
"assert",
"assertions"
] | I have been reading some source code and in several places I have seen the usage of `assert`.
What does it mean exactly? What is its usage? | The assert statement has two forms.
The simple form, `assert <expression>`, is equivalent to
```
if __âdebug__:
if not <expression>: raise AssertionError
```
The extended form, `assert <expression1>, <expression2>`, is equivalent to
```
if __âdebug__:
if not <expression1>: raise AssertionError, <express... |
What is the use of "assert" in Python? | 5,142,418 | 274 | 2011-02-28T13:11:45Z | 21,887,035 | 10 | 2014-02-19T16:52:57Z | [
"python",
"assert",
"assertions"
] | I have been reading some source code and in several places I have seen the usage of `assert`.
What does it mean exactly? What is its usage? | Assertions are a systematic way to check that the internal state of a program is as the programmer expected, with the goal of catching bugs. See the example below.
```
>>> number = input('Enter a positive number:')
Enter a positive number:-1
>>> assert (number > 0), 'Only positive numbers are allowed!'
Traceback (most... |
What is the use of "assert" in Python? | 5,142,418 | 274 | 2011-02-28T13:11:45Z | 30,770,447 | 89 | 2015-06-11T02:15:30Z | [
"python",
"assert",
"assertions"
] | I have been reading some source code and in several places I have seen the usage of `assert`.
What does it mean exactly? What is its usage? | Watch out for the parentheses. As has been pointed out above, [in Python 3, `assert` is still a statement](https://docs.python.org/3/reference/simple_stmts.html#assert), so by analogy with `print(..)`, one may extrapolate the same to `assert(..)` or `raise(..)` but you shouldn't.
This is important because:
```
assert... |
How can I use a raw_input with twisted? | 5,143,311 | 6 | 2011-02-28T14:34:17Z | 5,143,834 | 7 | 2011-02-28T15:19:21Z | [
"python",
"serial-port",
"twisted"
] | I am aware that raw\_input cannot be used in twisted. However here is my desired application.
I have an piece of hardware that provides an interactive terminal serial port. I am trying to connect to this port and send commands in an async manner. I need it this way because this is a motor controller that once I issue ... | You have a couple of options here that you can use. One would be to use a child process to handle communicating with the serial port and a pipe to communicate between the parent and child (which is simplified by Twisted's Process Protocol). Another is to spin off a separate Python thread and use raw\_input from there. ... |
Preserve end-of-line style when working with files in python | 5,144,382 | 7 | 2011-02-28T16:05:24Z | 5,144,434 | 10 | 2011-02-28T16:09:19Z | [
"python",
"line-endings"
] | I am looking for a way to ensure that the end-of-line style of a file is maintained in python program while reading, editing and writing.
Python has universal file ending support, which can convert all line endings to `\n` when the file is read, and then convert them all to the system default when the file is written.... | Use python's [universal newline support](http://www.python.org/dev/peps/pep-0278/):
```
f = open('randomthing.py', 'rU')
fdata = f.read()
newlines = f.newlines
print repr(newlines)
```
`newlines` contains the file's delimiter or a tuple of delimiters if the file uses a mix of delimiters. |
Python/Scipy 2D Interpolation (Non-uniform Data) | 5,146,025 | 13 | 2011-02-28T18:30:31Z | 5,147,409 | 14 | 2011-02-28T20:49:22Z | [
"python",
"numpy",
"scipy",
"interpolation"
] | This is a follow-up question to my previous post: [Python/Scipy Interpolation (map\_coordinates)](http://stackoverflow.com/questions/5124126/python-scipy-interpolation-map-coordinates)
Let's say I want to interpolate over a 2d rectangular area. My variable 'z' contains the data as shown below. Each column is at a cons... | Looks like you got it.
In your upper code example and in your previous ([linked](http://stackoverflow.com/questions/5124126/python-scipy-interpolation-map-coordinates)) question you have *structured* data. Which can be interpolated using `RectBivariateSpline` or `interp2d`. This means you have data that can be describ... |
Streaming a CSV file in Django | 5,146,539 | 15 | 2011-02-28T19:22:11Z | 5,147,454 | 28 | 2011-02-28T20:53:58Z | [
"python",
"django",
"csv",
"streaming"
] | I am attempting to stream a csv file as an attachment download. The CSV files are getting to be 4MB in size or more, and I need a way for the user to actively download the files without waiting for all of the data to be created and committed to memory first.
I first used my own file wrapper based on Django's `FileWrap... | Here's some simple code that'll stream a CSV; you can probably go from this to whatever you need to do:
```
import cStringIO as StringIO
import csv
def csv(request):
def data():
for i in xrange(10):
csvfile = StringIO.StringIO()
csvwriter = csv.writer(csvfile)
csvwriter... |
Streaming a CSV file in Django | 5,146,539 | 15 | 2011-02-28T19:22:11Z | 19,043,419 | 9 | 2013-09-27T05:41:00Z | [
"python",
"django",
"csv",
"streaming"
] | I am attempting to stream a csv file as an attachment download. The CSV files are getting to be 4MB in size or more, and I need a way for the user to actively download the files without waiting for all of the data to be created and committed to memory first.
I first used my own file wrapper based on Django's `FileWrap... | The middleware issue has been solved as of Django 1.5 and a [StreamingHttpResponse](https://docs.djangoproject.com/en/1.5/ref/request-response/#django.http.StreamingHttpResponse) has been introduced. The following should do:
```
import cStringIO as StringIO
import csv
def csv_view(request):
...
# Assume `rows... |
How can I access directory-local variables in my major mode hooks? | 5,147,060 | 7 | 2011-02-28T20:14:47Z | 5,148,435 | 11 | 2011-02-28T22:39:48Z | [
"python",
"emacs",
"python-mode",
"dot-emacs"
] | I have defined a .dir-locals.el file with the following content:
```
((python-mode . ((cr/virtualenv-name . "saas"))))
```
In my .emacs I have the following function to retrieve this value and provide a virtualenv path:
```
(defun cr/virtualenv ()
(cond (cr/virtualenv-name (format "%s/%s" virtualenv-base cr/virtua... | This happens because `normal-mode` calls `(set-auto-mode)` and `(hack-local-variables)` in that order.
However `hack-local-variables-hook` is run after the local variables have been processed, which enables some solutions:
1. The first is to make Emacs run a new "local variables hook" for each major mode:
```
... |
Matplotlib: How to put individual tags for a scatter plot | 5,147,112 | 141 | 2011-02-28T20:21:03Z | 5,147,430 | 233 | 2011-02-28T20:51:21Z | [
"python",
"matplotlib"
] | I am trying to do a scatter plot in matplotlib and I couldn't find a way to add tags to the points. For example:
```
scatter1=plt.scatter(data1["x"], data1["y"], marker="o",
c="blue",
facecolors="white",
edgecolors="blue")
```
I want for the points in "y"... | Perhaps use [plt.annotate](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.annotate):
```
import numpy as np
import matplotlib.pyplot as plt
N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
data[:, 0], data[:, 1], m... |
python: read json and loop dictionary | 5,147,292 | 7 | 2011-02-28T20:37:08Z | 5,147,382 | 18 | 2011-02-28T20:46:50Z | [
"python",
"json",
"loops",
"dictionary"
] | I'm learning python and i loop like this the json converted to dictionary: it works but is this the correct method? Thank you :)
```
import json
output_file = open('output.json').read()
output_json = json.loads(output_file)
for i in output_json:
print i
for k in output_json[i]:
print ... | That seems generally fine.
There's no need to first read the file, then use loads. You can just use load directly.
```
output_json = json.load(open('/tmp/output.json'))
```
Using i and k isn't correct for this. They should generally be used only for an integer loop counter. In this case they're keys, so something mo... |
Python Core Library and PEP8 | 5,148,707 | 5 | 2011-02-28T23:14:00Z | 5,149,398 | 9 | 2011-03-01T00:58:59Z | [
"python",
"pep8"
] | I was trying to understand why Python is said to be a beautiful language. I was directed to the beauty of PEP 8... and it was strange. In fact it says that you can use any convention you want, just be consistent... and suddenly I found some strange things in the core library:
```
request()
getresponse()
set_debuglevel... | PEP 8 recommends using underscores as the default choice, but leaving them out is generally done for one of two reasons:
* consistency with some other API (e.g. the current module, or a standard interface)
* because leaving them out doesn't hurt readability (or even improves it)
To address the specific examples you c... |
where are the .pyc files? | 5,149,832 | 9 | 2011-03-01T02:13:00Z | 5,149,853 | 14 | 2011-03-01T02:17:21Z | [
"python",
"bytecode"
] | I am a complete newb to python, hence a silly question.
As i understand, upon first execution of a \*.py program, byte code is created into \*.pyc and used until a change in \*.py file.
Where might this \*.pyc bytecode be found in a project?
I would think bin, but nothing is there | A \*.pyc file is created for imported modules, and they are placed in the same directory containing the .py file. However... no .pyc file is created for the main script for your program. In other words... if you call "python myscript.py" on the command line, there will be no .pyc file for myscript.py.
This is how Pyth... |
where are the .pyc files? | 5,149,832 | 9 | 2011-03-01T02:13:00Z | 5,149,973 | 11 | 2011-03-01T02:45:08Z | [
"python",
"bytecode"
] | I am a complete newb to python, hence a silly question.
As i understand, upon first execution of a \*.py program, byte code is created into \*.pyc and used until a change in \*.py file.
Where might this \*.pyc bytecode be found in a project?
I would think bin, but nothing is there | In Python < 3.2, the .pyc files are placed in the same directory as the .py file.
In Python 3.2, the compiled files are placed in a `__pycache__` subdirectory, and are named differently depending on which Python interpreter created them. (This can be useful to people importing the same Python modules from multiple ver... |
Using sqlite3 within Google App Engine? | 5,150,115 | 4 | 2011-03-01T03:14:02Z | 5,150,227 | 12 | 2011-03-01T03:39:16Z | [
"python",
"django",
"google-app-engine",
"sqlite"
] | I am trying to deploy my Python + Django project to the Google App Engine. Right now it works fine on my local computer, but when I try running it as a project within the Google App Engine, I get the following error.
```
ImproperlyConfigured: 'django.db.backends.sqlite3' isn't an available database backend.
Try using... | Google App Engine requires that you use its own datastore, rather than sqlite or another database. There is a project that will allow you to use pretty much regular Django models on App Engine called django-nonrel. You can find more information about setting it up here: <http://code.google.com/appengine/articles/django... |
how to install Matplotlib on Cygwin? | 5,151,755 | 8 | 2011-03-01T07:47:44Z | 9,013,184 | 13 | 2012-01-26T02:07:53Z | [
"python",
"cygwin",
"matplotlib"
] | I'm trying to install Matplotlib 1.0.1 version on latest Cygwin. In the processing, there is a weird fork error cannot be solved. I googled similar questions and found that it might be solved by manually running gcc/g++ with matplotlib 0.98.5.2 : <http://innuendopoly.org/arch/matplotlib-cygwin>. But it doesn't work und... | Here are instructions for how to install matplotlib 1.1.0 on Cygwin
<http://berlinbrowndev.blogspot.com/2012/01/python-matplotlib-plotting-setup-for.html>
# Python matplotlib plotting setup for cygwin
Matplotlib is a popular python library for generating plot graphics. It works with cygwin win32 but some non-intuiti... |
Django Admin Media prefix URL issue | 5,152,026 | 6 | 2011-03-01T08:29:20Z | 5,152,049 | 10 | 2011-03-01T08:33:53Z | [
"python",
"django",
"django-admin"
] | i 've the following folder structure
```
src\BAT\templates\admin\base.html
src\BAT\media\base.css
src\BAT\media\admin-media\base.css
```
settings.py
```
MEDIA_ROOT = os.path.join( APP_DIR, 'media' )
MEDIA_URL = '/media/'
ADMIN_MEDIA_PREFIX = '/admin-media/'
TEMPLATE_DIRS = (
os.path.join( APP_DIR, 'templates' )
... | Important for Django 1.4 and newer (see [here](https://docs.djangoproject.com/en/dev/releases/1.4/#django-contrib-admin)):
> Starting in Django 1.4, the adminâs static files also follow this convention, to make the files easier to deploy. In previous versions of Django, it was also common to define an ADMIN\_MEDIA\_... |
PyUSB backend not accessible | 5,152,133 | 5 | 2011-03-01T08:42:14Z | 5,943,530 | 11 | 2011-05-09T23:12:17Z | [
"python",
"pyusb"
] | hey i am trying to run the simple script available in the tutorial;. the usb is getting imported but when i try to search the device i get the following error,please help
```
>>> dev=usb.core.find()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\usb\core.... | You need to install libusb-1.0, libusb-0.1, or openusb as a backend to pyusb. Is this a Windows machine?
If so, you can download a simple installer here: <http://www.craftedge.com/products/libusb.html> |
django pagination and RawQuerySet | 5,152,984 | 8 | 2011-03-01T10:03:35Z | 5,465,549 | 16 | 2011-03-28T21:57:27Z | [
"python",
"django",
"django-pagination"
] | is there a way to paginate a rawqueryset using django's inbuilt pagination?
when i cast it to a list , it throws an error in my face ...TypeError: expected string or Unicode object, NoneType found. Is there a way around this? | I managed to achieve it using the following:
```
paginator = Paginator(files, 12)
paginator._count = len(list(files))
```
The code in django.core.paginator.py:
* checks for whether \_count is set
* if not then tries to run .count() which doesn't exist
* if not then tries plain len
len on a raw\_queryset doesn't wor... |
Python: How to do a system wide search for a file when just the filename (not path) is available | 5,153,317 | 6 | 2011-03-01T10:35:44Z | 5,153,364 | 12 | 2011-03-01T10:40:12Z | [
"python",
"search"
] | I'm still new to Python (using 2.6) and I am trying to do a system wide search for a file when just the filename is available and return the absolute path on windows. I've searched and found some modules like scriptutil.py and looked through the os module but haven't found anything that suits my needs (or I may not hav... | The os.walk() function is one way of doing it.
```
import os
from os.path import join
lookfor = "python.exe"
for root, dirs, files in os.walk('C:\\'):
print "searching", root
if lookfor in files:
print "found: %s" % join(root, lookfor)
break
``` |
Create Python class where the attributes is defined dynamically | 5,154,197 | 3 | 2011-03-01T11:57:27Z | 5,154,214 | 10 | 2011-03-01T11:59:30Z | [
"python",
"metaprogramming"
] | Sorry if this has been asked before. Is it possible to create class in Python dynamically where attributes is not defined in the `__init__` method of the class.
For example with this class
```
class Person(object):
def __init__(self):
...
```
I can dynamically put in the attributes during initialization like t... | The easiest way to do this is to assign the keyword argument dict to the `__dict__` attribute of the class:
```
class Person(object):
def __init__(self, **kw):
self.__dict__ = kw
person = Person(name='Joe')
print person.name
```
prints
```
Joe
```
To add attributes after object creation, use
```
def ad... |
Django - what is the difference between render(), render_to_response() and direct_to_template()? | 5,154,358 | 190 | 2011-03-01T12:13:50Z | 5,154,431 | 11 | 2011-03-01T12:20:11Z | [
"python",
"django"
] | Whats the difference (in language a python/django noob can understand) in a view between `render()`, `render_to_response()` and `direct_to_template()`?
e.g. from [Nathan Borror's basic apps examples](https://github.com/nathanborror/django-basic-apps)
```
def comment_edit(request, object_id, template_name='comments/ed... | From django [docs](https://docs.djangoproject.com/en/1.4/topics/http/shortcuts/#render):
> render() is the same as a call to
> render\_to\_response() with a
> context\_instance argument that that
> forces the use of a RequestContext.
`direct_to_template` is something different. It's a generic view that uses a data di... |
Django - what is the difference between render(), render_to_response() and direct_to_template()? | 5,154,358 | 190 | 2011-03-01T12:13:50Z | 5,154,458 | 155 | 2011-03-01T12:22:45Z | [
"python",
"django"
] | Whats the difference (in language a python/django noob can understand) in a view between `render()`, `render_to_response()` and `direct_to_template()`?
e.g. from [Nathan Borror's basic apps examples](https://github.com/nathanborror/django-basic-apps)
```
def comment_edit(request, object_id, template_name='comments/ed... | <https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render>
```
render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])
```
`render()` is a brand spanking new shortcut for `render_to_response` in 1.3 that will automatically use `RequestContext` that I will most d... |
Django - what is the difference between render(), render_to_response() and direct_to_template()? | 5,154,358 | 190 | 2011-03-01T12:13:50Z | 5,154,474 | 22 | 2011-03-01T12:24:47Z | [
"python",
"django"
] | Whats the difference (in language a python/django noob can understand) in a view between `render()`, `render_to_response()` and `direct_to_template()`?
e.g. from [Nathan Borror's basic apps examples](https://github.com/nathanborror/django-basic-apps)
```
def comment_edit(request, object_id, template_name='comments/ed... | Render is
```
def render(request, *args, **kwargs):
""" Simple wrapper for render_to_response. """
kwargs['context_instance'] = RequestContext(request)
return render_to_response(*args, **kwargs)
```
So there is really no difference between `render_to_response` except it wraps your context making the templ... |
Django - what is the difference between render(), render_to_response() and direct_to_template()? | 5,154,358 | 190 | 2011-03-01T12:13:50Z | 5,154,816 | 32 | 2011-03-01T12:59:39Z | [
"python",
"django"
] | Whats the difference (in language a python/django noob can understand) in a view between `render()`, `render_to_response()` and `direct_to_template()`?
e.g. from [Nathan Borror's basic apps examples](https://github.com/nathanborror/django-basic-apps)
```
def comment_edit(request, object_id, template_name='comments/ed... | Rephrasing Yuri, Fábio, and Frosts answers for the Django noob (i.e. me) - almost certainly a simplification, but a good starting point?
* `render_to_response()` is the "original", but requires you putting `context_instance=RequestContext(request)` in nearly all the time, a PITA.
* `direct_to_template()` is designed ... |
Using argparse to parse arguments of form "arg= val" | 5,154,716 | 8 | 2011-03-01T12:48:32Z | 11,762,020 | 14 | 2012-08-01T15:00:21Z | [
"python",
"parsing",
"command-line",
"argparse"
] | I want to use argparse to parse command lines of form "arg=val"
For example, the usage would be:
```
script.py conf_dir=/tmp/good_conf
```
To achieve it, I am doing this:
```
desc = "details"
parser = argparse.ArgumentParser(description=desc, add_help=False)
args = parser.add_argument("conf_dir")
args = parser.par... | You need a custom action
```
class StoreNameValuePair(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
n, v = values.split('=')
setattr(namespace, n, v)
args = parser.add_argument("conf_dir", action=StoreNameValuePair)
``` |
How to organize a Python Project? | 5,155,135 | 48 | 2011-03-01T13:28:57Z | 5,155,251 | 32 | 2011-03-01T13:40:27Z | [
"python",
"pydev",
"project-organization"
] | I'm new to Python and I'm starting a mini Project. but I have some doubts on how to organize the folders in the "Python Way".
I'm using PyDev in my Development Environment, and when I create a new project a folder is created called "src"
```
+ src
```
Now, in the PyDev I can create "Pydev Module" and "PyDev Package"... | A Package is basically a folder with `__init__.py` file under it and usually some Modules, where Module is a `*.py` file.
It has to do with `import` mainly. If you add `__init__.py` to Indicators you can use:
```
from Indicators.Stochastics import *
```
or
```
from Indicators import Stochastics
```
By the way, I wo... |
How to organize a Python Project? | 5,155,135 | 48 | 2011-03-01T13:28:57Z | 5,155,373 | 29 | 2011-03-01T13:49:35Z | [
"python",
"pydev",
"project-organization"
] | I'm new to Python and I'm starting a mini Project. but I have some doubts on how to organize the folders in the "Python Way".
I'm using PyDev in my Development Environment, and when I create a new project a folder is created called "src"
```
+ src
```
Now, in the PyDev I can create "Pydev Module" and "PyDev Package"... | From a file system perspective, a module is a file ending with `.py` and a package is a folder containing modules and (nested) packages again. Python recognizes a folder as a package if it contains a `__init__.py` file.
A file structure like that
```
some/
__init__.py
foofoo.py
thing/
__init__.py
... |
How to organize a Python Project? | 5,155,135 | 48 | 2011-03-01T13:28:57Z | 5,156,006 | 12 | 2011-03-01T14:43:49Z | [
"python",
"pydev",
"project-organization"
] | I'm new to Python and I'm starting a mini Project. but I have some doubts on how to organize the folders in the "Python Way".
I'm using PyDev in my Development Environment, and when I create a new project a folder is created called "src"
```
+ src
```
Now, in the PyDev I can create "Pydev Module" and "PyDev Package"... | You might want to check out the modern-package-template libary. It provides a way to setup a really nice basic layout for a project that walks you through a few questions and tries to help you get something that's able to be distributed fairly easily.
<http://pypi.python.org/pypi/modern-package-template> |
How to organize a Python Project? | 5,155,135 | 48 | 2011-03-01T13:28:57Z | 14,472,292 | 19 | 2013-01-23T04:06:57Z | [
"python",
"pydev",
"project-organization"
] | I'm new to Python and I'm starting a mini Project. but I have some doubts on how to organize the folders in the "Python Way".
I'm using PyDev in my Development Environment, and when I create a new project a folder is created called "src"
```
+ src
```
Now, in the PyDev I can create "Pydev Module" and "PyDev Package"... | See [python-package-template](https://github.com/vital-fadeev/python-package-template)
**Directory structure**
```
.
|-- bin
| `-- my_program
|-- docs
| `-- doc.txt
|-- my_program
| |-- data
| | `-- some_data.html
| |-- __init__.py
| |-- submodule
| | `-- ... |
create a dict of lists from a string | 5,155,434 | 4 | 2011-03-01T13:54:46Z | 5,155,534 | 13 | 2011-03-01T14:04:58Z | [
"python",
"list",
"dictionary",
"merge"
] | I want to convert a string such as 'a=b,a=c,a=d,b=e' into a dict of lists {'a': ['b', 'c', 'd'], 'b': ['e']} in Python 2.6.
My current solution is this:
```
def merge(d1, d2):
for k, v in d2.items():
if k in d1:
if type(d1[k]) != type(list()):
d1[k] = list(d1[k])
d1... | ```
d = {}
for i in 'a=b,a=c,a=d,b=e'.split(","):
k,v = i.split("=")
d.setdefault(k,[]).append(v)
print d
```
or, if you're using python > 2.4, you can use [defaultdict](http://docs.python.org/library/collections.html#defaultdict-examples)
```
from collections import defaultdict
d = defaultdict(list)
for i i... |
python creating tmp directory permissions | 5,156,268 | 2 | 2011-03-01T15:07:04Z | 5,156,335 | 8 | 2011-03-01T15:11:05Z | [
"python",
"linux"
] | I'm using a python script to create a copy of a linux filesystem. I'm having trouble with the permissions on the created /tmp directory. The /tmp directory should have 1777 permissions, i.e.:
```
ls -l /
drwxrwxrwt 17 root root 16384 2011-03-01 09:50 tmp
```
when I do the following,
```
os.mkdir('/mnt/tmp',1777... | You should provide the permissions as an octal number. In Python 2.x, simply use `01777` instead of `1777`. In Python 3.x, use `0o1777`. |
python homebrew by default | 5,157,678 | 87 | 2011-03-01T16:58:37Z | 5,157,738 | 9 | 2011-03-01T17:03:57Z | [
"python",
"homebrew"
] | I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with
```
brew install python
```
The problem is that, contrary to Macport, it seems that there is no python\_select utility, and my default mac python is always default
```
which python
```
give me
```
/usr/b... | You need to edit your PATH environmental variable to make sure wherever the homebrew python is located is searched before /usr/bin. You could also set things up in your shell config to have a variable like PYTHON be set to your desired version of python and call `$PYTHON` rather than `python` from the command line.
Al... |
python homebrew by default | 5,157,678 | 87 | 2011-03-01T16:58:37Z | 5,157,797 | 17 | 2011-03-01T17:08:50Z | [
"python",
"homebrew"
] | I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with
```
brew install python
```
The problem is that, contrary to Macport, it seems that there is no python\_select utility, and my default mac python is always default
```
which python
```
give me
```
/usr/b... | Homebrew does NOT replace stuff in "/usr/bin". You'll just want to put "/usr/local/bin" ahead of "/usr/bin" in your path, then "which python" will give you "/usr/local/bin/python".
Replacing /usr/bin/python (or /usr/bin/ruby) is highly unrecommended. |
python homebrew by default | 5,157,678 | 87 | 2011-03-01T16:58:37Z | 7,375,583 | 86 | 2011-09-11T00:37:01Z | [
"python",
"homebrew"
] | I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with
```
brew install python
```
The problem is that, contrary to Macport, it seems that there is no python\_select utility, and my default mac python is always default
```
which python
```
give me
```
/usr/b... | As you are using Homebrew the following command gives a better picture:
```
brew doctor
```
Output:
> ==> /usr/bin occurs before /usr/local/bin This means that system-provided programs will be used instead of those provided by
> Homebrew. This is an issue if you eg. brew installed Python.
>
> Consider editing your .... |
python homebrew by default | 5,157,678 | 87 | 2011-03-01T16:58:37Z | 9,821,036 | 51 | 2012-03-22T11:04:59Z | [
"python",
"homebrew"
] | I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with
```
brew install python
```
The problem is that, contrary to Macport, it seems that there is no python\_select utility, and my default mac python is always default
```
which python
```
give me
```
/usr/b... | Quick fix:
1. Open `/etc/paths`
2. Change the order of the lines (highest priority on top)
In my case `/etc/paths` looks like:
```
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin
```
If you want to know more about paths in OSX I found this article quite useful:
<http://muttsnutts.github.com/blog/2011/... |
python homebrew by default | 5,157,678 | 87 | 2011-03-01T16:58:37Z | 9,963,844 | 9 | 2012-04-01T10:59:15Z | [
"python",
"homebrew"
] | I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with
```
brew install python
```
The problem is that, contrary to Macport, it seems that there is no python\_select utility, and my default mac python is always default
```
which python
```
give me
```
/usr/b... | Modify your $PATH, Add this in your bashrc or bash\_profile:
```
export PATH=/usr/local/bin:/usr/local/sbin:~/bin:$PATH
```
more click here:
[Issue #89791](https://github.com/mxcl/homebrew/issues/8791) |
python homebrew by default | 5,157,678 | 87 | 2011-03-01T16:58:37Z | 14,645,426 | 42 | 2013-02-01T11:35:24Z | [
"python",
"homebrew"
] | I try to switch to Homebrew (after using fink and macport) on Mac OS X 10.6.2. I have installed python 2.7 with
```
brew install python
```
The problem is that, contrary to Macport, it seems that there is no python\_select utility, and my default mac python is always default
```
which python
```
give me
```
/usr/b... | See: [How to symlink python in Homebrew?](http://stackoverflow.com/questions/13354207/how-to-symlink-python-in-homebrew)
```
$ brew link --overwrite python
Linking /usr/local/Cellar/python/2.7.3... 28 symlinks created
$ which python
/usr/local/bin/python
``` |
Python: get datetime for '3 years ago today'? | 5,158,160 | 17 | 2011-03-01T17:37:06Z | 5,158,253 | 15 | 2011-03-01T17:45:30Z | [
"python"
] | This must be a duplicate (and documented), but I can't find the answer via Google.
In Python, how do I get a datetime object for '3 years ago today'?
Thanks!
UPDATE: FWIW, I don't care hugely about accuracy... i.e. it's Feb 29th today, I don't care whether I'm given Feb 28th or March 1st in my answer. Concision is m... | ```
import datetime
datetime.datetime.now() - datetime.timedelta(days=3*365)
``` |
Python: get datetime for '3 years ago today'? | 5,158,160 | 17 | 2011-03-01T17:37:06Z | 5,158,430 | 12 | 2011-03-01T18:00:46Z | [
"python"
] | This must be a duplicate (and documented), but I can't find the answer via Google.
In Python, how do I get a datetime object for '3 years ago today'?
Thanks!
UPDATE: FWIW, I don't care hugely about accuracy... i.e. it's Feb 29th today, I don't care whether I'm given Feb 28th or March 1st in my answer. Concision is m... | Subtracting 365\*3 days is wrong, of course--you're crossing a leap year more than half the time.
```
dt = datetime.now()
dt = dt.replace(year=dt.year-3)
# datetime.datetime(2008, 3, 1, 13, 2, 36, 274276)
```
ED: To get the leap-year issue right,
```
def subtract_years(dt, years):
try:
dt = dt.replace(ye... |
Python: get datetime for '3 years ago today'? | 5,158,160 | 17 | 2011-03-01T17:37:06Z | 5,159,103 | 41 | 2011-03-01T19:05:23Z | [
"python"
] | This must be a duplicate (and documented), but I can't find the answer via Google.
In Python, how do I get a datetime object for '3 years ago today'?
Thanks!
UPDATE: FWIW, I don't care hugely about accuracy... i.e. it's Feb 29th today, I don't care whether I'm given Feb 28th or March 1st in my answer. Concision is m... | If you need to be exact use the [dateutil](https://pypi.python.org/pypi/python-dateutil/2.1) module to calculate relative dates
```
from datetime import datetime
from dateutil.relativedelta import relativedelta
three_yrs_ago = datetime.now() - relativedelta(years=3)
``` |
Why does Python's urlparse.parse_qs() split arguments on semicolon | 5,158,565 | 6 | 2011-03-01T18:14:13Z | 5,159,027 | 13 | 2011-03-01T18:58:52Z | [
"python",
"http",
"get",
"query-string"
] | I'm writing a test script in Python to check the output of my PHP application and I've got a problem with Python's `urlparse.parse_qs()` function. GET string delimiter (AFAIK) is an ampersand. The function (as I understand) is supposed to split a GET string into Python dictionary, so that the output for `count=2&offset... | [';' is equivalent to '&'](http://en.wikipedia.org/wiki/Query_string#Structure)
[W3C recommends that all web servers support semicolon separators in the place of ampersand separators.](http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2.2)
So use ',' instead. |
is it possible to release the GIL before a C function that blocks and might call back into Python? | 5,159,040 | 3 | 2011-03-01T18:59:45Z | 5,159,313 | 7 | 2011-03-01T19:26:26Z | [
"python",
"gil",
"python-multithreading",
"python-bindings"
] | I am wrapping a C function which performs a blocking operation (select) and then handles incoming messages. My understanding is that when a C function is going to block, the correct way to call it while allowing other threads to run is:
```
Py_BEGIN_ALLOW_THREADS
block... | I used these API functions several months ago, and my recollection is a bit hazy, but I believe this code will solve your problem. I am assuming version 2.x (3.x may be different):
```
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
/* Make your call to PyEval_CallObject() here (and any other PY API calls). */... |
Need to add space between SubPlots for X axis label, maybe remove labelling of axis notches | 5,159,065 | 25 | 2011-03-01T19:01:51Z | 5,159,405 | 51 | 2011-03-01T19:36:02Z | [
"python",
"matplotlib"
] | Looking to add in vertical space between plotted graphs to allow a X-Axis label to show:
Each graph needs to have space to show the day, currently the last 2 graphs are the only one's that show simply because the graphs are overlapping it.
Also curious if I could actually remove the notch labels for the X-Axis for th... | Use [subplots\_adjust](http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure.subplots_adjust). In your case this looks good:
```
fig.subplots_adjust(hspace=.5)
```
to remove the tick labels do this:
```
ax1.set_xticklabels([])
```
Similar for the `yticklabels`. However, you cannot share the... |
How can I filter or limit the text being entered in a PyGTK text entry field? | 5,159,219 | 2 | 2011-03-01T19:17:08Z | 5,159,275 | 7 | 2011-03-01T19:22:56Z | [
"python",
"pygtk"
] | I want a text entry field (gtk.Entry) that accepts only hexadecimal characters as valid input from the user. | Filtering may be done by connecting to the 'insert\_text' signal and manipulating the entered text in the signal handler.
Here is example code for validating Hex characters:
```
#!/usr/bin/env python
import gtk, pygtk, gobject, string
class HexEntry(gtk.Entry):
"""A PyGTK text entry field which allows only Hex... |
Encoding nested python object in JSON | 5,160,077 | 19 | 2011-03-01T20:40:19Z | 5,160,278 | 15 | 2011-03-01T21:00:31Z | [
"python",
"json",
"encode"
] | I want to encode objects in JSON. But, I can not figure out how to make the output without the string escaping.
```
import json
class Abc:
def __init__(self):
self.name="abc name"
def toJSON(self):
return json.dumps(self.__dict__, cls=ComplexEncoder)
class Doc:
def __init__(self):
... | So, the immediate problem is that you're passing the json module a JSON value, which will get encoded as just another string in the JSON value.
The broader problem is that you're greatly overcomplicating this.
Drawing on [JSON datetime between Python and JavaScript](http://stackoverflow.com/questions/455580/json-date... |
Encoding nested python object in JSON | 5,160,077 | 19 | 2011-03-01T20:40:19Z | 5,165,421 | 22 | 2011-03-02T09:14:07Z | [
"python",
"json",
"encode"
] | I want to encode objects in JSON. But, I can not figure out how to make the output without the string escaping.
```
import json
class Abc:
def __init__(self):
self.name="abc name"
def toJSON(self):
return json.dumps(self.__dict__, cls=ComplexEncoder)
class Doc:
def __init__(self):
... | my previous sample, with another nested object and your advices :
```
import json
class Identity:
def __init__(self):
self.name="abc name"
self.first="abc first"
self.addr=Addr()
def reprJSON(self):
return dict(name=self.name, firstname=self.first, address=self.addr)
class Ad... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.