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
Print PDF document with python's win32print module?
1,462,842
2
2009-09-22T21:52:15Z
1,464,974
8
2009-09-23T09:37:55Z
[ "python", "windows", "pdf", "winapi", "postscript" ]
I'm trying to print a PDF document with the win32print module. Apparently this module can only accept PCL or raw text. Is that correct? If so, is there a module available to convert a PDF document into PCL? I contemplated using ShellExecute; however, this is not an option since it only allows printing to the default ...
I ended up using [Ghostscript](http://pages.cs.wisc.edu/~ghost/ "Ghostscript") to accomplish this task. There is a command line tool that relies on Ghostscript called [gsprint](http://pages.cs.wisc.edu/~ghost/gsview/gsprint.htm "gsprint"). You don't even need Acrobat installed to print PDFs in this fashion which is qu...
Lazy module variables--can it be done?
1,462,986
22
2009-09-22T22:32:05Z
1,463,773
39
2009-09-23T03:09:28Z
[ "python", "module", "variables", "lazy-loading", "itunes" ]
I'm trying to find a way to lazily load a module-level variable. Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a `DOWNLOAD_FOLDER_PATH` module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a fe...
You can't do it with modules, but you can disguise a class "as if" it was a module, e.g., in `itun.py`, code...: ``` import sys class _Sneaky(object): def __init__(self): self.download = None @property def DOWNLOAD_PATH(self): if not self.download: self.download = heavyComputations() return s...
Lazy module variables--can it be done?
1,462,986
22
2009-09-22T22:32:05Z
14,345,798
9
2013-01-15T19:57:57Z
[ "python", "module", "variables", "lazy-loading", "itunes" ]
I'm trying to find a way to lazily load a module-level variable. Specifically, I've written a tiny Python library to talk to iTunes, and I want to have a `DOWNLOAD_FOLDER_PATH` module variable. Unfortunately, iTunes won't tell you where its download folder is, so I've written a function that grabs the filepath of a fe...
I used Alex' implementation on Python 3.3, but this crashes miserably: The code ``` def __getattr__(self, name): return globals()[name] ``` is not correct because an `AttributeError` should be raised, not a `KeyError`. This crashed immediately under Python 3.3, because a lot of introspection is done during the ...
How can I get an email message's text content using python?
1,463,074
19
2009-09-22T22:56:24Z
1,463,144
51
2009-09-22T23:17:31Z
[ "python", "email", "mime", "rfc822" ]
Given an RFC822 message in Python 2.6, how can I get the *right* text/plain content part? Basically, the algorithm I want is this: ``` message = email.message_from_string(raw_message) if has_mime_part(message, "text/plain"): mime_part = get_mime_part(message, "text/plain") text_content = decode_mime_part(mime_...
In a multipart e-mail, `email.message.Message.get_payload()` returns a list with one item for each part. The easiest way is to walk the message and get the payload on each part: ``` import email msg = email.message_from_string(raw_message) for part in msg.walk(): # each part is a either non-multipart, or another m...
django - using a common header with some dynamic elements
1,463,153
3
2009-09-22T23:20:04Z
1,463,395
9
2009-09-23T00:47:22Z
[ "javascript", "python", "django" ]
I'm planning to create a website using django that will have a common header throughout the entire website. I've read django's documentation on templating inheritance, but I can't seem to find an elegant solution for the "dynamic" elements in my header. For example, the header in the website will include tabs, say sim...
I'm assuming each tab is a list item in your template `base.html`. ``` <ul> <li>Tab 1</li> <li>Tab 2</li> ... </ul> ``` Add an extra block to each `li`. ``` <ul> <li class="{% block class_tab1 %}inactive{% endblock %}">Tab 1</li> <li class="{% block class_tab2 %}inactive{% endblock %}">Tab 2</li>...
How does exec work with locals?
1,463,306
10
2009-09-23T00:18:47Z
1,463,370
18
2009-09-23T00:37:27Z
[ "python", "python-3.x", "exec", "locals" ]
I thought this would print 3, but it prints 1: ``` def f(): a = 1 exec("a = 3") print(a) ```
This issue is somewhat discussed in the [Python3 bug list](http://bugs.python.org/issue4831). Ultimately, to get this behavior, you need to do: ``` def foo(): ldict = locals() exec("a=3",globals(),ldict) a = ldict['a'] print(a) ``` And if you check [the Python3 documentation on `exec`](http://docs.pyt...
Django: how to including inline model fields in the list_display?
1,463,398
3
2009-09-23T00:48:30Z
1,464,624
7
2009-09-23T08:09:18Z
[ "python", "django", "django-models", "django-admin" ]
I'm attempting to extend django's contrib.auth User model, using an inline 'Profile' model to include extra fields. ``` from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin class Profile(models.Model): user = models.ForeignKey(User, unique=Tru...
You've mentioned the only solution - creating a callable. There's currently no other way to do it, and yes this does mean you can't sort by that column.
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
24
2009-09-23T01:19:17Z
1,463,857
7
2009-09-23T03:51:39Z
[ "python", "django", "http", "redirect" ]
I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning ``` HttpResponseRedirect(request.path) ``` which works fine. However, I'd also like to display some messages to the user in this case (e.g...
if you are using auth and have a logged in user you could: <http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.message_set.create> GET params are also hackable. Teh querystring, as mentioned in other answers. I think that the most choice way would be to use the sessions framework. That...
How do I pass template context information when using HttpResponseRedirect in Django?
1,463,489
24
2009-09-23T01:19:17Z
11,594,329
34
2012-07-21T17:25:09Z
[ "python", "django", "http", "redirect" ]
I have a form that redirects to the same page after a user enters information (so that they can continue entering information). If the form submission is successful, I'm returning ``` HttpResponseRedirect(request.path) ``` which works fine. However, I'd also like to display some messages to the user in this case (e.g...
For the sake of completion and future reference, you can now use [the messages framework](https://docs.djangoproject.com/en/dev/ref/contrib/messages/). After you install it: **views.py** ``` from django.contrib import messages def view(request): # your code messages.success(request, "Your data has been saved!") ...
Deploying CherryPy (daemon)
1,463,510
21
2009-09-23T01:27:13Z
1,463,562
13
2009-09-23T01:44:58Z
[ "python", "deployment", "cherrypy" ]
I've followed the basic CherryPy tutorial (<http://www.cherrypy.org/wiki/CherryPyTutorial>). One thing not discussed is deployment. How can I launch a CherryPy app as a daemon and "forget about it"? What happens if the server reboots? Is there a standard recipe? Maybe something that will create a service script (/etc...
There is a [Daemonizer](http://docs.cherrypy.org/stable/refman/process/plugins/daemonizer.html) plugin for CherryPy included by default which is useful for getting it to start but by far the easiest way for simple cases is to use the cherryd script: ``` > cherryd -h Usage: cherryd [options] Options: -h, --help ...
Deploying CherryPy (daemon)
1,463,510
21
2009-09-23T01:27:13Z
5,353,332
10
2011-03-18T14:22:32Z
[ "python", "deployment", "cherrypy" ]
I've followed the basic CherryPy tutorial (<http://www.cherrypy.org/wiki/CherryPyTutorial>). One thing not discussed is deployment. How can I launch a CherryPy app as a daemon and "forget about it"? What happens if the server reboots? Is there a standard recipe? Maybe something that will create a service script (/etc...
Daemonizer can be pretty simple to use: ``` # this works for cherrypy 3.1.2 on Ubuntu 10.04 from cherrypy.process.plugins import Daemonizer # before mounting anything Daemonizer(cherrypy.engine).subscribe() cherrypy.tree.mount(MyDaemonApp, "/") cherrypy.engine.start() cherrypy.engine.block() ``` [There is a decent H...
How can this python function code work?
1,463,588
6
2009-09-23T01:51:28Z
1,463,706
8
2009-09-23T02:41:30Z
[ "python", "function", "matplotlib" ]
this is from the source code of csv2rec in matplotlib how can this function work, if its only parameters are 'func, default'? ``` def with_default_value(func, default): def newfunc(name, val): if ismissing(name, val): return default else: return func(val) return newfunc...
This `with_default_value` function is what's often referred to (imprecisely) as "a closure" (technically, the closure is rather the *inner* function that gets returned, here `newfunc` -- see e.g. [here](http://en.wikipedia.org/wiki/Closure%5F%28computer%5Fscience%29)). More generically, `with_default_value` is a *highe...
What is the pythonic way of checking if an object is a list?
1,464,028
10
2009-09-23T04:54:10Z
1,464,049
11
2009-09-23T05:00:23Z
[ "python", "list" ]
I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0] Edit: I seem to have started a war of words down below by not giving enough info. For completeness let me ...
You don't. *This works only for Python >= 2.6. If you're targeting anything below use [Alex' solution](http://stackoverflow.com/questions/1464028/what-is-the-pythonic-way-of-checking-if-an-object-is-a-list/).* Python supports something called [Duck Typing](http://docs.python.org/glossary.html#term-duck-typing "If it ...
What is the pythonic way of checking if an object is a list?
1,464,028
10
2009-09-23T04:54:10Z
1,464,050
13
2009-09-23T05:00:29Z
[ "python", "list" ]
I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0] Edit: I seem to have started a war of words down below by not giving enough info. For completeness let me ...
``` if isinstance(your_object, list): print("your object is a list!") ``` This is more Pythonic than checking with type. Seems faster too: ``` >>> timeit('isinstance(x, list)', 'x = [1, 2, 3, 4]') 0.40161490440368652 >>> timeit('type(x) is list', 'x = [1, 2, 3, 4]') 0.46065497398376465 >>> ```
What is the pythonic way of checking if an object is a list?
1,464,028
10
2009-09-23T04:54:10Z
1,464,089
21
2009-09-23T05:17:53Z
[ "python", "list" ]
I have a function that may take in a number or a list of numbers. Whats the most pythonic way of checking which it is? So far I've come up with try/except block checking if i can slice the zero item ie. obj[0:0] Edit: I seem to have started a war of words down below by not giving enough info. For completeness let me ...
In such situations, you normally need to check for ANY iterable, not just lists -- if you're accepting lists OR numbers, rejecting (e.g) a tuple would be weird. The one kind of iterable you might want to treat as a "scalar" is a string -- in Python 2.\*, this means `str` or `unicode`. So, either: ``` def isNonStringIt...
Pyqt - QMenu dynamically populated and clicked
1,464,548
3
2009-09-23T07:53:24Z
1,464,589
9
2009-09-23T08:01:51Z
[ "python", "user-interface", "qt", "pyqt" ]
I need to be able to know what item I've clicked in a dynamically generated menu system. I only want to know what I've clicked on, even if it's simply a string representation. ``` def populateShotInfoMenus(self): self.menuFilms = QMenu() films = self.getList() for film in films: menuItem_Film = se...
Instead of using `onFilmSet` directly as the receiver of your connection, use a lambda function so you can pass additional parameters: ``` receiver = lambda film=film: self.onFilmSet(self, film) self.connect(menuItem_Film, SIGNAL('triggered()'), receiver) ```
internal server error (500) in simple cgi script
1,464,728
7
2009-09-23T08:33:52Z
1,464,762
18
2009-09-23T08:44:12Z
[ "python", "apache", "cgi" ]
I am trying to run a simple cgi script after configuring my server. My script looks like this: ``` print "Content-type: text/html" print print "<html><head><title>CGI</title></head>" print "<body>" print "hello cgi" print "</body>" print "</html>" ``` When I go to my scripts url `http://127.0.0.1/~flybywire/cgi-bin/...
You might need a `#!/usr/bin/python` at the top of your script to tell Apache to use Python to execute it. At least, I did that and it worked for me :-) .
internal server error (500) in simple cgi script
1,464,728
7
2009-09-23T08:33:52Z
1,464,804
8
2009-09-23T08:53:14Z
[ "python", "apache", "cgi" ]
I am trying to run a simple cgi script after configuring my server. My script looks like this: ``` print "Content-type: text/html" print print "<html><head><title>CGI</title></head>" print "<body>" print "hello cgi" print "</body>" print "</html>" ``` When I go to my scripts url `http://127.0.0.1/~flybywire/cgi-bin/...
Also, save the file (if this is a Linux server) with Unix line endings. You did make it executable using `chmod +x` didn't you? You can use `#!/usr/bin/env python` to cover the current running Python version if you're running in various environments (hence the `env` part).
How can I print only every third index in Perl or Python?
1,464,923
5
2009-09-23T09:27:09Z
1,464,942
7
2009-09-23T09:30:57Z
[ "python", "arrays", "perl" ]
How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.
Python: ``` for x in a[::3]: something(x) ```
How can I print only every third index in Perl or Python?
1,464,923
5
2009-09-23T09:27:09Z
1,464,951
11
2009-09-23T09:33:15Z
[ "python", "arrays", "perl" ]
How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.
Python ``` print list[::3] # print it newlist = list[::3] # copy it ``` Perl ``` for ($i = 0; $i < @list; $i += 3) { print $list[$i]; # print it push @y, $list[$i]; # copy it } ```
How can I print only every third index in Perl or Python?
1,464,923
5
2009-09-23T09:27:09Z
1,465,560
8
2009-09-23T12:01:48Z
[ "python", "arrays", "perl" ]
How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.
Perl 5.10 new [state](http://perldoc.perl.org/functions/state.html) variables comes in very handy here: ``` my @every_third = grep { state $n = 0; ++$n % 3 == 0 } @list; ``` Also note you can provide a list of elements to slice: ``` my @every_third = @list[ 2, 5, 8 ]; # returns 3rd, 5th & 9th items in list ``` You...
How can I print only every third index in Perl or Python?
1,464,923
5
2009-09-23T09:27:09Z
1,465,724
15
2009-09-23T12:39:48Z
[ "python", "arrays", "perl" ]
How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.
**Perl:** As with draegtun's answer, but using a count var: ``` my $i; my @new = grep {not ++$i % 3} @list; ```
How can I print only every third index in Perl or Python?
1,464,923
5
2009-09-23T09:27:09Z
1,466,696
7
2009-09-23T15:22:02Z
[ "python", "arrays", "perl" ]
How can I do a for() or foreach() loop in Python and Perl, respectively, that only prints every third index? I need to move every third index to a new array.
Perl: ``` # The initial array my @a = (1..100); # Copy it, every 3rd elements my @b = @a[ map { 3 * $_ } 0..$#a/3 ]; # Print it. space-delimited $, = " "; say @b; ```
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
13
2009-09-23T09:34:45Z
2,417,977
13
2010-03-10T15:13:01Z
[ "python", "amazon-s3", "boto" ]
I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).
Where bucket is the destination bucket: ``` bucket.copy_key(new_key,source_bucket,source_key) ```
How to clone a key in Amazon S3 using Python (and boto)?
1,464,961
13
2009-09-23T09:34:45Z
21,517,001
9
2014-02-02T22:18:26Z
[ "python", "amazon-s3", "boto" ]
I have a file contained in a key in my S3 bucket. I want to create a new key, which will contain the same file. Is it possible to do without downloading that file? I'm looking for a solution in Python (and preferably boto library).
``` from boto.s3.key import Key #Get source key from bucket by name source_key = source_bucket.get_key(source_key_name) #Copy source key to a new bucket with a new key name (can be the same as source) #Note: source_key is Key source_key.copy(dest_bucket_name,dest_key_name) #The signature of boto's Key class: def cop...
Install python 2.6 in CentOS
1,465,036
81
2009-09-23T09:53:04Z
1,465,105
23
2009-09-23T10:08:08Z
[ "python", "centos", "rpath" ]
I have a shell that runs CentOS. For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4. From what I've read, a number of things will break if you upgrade to 2.5. I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred ...
No, that's it. You might want to make sure you have all optional library headers installed too so you don't have to recompile it later. They are listed in the documentation I think. Also, you can install it even in the standard path if you do `make altinstall`. That way it won't override your current default "python".
Install python 2.6 in CentOS
1,465,036
81
2009-09-23T09:53:04Z
1,498,060
12
2009-09-30T13:18:24Z
[ "python", "centos", "rpath" ]
I have a shell that runs CentOS. For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4. From what I've read, a number of things will break if you upgrade to 2.5. I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred ...
[Chris Lea](http://chrislea.com/2009/09/09/easy-python-2-6-django-on-centos-5/) provides a YUM repository for python26 RPMs that can co-exist with the 'native' 2.4 that is needed for quite a few admin tools on CentOS. Quick instructions that worked at least for me: ``` $ sudo rpm -Uvh http://yum.chrislea.com/centos/5...
Install python 2.6 in CentOS
1,465,036
81
2009-09-23T09:53:04Z
1,580,510
28
2009-10-16T21:24:22Z
[ "python", "centos", "rpath" ]
I have a shell that runs CentOS. For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4. From what I've read, a number of things will break if you upgrade to 2.5. I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred ...
When I've run into similar situations, I generally avoid the package manager, especially if it would be embarrassing to break something, i.e. a production server. Instead, I would go to Activestate and download their binary package: <https://www.activestate.com/activepython/downloads/> This is installed by running a ...
Install python 2.6 in CentOS
1,465,036
81
2009-09-23T09:53:04Z
4,122,184
75
2010-11-08T08:13:04Z
[ "python", "centos", "rpath" ]
I have a shell that runs CentOS. For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4. From what I've read, a number of things will break if you upgrade to 2.5. I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred ...
You could also use the [EPEL-repository](http://fedoraproject.org/wiki/EPEL), and then do `sudo yum install python26` to install python 2.6
Install python 2.6 in CentOS
1,465,036
81
2009-09-23T09:53:04Z
5,001,536
21
2011-02-15T08:58:21Z
[ "python", "centos", "rpath" ]
I have a shell that runs CentOS. For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4. From what I've read, a number of things will break if you upgrade to 2.5. I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred ...
No need to do yum or make your own RPM. Build `python26` from source. ``` wget https://www.python.org/ftp/python/2.6.6/Python-2.6.6.tgz tar -zxvf Python-2.6.6.tgz cd Python-2.6.6 ./configure && make && make install ``` There can be a **dependency error** use ``` yum install gcc cc ``` Add the install path (`/usr/lo...
Install python 2.6 in CentOS
1,465,036
81
2009-09-23T09:53:04Z
8,352,224
29
2011-12-02T05:43:45Z
[ "python", "centos", "rpath" ]
I have a shell that runs CentOS. For a project I'm doing, I need python 2.5+, but centOS is pretty dependent on 2.4. From what I've read, a number of things will break if you upgrade to 2.5. I want to install 2.5 separately from 2.4, but I'm not sure how to do it. So far I've downloaded the source tarball, untarred ...
Try epel ``` wget http://download.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm sudo rpm -ivh epel-release-5-4.noarch.rpm sudo yum install python26 ``` The python executable will be available at `/usr/bin/python26` ``` mkdir -p ~/bin ln -s /usr/bin/python26 ~/bin/python export PATH=~/bin:$PATH # Appe...
How do you determine a processing time in Python?
1,465,146
22
2009-09-23T10:19:55Z
1,465,167
38
2009-09-23T10:24:28Z
[ "python", "datetime" ]
I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation. In java, I would write: ``` long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; ``` I'm sure it's...
Equivalent in python would be: ``` >>> import time >>> tic = time.clock() >>> toc = time.clock() >>> toc - tic ``` It's not clear what are you trying to do that for? Are you trying to find the best performing method? Then you should prob have a look at [`timeit`](http://docs.python.org/library/timeit.html).
How do you determine a processing time in Python?
1,465,146
22
2009-09-23T10:19:55Z
1,465,170
7
2009-09-23T10:24:47Z
[ "python", "datetime" ]
I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation. In java, I would write: ``` long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; ``` I'm sure it's...
Use timeit. <http://docs.python.org/library/timeit.html>
How do you determine a processing time in Python?
1,465,146
22
2009-09-23T10:19:55Z
14,739,514
16
2013-02-06T21:51:25Z
[ "python", "datetime" ]
I'm new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation. In java, I would write: ``` long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore; ``` I'm sure it's...
Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use `timeit`'s `default_timer()`: ``` >>> import timeit >>> tic=timeit.default_timer() >>> # Do Stuff >>> toc=timeit.default_timer() >>> toc - tic #elapsed time in seconds ``` This will return ...
vim syntax highlighting for jinja2?
1,465,240
8
2009-09-23T10:42:29Z
1,465,251
11
2009-09-23T10:45:00Z
[ "python", "vim", "jinja2", "vim-syntax-highlighting" ]
How do you do jinja2 aware syntax highlighting for vim?
There appears to be a syntax highlighting file [here](http://www.vim.org/scripts/script.php?script%5Fid=1856).
jinja2: get lengths of list
1,465,249
112
2009-09-23T10:44:54Z
1,466,550
187
2009-09-23T14:55:54Z
[ "python", "jinja2" ]
How do I get the number of elements in a list in jinja2 template. For example, in python: ``` print template.render(products=[???]) ``` and in jinja2 ``` <span>You have {{what goes here?}} products</span> ```
``` <span>You have {{products|length}} products</span> ``` You can also use this syntax in expressions like ``` {% if products|length > 1 %} ``` jinja2's builtin filters are documented [here](http://jinja.pocoo.org/docs/templates/#builtin-filters); and specifically, as you've already found, [`length`](http://jinja.p...
What is involved in adding to the standard Python API?
1,465,302
4
2009-09-23T10:56:39Z
1,465,322
9
2009-09-23T11:02:56Z
[ "python", "api" ]
What steps would be necessary, and what kind of maintenance would be expected if I wanted to contribute a module to the Python standard API? For example I have a module that encapsulates automated update functionality similar to Java's JNLP.
Please look at [Python PEP 2](http://www.python.org/dev/peps/pep-0002/) for details. You'll surely find more necessary information at the [PEP Index](http://www.python.org/dev/peps/), such as [PEP 1: PEP Purpose and Guidelines](http://www.python.org/dev/peps/pep-0001/). Have a look through the PEP index for previous P...
How can I implement decrease-key functionality in Python's heapq?
1,465,662
24
2009-09-23T12:23:52Z
1,466,444
23
2009-09-23T14:41:15Z
[ "python", "heap" ]
I know it is possible to realize decrease-key functionality in O(log n) but I don't know how?
To implement "decrease-key" effectively, you'd need to access the functionality "decrement this element AND swap this element with a child until heap condition is restore". In [heapq.py](http://hg.python.org/cpython/file/2.7/Lib/heapq.py#l242), that's called `_siftdown` (and similarly `_siftup` for INcrementing). So th...
Limiting results returned fromquery in django, python
1,465,734
3
2009-09-23T12:42:20Z
1,465,750
8
2009-09-23T12:45:43Z
[ "python", "django" ]
I've just started to learn how to do queries in my Django application, and I have a query that gets me the list of new users filtered by the date joined: ``` newUsers = User.objects.filter(is_active=True).order_by("-date_joined") ``` This as I understand it gives me ALL the users, sorted by date joined. How would I b...
``` User.objects.filter(is_active=True).order_by("-date_joined")[:10] ``` will give you the last 10 users who joined. See [the Django docs](http://docs.djangoproject.com/en/dev/topics/db/queries/#id4) for details.
Install mysqldb on snow leopard
1,465,846
7
2009-09-23T13:01:50Z
6,537,345
7
2011-06-30T15:37:18Z
[ "python", "mysql", "django", "osx-snow-leopard" ]
I am trying to get started on working with Python on Django I am by profession a PHP developer and have been told to set up django and python on my current apache and mysql setup however I am having trouble getting the Mysqldb module for python to work, I must of followed about 6 different set of instructions, I am run...
On MAC OS X 10.6, Install the package as usual. The dynamic import error occurs because of wrong DYLD path. Export the path and open up a python terminal. $ sudo python setup.py clean $ sudo python setup.py build $ sudo python setup.py install $ **export DYLD\_LIBRARY\_PATH=/usr/local/mysql/lib:$DYLD\_LIBRARY\_PATH...
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
224
2009-09-23T13:27:36Z
1,466,036
302
2009-09-23T13:33:20Z
[ "python" ]
In the python built-in [open](http://docs.python.org/library/functions.html#open) function, what is the exact difference between the modes w, a, w+, a+, and r+? In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "u...
The opening modes are exactly the same that C **`fopen()`** std library function. [The BSD `fopen` manpage](http://www.manpagez.com/man/3/fopen/) defines them as follows: ``` The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.): ``r...
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
224
2009-09-23T13:27:36Z
1,466,037
34
2009-09-23T13:33:37Z
[ "python" ]
In the python built-in [open](http://docs.python.org/library/functions.html#open) function, what is the exact difference between the modes w, a, w+, a+, and r+? In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "u...
The options are the same as for the [fopen function](http://www.manpagez.com/man/3/fopen/) in the C standard library: `w` truncates the file, overwriting whatever was already there `a` appends to the file, adding onto whatever was already there `w+` opens for reading and writing, truncating the file but also allowin...
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
224
2009-09-23T13:27:36Z
30,566,011
119
2015-06-01T05:13:40Z
[ "python" ]
In the python built-in [open](http://docs.python.org/library/functions.html#open) function, what is the exact difference between the modes w, a, w+, a+, and r+? In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "u...
I noticed that every now and then I need to Google fopen all over again, just to build a mental image of what the primary differences between the modes are. So, I thought a diagram will be faster to read next time. Maybe someone else will find that helpful too. ![](http://i.stack.imgur.com/ExWNT.png)
python open built-in function: difference between modes a, a+, w, w+, and r+?
1,466,000
224
2009-09-23T13:27:36Z
30,931,305
40
2015-06-19T06:26:02Z
[ "python" ]
In the python built-in [open](http://docs.python.org/library/functions.html#open) function, what is the exact difference between the modes w, a, w+, a+, and r+? In particular, the documentation implies that all of these will allow writing to the file, and says that it opens the files for "appending", "writing", and "u...
Same info, just in table form ``` | r r+ w w+ a a+ ------------------|-------------------------- read | + + + + write | + + + + + create | + + + + truncate | + + position at start | + + ...
Python gzip folder structure when zipping single file
1,466,287
4
2009-09-23T14:18:58Z
1,466,443
10
2009-09-23T14:41:12Z
[ "python", "gzip", "folders" ]
I'm using Python's gzip module to gzip content for a single file, using code similar to the example in the docs: ``` import gzip content = "Lots of content here" f = gzip.open('/home/joe/file.txt.gz', 'wb') f.write(content) f.close() ``` If I open the gz file in 7-zip, I see a folder hierarchy matching the path I wro...
It looks like you will have to use `GzipFile` directly: ``` import gzip content = "Lots of content here" real_f = open('/home/joe/file.txt.gz', 'wb') f = gzip.GZipFile('file.txt.gz', fileobj = realf) f.write(content) f.close() real_f.close() ``` It looks like `open` doesn't allow you to specify the fileobj separate f...
Create a wrapper class to call a pre and post function around existing functions?
1,466,676
6
2009-09-23T15:19:05Z
1,467,296
12
2009-09-23T16:52:33Z
[ "python" ]
I want to create a class that wraps another class so that when a function is run through the wrapper class a pre and post function is run as well. I want the wrapper class to work with any class without modification. For example if i have this class. ``` class Simple(object): def one(self): print "one" ...
You're almost there, you just need to do some introspection inside `__getattr__`, returning a new wrapped function when the original attribute is callable: ``` class Wrapper(object): def __init__(self,wrapped_class): self.wrapped_class = wrapped_class() def __getattr__(self,attr): orig_attr = ...
Testing for cookie existence in Django
1,466,732
2
2009-09-23T15:26:44Z
1,467,053
17
2009-09-23T16:13:23Z
[ "python", "django", "http", "cookies" ]
Simple stuff here... if I try to reference a cookie in Django via ``` request.COOKIE["key"] ``` if the cookie doesn't exist that will throw a key error. For Django's `GET` and `POST`, since they are `QueryDict` objects, I can just do ``` if "foo" in request.GET ``` which is wonderfully sophisticated... what's th...
`request.COOKIES` is a standard Python dictionary, so the same syntax works. Another way of doing it is: ``` request.COOKIES.get('key', 'default') ``` which returns the value if the key exists, otherwise 'default' - you can put anything you like in place of 'default'.
Parameterized queries with psycopg2 / Python DB-API and PostgreSQL
1,466,741
23
2009-09-23T15:28:13Z
1,467,978
9
2009-09-23T18:59:40Z
[ "python", "postgresql", "psycopg2" ]
What's the best way to make psycopg2 pass parameterized queries to PostgreSQL? I don't want to write my own escpaing mechanisms or adapters and the psycopg2 source code and examples are difficult to read in a web browser. If I need to switch to something like PyGreSQL or another python pg adapter, that's fine with me....
Here are a few examples you might find helpful ``` cursor.execute('SELECT * from table where id = %(some_id)d', {'some_id': 1234}) ``` Or you can dynamically build your query based on a dict of field name, value: ``` fields = ', '.join(my_dict.keys()) values = ', '.join(['%%(%s)s' % x for x in my_dict]) query = 'INS...
Parameterized queries with psycopg2 / Python DB-API and PostgreSQL
1,466,741
23
2009-09-23T15:28:13Z
1,471,178
45
2009-09-24T11:47:49Z
[ "python", "postgresql", "psycopg2" ]
What's the best way to make psycopg2 pass parameterized queries to PostgreSQL? I don't want to write my own escpaing mechanisms or adapters and the psycopg2 source code and examples are difficult to read in a web browser. If I need to switch to something like PyGreSQL or another python pg adapter, that's fine with me....
`psycopg2` follows the rules for DB-API 2.0 (set down in [PEP-249](http://www.python.org/dev/peps/pep-0249/)). That means you can call `execute` method from your `cursor` object and use the `pyformat` binding style, and it will do the escaping for you. For example, the following *should* be safe (and work): ``` cursor...
Can SAP work with Python?
1,466,917
15
2009-09-23T15:55:23Z
1,467,136
15
2009-09-23T16:24:26Z
[ "python", "sap", "abap" ]
Can Python be used to query a SAP database?
[Python SAP RFC module](http://pysaprfc.sourceforge.net/) seems inactive - [last (insignificant ) commit](http://pysaprfc.cvs.sourceforge.net/viewvc/pysaprfc/pysaprfc/) 2 years ago - but may serve you: > Pysaprfc is a wrapper around SAP librfc (librfc32.dll on Windows, librfccm.so or librfc.so on Linux). It uses the e...
Can SAP work with Python?
1,466,917
15
2009-09-23T15:55:23Z
13,127,357
9
2012-10-29T18:14:39Z
[ "python", "sap", "abap" ]
Can Python be used to query a SAP database?
Python RFC connector is now available as SAP open source <https://github.com/SAP/PyRFC>
Are python modules first class citizens?
1,467,612
6
2009-09-23T17:56:19Z
1,467,635
9
2009-09-23T17:59:30Z
[ "python", "module" ]
I mean, can I create them dynamically?
Yes: ``` >>> import types >>> m = types.ModuleType("mymod") >>> m <module 'mymod' (built-in)> ```
What language could I use for fast execution of this database summarization task?
1,467,898
9
2009-09-23T18:45:07Z
1,467,922
9
2009-09-23T18:50:07Z
[ "python", "sql", "lisp", "ocaml", "apache-pig" ]
So I wrote a Python program to handle a little data processing task. Here's a very brief specification in a made-up language of the computation I want: ``` parse "%s %lf %s" aa bb cc | group_by aa | quickselect --key=bb 0:5 | \ flatten | format "%s %lf %s" aa bb cc ``` That is, for each line, parse out a word, a...
I have a hard time believing that any script without any prior knowledge of the data (unlike MySql which has such info pre-loaded), would be faster than a SQL approach. Aside from the time spent parsing the input, the script needs to "keep" sorting the order by array etc... The following is a first guess at what shou...
python win32 extensions documentation
1,468,099
13
2009-09-23T19:27:17Z
1,468,133
10
2009-09-23T19:35:59Z
[ "python", "documentation", "pywin32" ]
I'm new to both python and the python win32 extensions available at <http://python.net/crew/skippy/win32/> but I can't find any documentation online or in the installation directories concerning what exactly the win32 extensions provide. Where is this information?
You'll find documentation here: <http://docs.activestate.com/activepython/2.4/pywin32/PyWin32.HTML> (Note: most of the API docs are under 'modules' and 'objects'. Note that the documentation is very sparse here but rembember: since it's only a wrapper on top of the win32 API --> the 'full' documentation is also on the...
How do you turn an unquoted Python function/lambda into AST? 2.6
1,468,634
5
2009-09-23T21:34:07Z
1,468,770
9
2009-09-23T22:03:27Z
[ "python", "abstract-syntax-tree" ]
This seems like it should be easy, but I can't find the answer anywhere - nor able to derive one myself. How do you turn an unquoted python function/lambda into an AST? Here is what I'd like to be able to do. ``` import ast class Walker(ast.NodeVisitor): pass # ... # note, this doesnt work as ast.parse wants...
In general, you can't. For example, `2 + 2` is an expression -- but if you pass it to any function or method, the argument being passed is just the number `4`, no way to recover what expression it was computed from. Function source code can sometimes be recovered (though not for a `lambda`), but "an unquoted Python exp...
Why am I receiving a low level socket error when using the Fabric python library?
1,469,431
16
2009-09-24T01:51:21Z
1,469,466
24
2009-09-24T02:01:12Z
[ "python" ]
When I run the command: ``` fab -H localhost host_type ``` I receive the following error: ``` [localhost] Executing task 'host_type' [localhost] run: uname -s Fatal error: Low level socket error connecting to host localhost: Connection refused Aborting. ``` Any thoughts as to why? Thanks. ### Fabfile.py ``` fro...
The important part isn't the "low level error" part of the message - the important part is the "Connection refused" part. You'll get a "connection refused" message when trying to connect to a closed port. The most likely scenario is that you are not running an ssh server on your machine at the time that Fabric is runn...
Eclipse+PyDev+GAE memcache error
1,469,860
18
2009-09-24T05:12:28Z
4,262,347
25
2010-11-24T00:09:11Z
[ "python", "eclipse", "google-app-engine", "pydev" ]
I've started using Eclipe+PyDev as an environment for developing my first app for Google App Engine. Eclipse is configured according to [this tutorial](http://code.google.com/appengine/articles/eclipse.html). Everything was working until I start to use memcache. PyDev reports the errors and I don't know how to fix it:...
There is a cleaner solution: Try adding GAE's memcache to your forced builtins. In your PyDev->Interpreter-Python->ForcedBuiltins window, add the "google.appengine.api.memcache" entry and apply. Double-click on the memcache errors to check them back, they disappear! Please make sure that system pythonpath includes g...
Why is the WindowsError while deleting the temporary file?
1,470,350
3
2009-09-24T08:10:28Z
1,472,979
9
2009-09-24T17:02:49Z
[ "python", "temporary-files" ]
1. I have created a temporary file. 2. Added some data to the file created. 3. Saved it and then trying to delete it. But I am getting `WindowsError`. I have closed the file after editing it. How do I check which other process is accessing the file. ``` C:\Documents and Settings\Administrator>python Python 2.6.1 (r26...
From the [documentation](http://docs.python.org/library/tempfile.html#tempfile.mkstemp): > mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order. New in version 2.3. So, `mkstemp` returns both the OS file handl...
Create new List object in python
1,470,446
3
2009-09-24T08:42:50Z
1,470,460
9
2009-09-24T08:47:29Z
[ "python", "list" ]
I am a beginner in python. I want to Create new List object in python. **My Code:** ``` recordList=[] mappedDictionay={} sectionGroupName= None for record in recordCols: item = record print item if not sectionGroupName == record[0]: sectionGroupName = record[0] del recordList[0:] # Her...
It's not that easy to understand your question, especially since your code lost its formatting, but you can create new list objects quite easily. The following assigns a new list object to the variable recordList: ``` recordList = list() ``` You could also use ``` recordList = [] ``` [] and list() are equivalent in...
How can I tell the Django ORM to reverse the order of query results?
1,470,676
26
2009-09-24T09:39:09Z
1,470,680
60
2009-09-24T09:40:23Z
[ "python", "django" ]
In my quest to understand queries against Django models, I've been trying to get the last 3 added valid Avatar models with a query like: ``` newUserAv = Avatar.objects.filter(valid=True).order_by("date")[:3] ``` However, this instead gives me the first three avatars added ordered by date. I'm sure this is simple, but...
Put a hyphen before the field name. ``` .order_by('-date') ```
Django: disallow can_delete on GenericStackedInline
1,470,811
15
2009-09-24T10:16:36Z
1,474,066
7
2009-09-24T20:48:45Z
[ "python", "django", "django-admin", "generics", "formset" ]
I've built this model which contains a generic foreign key: ``` class MyModel(models.Model): content_type = models.ForeignKey(ContentType, verbose_name=_('content type')) object_id = models.PositiveIntegerField(_('object id')) content_object = generic.GenericForeignKey('content_type', 'object_id') ``` Nex...
Update 2016: as per Stan's answer below, modern versions of django let you set [`can_delete = True`](https://docs.djangoproject.com/en/1.9/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.can_delete) on the [`GenericStackedInline`](https://docs.djangoproject.com/en/1.9/ref/contrib/contenttypes/#django.contrib.c...
Django: disallow can_delete on GenericStackedInline
1,470,811
15
2009-09-24T10:16:36Z
4,895,968
19
2011-02-04T08:33:29Z
[ "python", "django", "django-admin", "generics", "formset" ]
I've built this model which contains a generic foreign key: ``` class MyModel(models.Model): content_type = models.ForeignKey(ContentType, verbose_name=_('content type')) object_id = models.PositiveIntegerField(_('object id')) content_object = generic.GenericForeignKey('content_type', 'object_id') ``` Nex...
Maybe It is a post '09 feature, but you can specify that without overriding the `__init__()` method : ``` class StupidCarOptionsInline(admin.StackedInline): model = models.StupidOption form = StupidCarOptionAdminForm extra = 0 can_delete = False ```
Twisted network client with multiprocessing workers?
1,470,850
7
2009-09-24T10:28:19Z
1,472,271
12
2009-09-24T14:58:46Z
[ "python", "twisted", "multiprocessing" ]
So, I've got an application that uses Twisted + Stomper as a STOMP client which farms out work to a multiprocessing.Pool of workers. This appears to work ok when I just use a python script to fire this up, which (simplified) looks something like this: ``` # stompclient.py logging.config.fileConfig(config_path) logge...
Since the difference between your working invocation and your non-working invocation is only the "-n" option, it seems most likely that the problem is caused by the daemonization process (which "-n" prevents from happening). On POSIX, one of the steps involved in daemonization is forking and having the parent exit. Am...
String similarity metrics in Python
1,471,153
28
2009-09-24T11:43:00Z
1,471,303
15
2009-09-24T12:13:28Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
I want to find string similarity between two strings. [This](http://en.wikipedia.org/wiki/Category%3aString_similarity_measures) page has examples of some of them. Python has an implemnetation of [Levenshtein algorithm](http://code.google.com/p/pylevenshtein/). Is there a better algorithm, (and hopefully a python libra...
There's a great resource for string similarity metrics at the University of Sheffield. It has a list of various metrics (beyond just Levenshtein) and has open-source implementations of them. Looks like many of them should be easy to adapt into Python. <http://web.archive.org/web/20081224234350/http://www.dcs.shef.ac.u...
String similarity metrics in Python
1,471,153
28
2009-09-24T11:43:00Z
1,471,603
63
2009-09-24T13:10:55Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
I want to find string similarity between two strings. [This](http://en.wikipedia.org/wiki/Category%3aString_similarity_measures) page has examples of some of them. Python has an implemnetation of [Levenshtein algorithm](http://code.google.com/p/pylevenshtein/). Is there a better algorithm, (and hopefully a python libra...
I realize it's not the same thing, but this is close enough: ``` >>> import difflib >>> a = 'Hello, All you people' >>> b = 'hello, all You peopl' >>> seq=difflib.SequenceMatcher(a=a.lower(), b=b.lower()) >>> seq.ratio() 0.97560975609756095 ``` You can make this as a function ``` def similar(seq1, seq2): return ...
Small Tables in Python?
1,471,924
12
2009-09-24T14:07:17Z
1,472,025
13
2009-09-24T14:21:30Z
[ "python", "table", "lookup-tables" ]
Let's say I don't have more than one or two dozen objects with different properties, such as the following: UID, Name, Value, Color, Type, Location I want to be able to call up all objects with Location = "Boston", or Type = "Primary". Classic database query type stuff. Most table solutions (pytables, \*sql) are rea...
For small relational problems I love using Python's builtin [sets](http://docs.python.org/library/sets.html). For the example of location = 'Boston' OR type = 'Primary', if you had this data: ``` users = { 1: dict(Name="Mr. Foo", Location="Boston", Type="Secondary"), 2: dict(Name="Mr. Bar", Location="New York",...
How do I parse an HTTP date-string in Python?
1,471,987
27
2009-09-24T14:15:39Z
1,472,336
35
2009-09-24T15:10:31Z
[ "python", "http", "datetime", "parsing" ]
Is there an easy way to parse HTTP date-strings in Python? According to [the standard](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3), there are several ways to format HTTP date strings; the method should be able to handle this. In other words, I want to convert a string like "Wed, 23 Sep 2009 22:15:29 ...
``` >>> import email.utils as eut >>> eut.parsedate('Wed, 23 Sep 2009 22:15:29 GMT') (2009, 9, 23, 22, 15, 29, 0, 1, -1) ``` If you want a `datetime.datetime` object, you can do: ``` def my_parsedate(text): return datetime.datetime(*eut.parsedate(text)[:6]) ```
What is setup.py?
1,471,994
285
2009-09-24T14:16:52Z
1,472,014
202
2009-09-24T14:19:35Z
[ "python", "setup.py", "pypi", "python-packaging" ]
Can anyone please explain, what is `setup.py` and how can it be configured or used?
setup.py is a python file, which usually tells you that the module/package you are about to install have been packaged and distributed with Distutils, which is the standard for distributing Python Modules. This allows you to easily install Python packages, often it's enough to write: ``` python setup.py install ``` ...
What is setup.py?
1,471,994
285
2009-09-24T14:16:52Z
1,472,029
36
2009-09-24T14:21:46Z
[ "python", "setup.py", "pypi", "python-packaging" ]
Can anyone please explain, what is `setup.py` and how can it be configured or used?
If you downloaded package that has "setup.py" in root folder, you can install it by running ``` python setup.py install ``` If you are developing a project and are wondering what this file is useful for, check [Python documentation on writing the Setup Script](http://docs.python.org/distutils/setupscript.html)
What is setup.py?
1,471,994
285
2009-09-24T14:16:52Z
1,472,031
14
2009-09-24T14:21:58Z
[ "python", "setup.py", "pypi", "python-packaging" ]
Can anyone please explain, what is `setup.py` and how can it be configured or used?
`setup.py` is a Python script that is usually shipped with libraries or programs, written in that language. It's purpose is the correct installation of the software. Many packages use the `distutils` framework in conjuction with `setup.py`. <http://docs.python.org/distutils/>
What is setup.py?
1,471,994
285
2009-09-24T14:16:52Z
1,472,439
43
2009-09-24T15:29:09Z
[ "python", "setup.py", "pypi", "python-packaging" ]
Can anyone please explain, what is `setup.py` and how can it be configured or used?
`setup.py` is Python's answer to a multi-platform installer and `make` file. If you’re familiar with command line installations, then `make && make install` translates to `python setup.py build && python setup.py install`. Some packages are pure Python, and are only byte compiled. Others may contain native code, wh...
What is setup.py?
1,471,994
285
2009-09-24T14:16:52Z
16,088,409
9
2013-04-18T16:29:38Z
[ "python", "setup.py", "pypi", "python-packaging" ]
Can anyone please explain, what is `setup.py` and how can it be configured or used?
setup.py can be used in two scenarios , First, you want to install a Python package. Second, you want to create your own Python package. Usually standard Python package has couple of important files like setup.py, setup.cfg and Manifest.in. When you are creating the Python package, these three files will determine the ...
regex for triple quote
1,472,047
3
2009-09-24T14:26:01Z
1,472,390
10
2009-09-24T15:20:41Z
[ "python", "regex" ]
What regex will find the triple quote comments (possibly multi-line) in a Python source code?
Python is not a regular language and cannot reliably be parsed using regex. If you want a proper Python parser, look at the [ast](http://docs.python.org/library/ast.html) module. You may be looking for `get_docstring`.
Writing unicode strings via sys.stdout in Python
1,473,577
13
2009-09-24T19:02:35Z
1,475,202
9
2009-09-25T02:55:36Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
Assume for a moment that one cannot use `print` (and thus enjoy the benefit of automatic encoding detection). So that leaves us with `sys.stdout`. However, `sys.stdout` is so dumb as to [not do any sensible encoding](http://bugs.python.org/issue4947). Now one reads the Python wiki page [PrintFails](http://wiki.python....
Best idea is to check if you are directly connected to a terminal. If you are, use the terminal's encoding. Otherwise, use system preferred encoding. ``` if sys.stdout.isatty(): default_encoding = sys.stdout.encoding else: default_encoding = locale.getpreferredencoding() ``` It's also very important to always...
Writing unicode strings via sys.stdout in Python
1,473,577
13
2009-09-24T19:02:35Z
4,027,905
8
2010-10-26T20:50:59Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
Assume for a moment that one cannot use `print` (and thus enjoy the benefit of automatic encoding detection). So that leaves us with `sys.stdout`. However, `sys.stdout` is so dumb as to [not do any sensible encoding](http://bugs.python.org/issue4947). Now one reads the Python wiki page [PrintFails](http://wiki.python....
There is an optional environment variable "PYTHONIOENCODING" which may be set to a desired default encoding. It would be one way of grabbing the user-desired encoding in a way consistent with all of Python. It is buried in the Python manual [here](http://docs.python.org/release/3.1.2/using/cmdline.html?highlight=python...
Writing unicode strings via sys.stdout in Python
1,473,577
13
2009-09-24T19:02:35Z
6,361,471
23
2011-06-15T17:04:06Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
Assume for a moment that one cannot use `print` (and thus enjoy the benefit of automatic encoding detection). So that leaves us with `sys.stdout`. However, `sys.stdout` is so dumb as to [not do any sensible encoding](http://bugs.python.org/issue4947). Now one reads the Python wiki page [PrintFails](http://wiki.python....
``` export PYTHONIOENCODING=utf-8 ``` will do the job, but can't set it on python itself ... what we can do is verify if isn't setting and tell the user to set it before call script with : ``` if __name__ == '__main__': if (sys.stdout.encoding is None): print >> sys.stderr, "please set python env PYTHONI...
Raising ValidationError from django model's save method?
1,473,888
10
2009-09-24T20:13:16Z
1,473,979
8
2009-09-24T20:29:42Z
[ "python", "django" ]
I need to raise an exception in a model's save method. I'm hoping that an exception exists that will be caught by any django `ModelForm` that uses this model including the admin forms. I tried raising `django.forms.ValidationError`, but this seems to be uncaught by the admin forms. The model makes a remote procedure c...
There's currently no way of performing validation in model save methods. This is however being developed, as a separate model-validation branch, and should be merged into trunk in the next few months. In the meantime, you need to do the validation at the form level. It's quite simple to create a `ModelForm` subclass w...
Raising ValidationError from django model's save method?
1,473,888
10
2009-09-24T20:13:16Z
12,356,526
9
2012-09-10T17:19:52Z
[ "python", "django" ]
I need to raise an exception in a model's save method. I'm hoping that an exception exists that will be caught by any django `ModelForm` that uses this model including the admin forms. I tried raising `django.forms.ValidationError`, but this seems to be uncaught by the admin forms. The model makes a remote procedure c...
Since Django 1.2, this is what I've been doing: ``` class MyModel(models.Model): <...model fields...> def clean(self, *args, **kwargs): if <some constraint not met>: raise ValidationError('You have not met a constraint!') super(MyModel, self).clean(*args, **kwargs) def full_c...
Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
1,474,135
14
2009-09-24T21:01:23Z
1,474,175
21
2009-09-24T21:10:23Z
[ "python", "django", "sorting", "admin", "user-profile" ]
I have an application that makes use of Django's `UserProfile` to extend the built-in Django `User` model. Looks a bit like: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # Local Stuff image_url_s = models.CharField(max_length=128, blank=True) image_url_m = models.Cha...
One way would be to define a custom form to use for your Team model in the admin, and override the `manager` field to use a queryset with the correct ordering: ``` from django import forms class TeamForm(forms.ModelForm): manager = forms.ModelChoiceField(queryset=User.objects.order_by('username')) class Meta...
Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
1,474,135
14
2009-09-24T21:01:23Z
1,474,195
23
2009-09-24T21:15:58Z
[ "python", "django", "sorting", "admin", "user-profile" ]
I have an application that makes use of Django's `UserProfile` to extend the built-in Django `User` model. Looks a bit like: ``` class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # Local Stuff image_url_s = models.CharField(max_length=128, blank=True) image_url_m = models.Cha...
This ``` class Meta: ordering = ['username'] ``` should be ``` ordering = ['user__username'] ``` if it's in your UserProfile admin class. That'll stop the exception, but I don't think it helps you. Ordering the User model as you describe is quite tricky, but see <http://code.djangoproject.com/ticket/6089#c...
python arbitrarily incrementing an iterator inside a loop
1,474,646
32
2009-09-24T23:11:17Z
1,474,848
35
2009-09-25T00:27:11Z
[ "python", "iterator" ]
I am probably going about this in the wrong manner, but I was wondering how to handle this in python. First some c code: ``` int i; for(i=0;i<100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } ``` Ok so we never see the 50's... My question is, how can I do something similar in python? For instance: ``...
There is a fantastic package in Python called [`itertools`](http://docs.python.org/library/itertools.html). But before I get into that, it'd serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the [`__iter__()`](http://docs.pyth...
python arbitrarily incrementing an iterator inside a loop
1,474,646
32
2009-09-24T23:11:17Z
1,474,881
16
2009-09-25T00:42:07Z
[ "python", "iterator" ]
I am probably going about this in the wrong manner, but I was wondering how to handle this in python. First some c code: ``` int i; for(i=0;i<100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } ``` Ok so we never see the 50's... My question is, how can I do something similar in python? For instance: ``...
### [itertools.islice](http://docs.python.org/library/itertools.html#itertools.islice): ``` lines = iter(cdata.splitlines()) for line in lines: if exp.match(line): #increment the position of the iterator by 5 for _ in itertools.islice(lines, 4): pass continue # skip 1+4 lines pr...
Easiest way to turn a list into an HTML table in python?
1,475,123
6
2009-09-25T02:23:41Z
1,475,453
19
2009-09-25T04:36:28Z
[ "python", "html-table", "html-generation" ]
lets say I have a list like so: ``` ['one','two','three','four','five','six','seven','eight','nine'] ``` and I want to experiment with turning this data into a HTML table of various dimensions: ``` one two three four five six seven eight nine ``` or ``` one four seven two five eight three ...
I would decompose your problem into two parts: * given a "flat list", produce a list of sublists where the sublists are of a given length and the overall list may be walked into either a "row major" order (your first and third example) or "column major" (your second example); * given a list of sublists with string ite...
How do you bind a language (python, for example) to another (say, C++)?
1,475,637
15
2009-09-25T05:55:40Z
1,475,717
11
2009-09-25T06:26:11Z
[ "java", "python", "binding" ]
I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.
### Interpreters Written in C89 with Reflection, Who Knew? --- I have a feeling you are looking for an explanation of the mechanism and not a link to the API or instructions on how to code it. So, as I understand it . . . The main interpreter is typically written in C and is dynamically linked. In a dynamically link...
tail -f in python with no time.sleep
1,475,950
24
2009-09-25T07:45:08Z
1,475,976
10
2009-09-25T07:53:40Z
[ "python" ]
I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown ...
When reading from a file, your only choice is sleep ([see the source code](http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/tail.c#n877)). If you read from a pipe, you can simply read since the read will block until there is data ready. The reason for this is that the OS doesn't support the notion "wait for som...
tail -f in python with no time.sleep
1,475,950
24
2009-09-25T07:45:08Z
1,476,006
31
2009-09-25T08:05:04Z
[ "python" ]
I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown ...
(update) Either use FS monitors tools * For [linux](http://pyinotify.sourceforge.net/) * For [Windows](http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/watch%5Fdirectory%5Ffor%5Fchanges.html) * For [Mac](http://pypi.python.org/pypi/pyobjc-framework-FSEvents/2.2b2) Or a single sleep usage (which I would you consider...
tail -f in python with no time.sleep
1,475,950
24
2009-09-25T07:45:08Z
13,691,289
10
2012-12-03T20:37:45Z
[ "python" ]
I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown ...
To minimize the sleep issues I modified Tzury Bar Yochay's solution and now it polls quickly if there is activity and after a few seconds of no activity it only polls every second. ``` import time def follow(thefile): thefile.seek(0,2) # Go to the end of the file sleep = 0.00001 while True: l...
Python: Referencing another project
1,476,111
4
2009-09-25T08:34:30Z
1,476,134
10
2009-09-25T08:40:16Z
[ "python", "command-line" ]
I want to be able to run my Python project from the command line. I am referencing other projects, so I need to be able run modules in other folders. One method of making this work would be to modify the Pythonpath environment variable, but I think this is an abuse. Another hack would be to copy all the files I want i...
If you import sys, it contains a list of the directories in PYTHONPATH as sys.path Adding directories to this list (sys.path.append("my/path")) allows you to import from those locations in the current module as normal without changing the global settings on your system.
Compile Matplotlib for Python on Snow Leopard
1,477,144
20
2009-09-25T12:56:40Z
1,477,394
7
2009-09-25T13:49:12Z
[ "python", "osx-snow-leopard", "numpy", "compilation", "matplotlib" ]
I've killed half a day trying to compile matplotlib for python on Snow Leopard. I've used the googles and found this helpful page (<http://blog.hyperjeff.net/?p=160>) but I still can't get it to compile. I see comments from other users on that page, so I know I'm not alone. I already installed zlib, libpng and freetyp...
According to your error message you have missing freetype headers. Can you locate them using system search functionalities. I will not lecture on using a pre-built package since I love scratching my head and compiling from the start as well.
Generate random UTF-8 string in Python
1,477,294
15
2009-09-25T13:29:53Z
1,477,375
7
2009-09-25T13:47:12Z
[ "python", "unicode", "utf-8", "random" ]
I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer. Edit: It looks like this is more complex than expected, so I'll rephrase the question - ...
There is a [UTF-8 stress test from Markus Kuhn](http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt) you could use. See also [Really Good, Bad UTF-8 example test data](http://stackoverflow.com/questions/1319022/really-good-bad-utf-8-example-test-data).
Generate random UTF-8 string in Python
1,477,294
15
2009-09-25T13:29:53Z
21,666,621
8
2014-02-09T23:34:33Z
[ "python", "unicode", "utf-8", "random" ]
I'd like to test the Unicode handling of my code. Is there anything I can put in random.choice() to select from the entire Unicode range, preferably not an external module? Neither Google nor StackOverflow seems to have an answer. Edit: It looks like this is more complex than expected, so I'll rephrase the question - ...
People may find their way here based mainly on the question title, so here's a way to generate a random string containing a variety of Unicode characters. To include more (or fewer) possible characters, just extend that part of the example with the code point ranges that you want. ``` import random def get_random_uni...
How was the syntax chosen for static methods in Python?
1,477,545
14
2009-09-25T14:14:31Z
1,477,598
12
2009-09-25T14:24:47Z
[ "python", "syntax", "static", "language-history" ]
I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar. A regular method would be declared: ``` def mymethod(self, params) ... return ``` A static method is declared: ``` def mystaticethod(params) ... return mystaticmethod = staticmethod(mystaticme...
Static methods were added to Python long after classes were (classes were added very early on, possibly even before 1.0; static methods didn't show up until sometime about 2.0). They were implemented as a modification of normal methods — you create a static method object from a function to get a static method, whereas ...
How was the syntax chosen for static methods in Python?
1,477,545
14
2009-09-25T14:14:31Z
1,477,897
11
2009-09-25T15:13:08Z
[ "python", "syntax", "static", "language-history" ]
I've been working with Python for a while and I find the syntax for declaring methods as static to be peculiar. A regular method would be declared: ``` def mymethod(self, params) ... return ``` A static method is declared: ``` def mystaticethod(params) ... return mystaticmethod = staticmethod(mystaticme...
voyager and adurdin do a good job, between them, of explaining what happened: with the introduction of new-style classes and descriptors in Python 2.2, new and deep semantic possibilities arose -- and the most obviously useful examples (static methods, class methods, properties) were supported by built-in descriptor ty...
Python chat : delete variables to clean memory in functions?
1,477,980
11
2009-09-25T15:26:38Z
1,478,088
7
2009-09-25T15:44:19Z
[ "python", "class", "function", "twisted" ]
I'm creating a chat daemon in python and twisted framework. And I'm wondering if I have to delete every variable create in my functions to save memory in the long run when multiple users are connected, or are those variable automatically clear?. Here's a strip down version of my code to illustrate my point: ``` class ...
Python objects are never explicitly deleted. The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The `del` keyword simply unbinds a name from an object, but the object still needs to be garbage collected. If you really think you have to, you can force the garbage collect...
Python chat : delete variables to clean memory in functions?
1,477,980
11
2009-09-25T15:26:38Z
1,478,134
16
2009-09-25T15:52:17Z
[ "python", "class", "function", "twisted" ]
I'm creating a chat daemon in python and twisted framework. And I'm wondering if I have to delete every variable create in my functions to save memory in the long run when multiple users are connected, or are those variable automatically clear?. Here's a strip down version of my code to illustrate my point: ``` class ...
C Python (the reference implementation) uses reference counting and garbage collection. When count of references to object decrease to 0, it is automatically reclaimed. The garbage collection normally reclaims only those objects that refer to each other (or other objects from them) and thus cannot be reclaimed by refer...
Python type inference for autocompletion
1,478,044
10
2009-09-25T15:34:35Z
1,478,067
9
2009-09-25T15:40:04Z
[ "python", "algorithm", "ide", "haskell", "ocaml" ]
Is it possible to use Ocaml/Haskell algorithm of type inference to suggest better autocompletions for Python? The idea is to propose autocompletion for example in the following cases: ``` class A: def m1(self): pass def m2(self): pass a = A() a. <--- suggest here 'm1' and 'm2' fun1(a) def fun1(b): ...
Excellent discussion, with many pointers, [here](http://lambda-the-ultimate.org/node/1519) (a bit dated). I don't believe any "production" editors aggressively try type-inferencing for autocomplete purposes (but I haven't used e.g. wingware's in a while, so maybe they do now).
for line in open(filename)
1,478,697
17
2009-09-25T17:47:07Z
1,478,711
8
2009-09-25T17:50:45Z
[ "python", "file", "garbage-collection" ]
I frequently see python code similar to ``` for line in open(filename): do_something(line) ``` When does filename get closed with this code? Would it be better to write ``` with open(filename) as f: for line in f.readlines(): do_something(line) ```
The `with` part is better because it close the file afterwards. You don't even have to use `readlines()`. `for line in file` is enough. I don't think the first one closes it.
for line in open(filename)
1,478,697
17
2009-09-25T17:47:07Z
1,478,712
27
2009-09-25T17:50:52Z
[ "python", "file", "garbage-collection" ]
I frequently see python code similar to ``` for line in open(filename): do_something(line) ``` When does filename get closed with this code? Would it be better to write ``` with open(filename) as f: for line in f.readlines(): do_something(line) ```
`filename` would be closed when it falls out of scope. That normally would be the end of the method. Yes, it's better to use `with`. > Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the `close` method on the ...
Python: "1-2-3-4" to [1, 2, 3, 4]
1,478,908
2
2009-09-25T18:33:09Z
1,478,912
8
2009-09-25T18:34:29Z
[ "python" ]
What is the best way to convert a string on the format `"1-2-3-4"` to a list `[1, 2, 3, 4]`? The string may also be empty, in which case the conversion should return an empty list `[]`. This is what I have: ``` map(lambda x: int(x), filter(lambda x: x != '', "1-2-3-4".split('-'))) ``` EDIT: Sorry all ...
``` >>> for s in ["", "0", "-0-0", "1-2-3-4"]: ... print(map(int, filter(None, s.split('-')))) ... [] [0] [0, 0] [1, 2, 3, 4] ```
Python: "1-2-3-4" to [1, 2, 3, 4]
1,478,908
2
2009-09-25T18:33:09Z
1,478,917
12
2009-09-25T18:35:17Z
[ "python" ]
What is the best way to convert a string on the format `"1-2-3-4"` to a list `[1, 2, 3, 4]`? The string may also be empty, in which case the conversion should return an empty list `[]`. This is what I have: ``` map(lambda x: int(x), filter(lambda x: x != '', "1-2-3-4".split('-'))) ``` EDIT: Sorry all ...
You can use a list comprehension to make it shorter. Use the `if` to account for the empty string. ``` the_string = '1-2-3-4' [int(x) for x in the_string.split('-') if x != ''] ```