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
virtualenv yolk problem
2,742,980
11
2010-04-30T07:37:46Z
2,744,571
18
2010-04-30T12:47:51Z
[ "python", "virtualenv", "yolk" ]
`yolk -l` gives me information that I've got 114 packages installed on my Ubuntu 10.04. After creating new virtualenv directory using `virtualenv virt_env/virt1 --no-site-packages --clear` I switched to that, my prompt changed and then `yolk -l` gives me again the same 114 packages. What is going on there?
Activating a virtualenv works by changing your shell PATH so the virtualenv's bin/ directory is first. This is *all* it does. This means that when you run "python" it runs the virtualenv's copy of the Python binary instead of your global system python. If you have yolk installed globally, however, the only "yolk" bina...
Remove non-ASCII characters from a string using python / django
2,743,070
14
2010-04-30T07:56:35Z
2,743,163
16
2010-04-30T08:16:56Z
[ "python", "regex", "django", "unicode", "replace" ]
I have a string of HTML stored in a database. Unfortunately it contains characters such as ® I want to replace these characters by their HTML equivalent, either in the DB itself or using a Find Replace in my Python / Django code. Any suggestions on how I can do this?
You can use that the ASCII characters are the first 128 ones, so get the number of each character with `ord` and strip it if it's out of range ``` # -*- coding: utf-8 -*- def strip_non_ascii(string): ''' Returns the string without non ASCII characters''' stripped = (c for c in string if 0 < ord(c) < 127) ...
Performing non-blocking requests? - Django
2,743,331
9
2010-04-30T08:51:51Z
2,743,372
9
2010-04-30T08:59:36Z
[ "python", "django", "asynchronous", "nonblocking" ]
I have been playing with other frameworks, such as NodeJS, lately. I love the possibility to return a response, and still being able to do further operations. e.g. ``` def view(request): do_something() return HttpResponse() do_more_stuff() #not possible!!! ``` --- Maybe Django already offers a way to perfor...
not out of the box as you've already returned out of the method. You could use something like [Celery](http://ask.github.com/celery/getting-started/introduction.html) which would pass the `do_more_stuff` task onto a queue and then have it run `do_more_stuff()` outside of http request / response flow.
Performing non-blocking requests? - Django
2,743,331
9
2010-04-30T08:51:51Z
2,743,374
7
2010-04-30T08:59:56Z
[ "python", "django", "asynchronous", "nonblocking" ]
I have been playing with other frameworks, such as NodeJS, lately. I love the possibility to return a response, and still being able to do further operations. e.g. ``` def view(request): do_something() return HttpResponse() do_more_stuff() #not possible!!! ``` --- Maybe Django already offers a way to perfor...
Django lets you accomplish this with Signals, more information can be found [here](http://docs.djangoproject.com/en/dev/topics/signals/). (Please note, as I said in comments below, signals aren't non-blocking, but they do allow you to execute code after returning a response in a view.) If you're looking into doing man...
How to change User-Agent on Google App Engine UrlFetch service?
2,743,521
6
2010-04-30T09:24:28Z
2,743,571
10
2010-04-30T09:34:25Z
[ "python", "google-app-engine" ]
Is it possible to change User-Agent of Google App Engine [UrlFetch service](http://code.google.com/intl/it/appengine/docs/python/urlfetch/)?
Ok found it, it's possible since [SDK 1.2.1](http://googleappengine.blogspot.com/2009/04/sdk-version-121-released.html) was released ([Issue 342](http://code.google.com/p/googleappengine/issues/detail?id=342)). You just have to specify the User-Agent header: ``` urlfetch.fetch(url, headers = {'User-Agent': "MyApplic...
Installing OSQA on windows (local system)
2,743,712
13
2010-04-30T10:05:16Z
2,744,164
14
2010-04-30T11:33:56Z
[ "python", "django", "osqa" ]
I want to install OSQA on a local Windows system. I've downloaded bitnami-djangostack-1.1.1-2-windows-installer.exe, which has django, python, mysql and apache built in. I've run a django example given on the django website and it's working fine. But I'm confused how to install OSAQ. I've downloaded the source code f...
1. Download <http://svn.osqa.net/svnroot/osqa/trunk> to a folder `{OSQA_ROOT}` eg, `c:\osqa` 2. Rename `{OSQA_ROOT}\settings_local.py.dist` to `{OSQA_ROOT}\settings_local.py` 3. set following in `{OSQA_ROOT}\settings_local.py` ``` DATABASE_NAME = 'osqa' # Or path to database file if using sqlite3. ...
Change text_factory in Django/sqlite
2,744,632
6
2010-04-30T13:00:48Z
3,073,125
8
2010-06-18T21:11:35Z
[ "python", "django", "sqlite", "pysqlite" ]
I have a django project that uses a sqlite database that can be written to by an external tool. The text is supposed to be UTF-8, but in some cases there will be errors in the encoding. The text is from an external source, so I cannot control the encoding. Yes, I know that I could write a "wrapping layer" between the e...
> The solution in sqlite is to change > the text\_factory to something like: > lambda x: unicode(x, "utf-8", > "ignore") > > However, I don't know how to tell the Django model driver this. Have you tried ``` from django.db import connection connection.connection.text_factory = lambda x: unicode(x, "utf-8", "ignore") ...
Background color for Tk in Python
2,744,795
15
2010-04-30T13:28:19Z
2,745,312
34
2010-04-30T14:45:45Z
[ "python", "tkinter", "tk" ]
I'm writing a slideshow program with Tkinter, but I don't know how to change the background color to black instead of the standard light gray. How can this be done? ``` import os, sys import Tkinter import Image, ImageTk import time root = Tkinter.Tk() w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.o...
``` root.configure(background='black') ``` or more generally ``` <widget>.configure(background='black') ```
Background color for Tk in Python
2,744,795
15
2010-04-30T13:28:19Z
18,025,958
11
2013-08-02T20:54:06Z
[ "python", "tkinter", "tk" ]
I'm writing a slideshow program with Tkinter, but I don't know how to change the background color to black instead of the standard light gray. How can this be done? ``` import os, sys import Tkinter import Image, ImageTk import time root = Tkinter.Tk() w, h = root.winfo_screenwidth(), root.winfo_screenheight() root.o...
I know this is kinda an old question but: ``` root["bg"] = "black" ``` will also do what you want and it involves less typing.
Basic Python: Exception raising and local variable scope / binding
2,744,820
4
2010-04-30T13:32:19Z
2,745,436
8
2010-04-30T15:00:02Z
[ "python", "exception-handling", "scope" ]
I have a basic "best practices" Python question. I see that there are already StackOverflow answers tangentially related to this question but they're mired in complicated examples or involve multiple factors. Given this code: ``` #!/usr/bin/python def test_function(): try: a = str(5) raise b = s...
> Does python have an elegant way to > handle this? To avoid exceptions from printing unbound names, the most elegant way is not to print them; the second most elegant is to ensure the names do get bound, e.g. by binding them at the start of the function (the placeholder `None` is popular for this purpose). > If not,...
differences between "d = dict()" and "d = {}"
2,745,008
24
2010-04-30T13:58:07Z
2,745,047
19
2010-04-30T14:12:29Z
[ "python", "performance", "timing" ]
``` $ python2.7 -m timeit 'd={}' 10000000 loops, best of 3: 0.0331 usec per loop $ python2.7 -m timeit 'd=dict()' 1000000 loops, best of 3: 0.19 usec per loop ``` Why use one over the other?
`d=dict()` requires a lookup in [`locals()`](http://docs.python.org/2/library/functions.html#locals) then [`globals()`](http://docs.python.org/2/library/functions.html#globals) then `__builtins__`, `d={}` doesn't
differences between "d = dict()" and "d = {}"
2,745,008
24
2010-04-30T13:58:07Z
2,745,122
7
2010-04-30T14:23:35Z
[ "python", "performance", "timing" ]
``` $ python2.7 -m timeit 'd={}' 10000000 loops, best of 3: 0.0331 usec per loop $ python2.7 -m timeit 'd=dict()' 1000000 loops, best of 3: 0.19 usec per loop ``` Why use one over the other?
If people use (just) `dict()` over (just) `{}`, it's generally because they don't know about `{}` (which is quite a feat), or because they think it's clearer (which is subjective, but uncommon.) There are things you can do with `dict` that you can't do with `{}`, though, such as pass it to something that expects a cal...
differences between "d = dict()" and "d = {}"
2,745,008
24
2010-04-30T13:58:07Z
2,745,292
33
2010-04-30T14:43:33Z
[ "python", "performance", "timing" ]
``` $ python2.7 -m timeit 'd={}' 10000000 loops, best of 3: 0.0331 usec per loop $ python2.7 -m timeit 'd=dict()' 1000000 loops, best of 3: 0.19 usec per loop ``` Why use one over the other?
I'm one of those who prefers words to punctuation -- it's one of the reasons I've picked Python over Perl, for example. "Life is better without braces" (an old Python motto which went on a T-shirt with a cartoon of a smiling teenager;-), after all (originally intended to refer to braces vs indentation for grouping, of ...
Python - is there a "don't care" symbol for tuple assignments?
2,745,018
28
2010-04-30T13:59:31Z
2,745,063
14
2010-04-30T14:15:48Z
[ "python", "syntax" ]
Given a string "VAR=value" I want to split it (only) at the **first** '=' sign (< value > may contain more '=' signs), something like this: ``` var, sep, value = "VAR=value".partition('=') ``` Is there a way to NOT declare a variable 'sep'? Like this (just made up the syntax): ``` var, -, value = "VAR=value".partiti...
Almost there: ``` var, _, value = "VAR=value".partition('=') ``` `_` is conventionally considered a don't-care variable.
Python - is there a "don't care" symbol for tuple assignments?
2,745,018
28
2010-04-30T13:59:31Z
2,745,537
32
2010-04-30T15:13:22Z
[ "python", "syntax" ]
Given a string "VAR=value" I want to split it (only) at the **first** '=' sign (< value > may contain more '=' signs), something like this: ``` var, sep, value = "VAR=value".partition('=') ``` Is there a way to NOT declare a variable 'sep'? Like this (just made up the syntax): ``` var, -, value = "VAR=value".partiti...
`_` is indeed a very popular choice for "a name which doesn't matter" -- it's a legal name, visually unobtrusive, etc. However sometimes these very qualities can hinder you. For example, the GNU [gettext](http://docs.python.org/library/gettext.html) module for I18N and L10N, which is part of Python's standard library, ...
How to make scipy.interpolate give an extrapolated result beyond the input range?
2,745,329
40
2010-04-30T14:46:56Z
2,745,496
21
2010-04-30T15:07:53Z
[ "python", "math", "numpy", "scipy" ]
I'm trying to port a program which uses a hand-rolled interpolator (developed by a mathematician colleage) over to use the interpolators provided by scipy. I'd like to use or wrap the scipy interpolator so that it has as close as possible behavior to the old interpolator. A key difference between the two functions is ...
### 1. Constant extrapolation You can use `interp` function from scipy, it extrapolates left and right values as constant beyond the range: ``` >>> from scipy import interp, arange, exp >>> x = arange(0,10) >>> y = exp(-x/3.0) >>> interp([9,10], x, y) array([ 0.04978707, 0.04978707]) ``` ### 2. Linear (or other cus...
How to make scipy.interpolate give an extrapolated result beyond the input range?
2,745,329
40
2010-04-30T14:46:56Z
8,166,155
37
2011-11-17T11:12:38Z
[ "python", "math", "numpy", "scipy" ]
I'm trying to port a program which uses a hand-rolled interpolator (developed by a mathematician colleage) over to use the interpolators provided by scipy. I'd like to use or wrap the scipy interpolator so that it has as close as possible behavior to the old interpolator. A key difference between the two functions is ...
You can take a look at [InterpolatedUnivariateSpline](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.InterpolatedUnivariateSpline.html#scipy.interpolate.InterpolatedUnivariateSpline) Here an example using it: ``` import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import I...
PyDev and Django: how to restart dev server?
2,746,512
15
2010-04-30T17:41:39Z
2,746,745
13
2010-04-30T18:25:43Z
[ "python", "django", "eclipse", "pydev", "devserver" ]
I'm new to Django. I think I'm making a simple mistake. I launched the dev server with Pydev: > RClick on project >> Django >> Custom > command >> runserver The server came up, and everything was great. But now I'm trying to stop it, and can't figure out how. I stopped the process in the PyDev console, and closed Ec...
By default, the runserver command runs in autoreload mode, which runs in a separate process. This means that PyDev doesn't know how to stop it, and doesn't display its output in the console window. If you run the command `runserver --noreload` instead, the auto-reloader will be disabled. Then you can see the console o...
How do I overwrite a file currently being read by Python
2,746,758
3
2010-04-30T18:27:06Z
2,746,773
7
2010-04-30T18:30:10Z
[ "python", "pdf", "input", "overwrite" ]
I am not too sure the best way to word this, but what I want to do, is read a pdf file, make various modifications, and save the modified pdf over the original file. As of now, I am able to save the modified pdf to a separate file, but I am looking to replace the original, not create a new file. Here is my current cod...
You can always rename the temporary output file to the old file: ``` import os f = open('input.pdf', 'rb') # do stuff to temp.pdf f.close() os.rename('temp.pdf', 'input.pdf') ```
Django: Change models without clearing all data?
2,746,818
16
2010-04-30T18:36:32Z
2,746,865
20
2010-04-30T18:43:59Z
[ "python", "django" ]
I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data? I tried changing the field and running `python manage.py syncdb`. There was no output from this command. Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors...
Django does not ever alter an existing database column. Syncdb will create tables, but it does not do 'migrations' as found in Rails, for instance. If you need something like that, check out [Django South](http://south.aeracode.org/). See [the docs for syndb](http://docs.djangoproject.com/en/dev/ref/django-admin/#sync...
Django: Change models without clearing all data?
2,746,818
16
2010-04-30T18:36:32Z
2,746,888
8
2010-04-30T18:47:39Z
[ "python", "django" ]
I have some models I'm working with in a new Django installation. Is it possible to change the fields without losing app data? I tried changing the field and running `python manage.py syncdb`. There was no output from this command. Renavigating to admin pages for editing the changed models caused TemplateSyntaxErrors...
Of course there is. Check out [South](http://south.aeracode.org/)
Why do dicts of defaultdict(int)'s use so much memory? (and other simple python performance questions)
2,747,511
10
2010-04-30T20:33:57Z
2,747,855
8
2010-04-30T21:36:10Z
[ "python", "performance", "memory", "runtime" ]
I do understand that querying a non-existent key in a defaultdict the way I do will add items to the defaultdict. That is why it is fair to compare my 2nd code snippet to my first one in terms of performance. ``` import numpy as num from collections import defaultdict topKeys = range(16384) keys = range(8192) table ...
Python ints are internally represented as C longs (it's actually a bit more complicated than that), but that's not really the root of your problem. The biggest overhead is your usage of dicts. (defaultdicts and dicts are about the same in this description). dicts are implemented using hash tables, which is nice becaus...
Equivalent of PHP "echo something; exit();" with Python/Django?
2,747,554
14
2010-04-30T20:43:05Z
2,747,570
11
2010-04-30T20:45:37Z
[ "python", "django" ]
Sometimes the best way to debug something is to print some stuff to the page, and `exit()`, how can I do this in a Python/Django site? e.g. in PHP: ``` echo $var; exit(); ``` Thanks
Put this in your view function: ``` from django.http import HttpResponse return HttpResponse(str(var)) ```
Equivalent of PHP "echo something; exit();" with Python/Django?
2,747,554
14
2010-04-30T20:43:05Z
2,747,724
11
2010-04-30T21:11:17Z
[ "python", "django" ]
Sometimes the best way to debug something is to print some stuff to the page, and `exit()`, how can I do this in a Python/Django site? e.g. in PHP: ``` echo $var; exit(); ``` Thanks
I just wanted to give an alternative answer: Simply use `print` statements and serve your django site with `python manage.py runserver` In this case the `print` statements show up in your shell, and your site continues functioning as it would normally.
Pyglet OpenGL drawing anti-aliasing
2,747,784
8
2010-04-30T21:21:52Z
2,748,072
7
2010-04-30T22:35:37Z
[ "python", "opengl", "antialiasing", "pyglet", "pyopengl" ]
I've been looking around for a way to anti-alias lines in OpenGL, but none of them seem to work... here's some example code: ``` import pyglet from pyglet.gl import * window = pyglet.windo...
It's a bit hard to say for sure. The first thing is probably to change your hint from GL\_DONT\_CARE to GL\_NICEST. It probably won't make much difference with most graphics cards, but it might help a little. Other than that, it's a bit hard to say. Here's a bit of code (in C++; sorry): ``` void draw_line(float y_off...
Pyglet OpenGL drawing anti-aliasing
2,747,784
8
2010-04-30T21:21:52Z
2,748,107
8
2010-04-30T22:44:49Z
[ "python", "opengl", "antialiasing", "pyglet", "pyopengl" ]
I've been looking around for a way to anti-alias lines in OpenGL, but none of them seem to work... here's some example code: ``` import pyglet from pyglet.gl import * window = pyglet.windo...
Allow Pyglet to use an extra sample buffer might help. Change your window line to this: ``` config = pyglet.gl.Config(sample_buffers=1, samples=4) window = pyglet.window.Window(config=config, resizable=True) ``` This works for me.
In Python, how can I find the index of the first item in a list that is NOT some value?
2,748,235
11
2010-04-30T23:35:07Z
2,748,753
14
2010-05-01T03:15:29Z
[ "python", "list", "methods", "indexing" ]
Python's list type has an index(x) method. It takes a single parameter x, and returns the (integer) index of the first item in the list that has the value x. Basically, I need to invert the index(x) method. I need to get the index of the first value in a list that does NOT have the value x. I would probably be able to...
Exiting at the first match is really easy: instead of computing a full list comprehension (then tossing away everything except the first item), use [`next`](http://docs.python.org/2/library/functions.html#next) over a genexp. Assuming for example that you want `-1` when no item satisfies the condition of being `!= x`, ...
Why are closures broken within exec?
2,749,655
16
2010-05-01T10:59:11Z
2,749,806
21
2010-05-01T12:00:08Z
[ "python", "closures", "exec" ]
In Python 2.6, ``` >>> exec "print (lambda: a)()" in dict(a=2), {} 2 >>> exec "print (lambda: a)()" in globals(), {'a': 2} Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> File "<string>", line 1, in <lambda> NameError: global name 'a' is not defined >>>...
When you pass a string to `exec` or `eval`, it compiles that string to a code object before considering globals or locals. So when you say: ``` eval('lambda: a', ...) ``` it means: ``` eval(compile('lambda: a', '<stdin>', 'eval'), ...) ``` There's no way for `compile` to know that `a` is a freevar, so it compiles i...
How to get the original variable name of variable passed to a function
2,749,796
17
2010-05-01T11:57:18Z
2,749,810
7
2010-05-01T12:01:40Z
[ "python", "function", "variables" ]
Is it possible to get the original variable name of a variable passed to a function? E.g. ``` foobar = "foo" def func(var): print var.origname ``` So that: ``` func(foobar) ``` Returns: `>>foobar` **EDIT:** All I was trying to do was make a function like: ``` def log(soup): f = open(varname+'.html', 'w...
You can't. It's evaluated before being passed to the function. All you can do is pass it as a string.
How to get the original variable name of variable passed to a function
2,749,796
17
2010-05-01T11:57:18Z
2,749,857
24
2010-05-01T12:13:58Z
[ "python", "function", "variables" ]
Is it possible to get the original variable name of a variable passed to a function? E.g. ``` foobar = "foo" def func(var): print var.origname ``` So that: ``` func(foobar) ``` Returns: `>>foobar` **EDIT:** All I was trying to do was make a function like: ``` def log(soup): f = open(varname+'.html', 'w...
**EDIT:** To make it clear, I don't recommend using this AT ALL, it will break, it's a mess, it won't help you in anyway, but it's doable for entertainment/education purposes. You can hack around with the `inspect` module, I don't recommend that, but you can do it... ``` import inspect def foo(a, f, b): frame = ...
Looking forward to a programming future but confused where to start
2,749,889
10
2010-05-01T12:25:57Z
2,749,911
8
2010-05-01T12:34:10Z
[ "java", "c++", "python" ]
I am very new to this site and to programming. I started doing some basic programming with python a few weeks ago and recently, messing around with Java basics. My main problem is that I am completely overwhelmed and haven't got the slightest clue where I should be starting. I want to learn programming because I real...
C++ is horrible for beginners. It's a sprawling mixed metaphor of a language. You would certainly find it easier to approach once comfortable with object-orientation through more disciplined environments like C# or Java. Scripting languages like Python are a much better place to start. Bash up some stuff in Pygame or ...
Looking forward to a programming future but confused where to start
2,749,889
10
2010-05-01T12:25:57Z
2,749,965
12
2010-05-01T12:49:03Z
[ "java", "c++", "python" ]
I am very new to this site and to programming. I started doing some basic programming with python a few weeks ago and recently, messing around with Java basics. My main problem is that I am completely overwhelmed and haven't got the slightest clue where I should be starting. I want to learn programming because I real...
Game programming is a lot about *design* and *gameplay*; the language is merely a tool. Of course, C++ is widely used, but even a C++ guru wouldn't be able to make a decent game if he didn't play games or understand how the actual mechanics work. You can learn C++ any day, learning how to create a game that is actuall...
Send a "304 Not Modified" for images stored in the datastore
2,750,889
5
2010-05-01T17:27:14Z
2,750,925
7
2010-05-01T17:38:32Z
[ "python", "http", "google-app-engine", "httphandler" ]
I store user-uploaded images in the Google App Engine datastore as `db.Blob`, as proposed in [the docs](http://code.google.com/appengine/docs/python/images/usingimages.html). I then serve those images on `/images/<id>.jpg`. The server always sends a `200 OK` response, which means that the browser has to download the s...
[Bloggart](http://github.com/Arachnid/bloggart) uses this technique. Have a look at [this blog post](http://blog.notdot.net/2009/10/Blogging-on-App-Engine-part-1-Static-serving). ``` class StaticContentHandler(webapp.RequestHandler): def output_content(self, content, serve=True): self.response.headers['Content-T...
Google App Engine Python Unit Tests
2,750,911
16
2010-05-01T17:32:11Z
2,750,940
17
2010-05-01T17:44:27Z
[ "python", "unit-testing", "google-app-engine" ]
I'd like to write some Python unit tests for my Google App Engine. How can I set that up? Does someone happen to have some sample code which shows how to write a simple test?
[GAEUnit](http://code.google.com/p/gaeunit/) is a unit test framework that helps to automate testing of your Google App Engine application. **Update**: The Python SDK now provides a `testbed` module that makes service stubs available for unit testing. [Documentation here](http://code.google.com/appengine/docs/python/t...
Enthought Python, Sage, or others (in Unix clusters)
2,751,058
12
2010-05-01T18:21:51Z
2,751,347
9
2010-05-01T19:47:49Z
[ "python", "unix", "numpy", "scipy" ]
I have access to a cluster of Unix machines, but they don't have the software I need ([numpy](http://numpy.scipy.org/), [scipy](http://numpy.scipy.org/), [matplotlib](http://matplotlib.sourceforge.net/), etc), so I have to install them by myself (I don't have root permissions, either, so commands like `apt-get` or `yas...
EPD (Enthought Python Distribution) is great, but even for academics, you can only get the 32-bit version free of charge. If you intend to do anything ram-intensive, it's not really an option. Edit: This has since changed, and the 64-bit version is freely available for academic/educational use. On the other hand, the...
Why would one build supervisord inside of a buildout?
2,752,433
9
2010-05-02T04:18:09Z
2,752,851
8
2010-05-02T08:27:26Z
[ "python", "buildout", "supervisord" ]
I've seen buildout recipes that build [supervisor](http://supervisord.org) into the buildout, I suppose to control the daemons inside. However, it seems to me that one would still need something in /etc/init.d ( for example ) to run said supervisor instance on boot. So, why build supervisor inside the buildout? Why no...
When we create a buildout for a customer, we want that buildout to run on arbitrary hosting environments with minimal dependencies, all satisfiable with system packages. By including supervisord in the buildout, we eliminate the need for it to be installed system-wide and can tweak it's parameters finely, without havin...
How to open a file in the parent directory in python in AppEngine?
2,753,254
9
2010-05-02T11:09:40Z
2,753,304
15
2010-05-02T11:29:27Z
[ "python", "google-app-engine" ]
How to open a file in the parent directory in python in AppEngine? I have a python file module/mod.py with the following code ``` f = open('../data.yml') z = yaml.load(f) f.close() ``` data.yml is in the parent dir of module. The error I get is ``` IOError: [Errno 13] file not accessible: '../data.yml' ``` I am us...
The `open` function operates relative to the current process working directory, not the module it is called from. If the path must be module-relative, do this: ``` import os.path f = open(os.path.dirname(__file__) + '/../data.yml') ```
How to make shell output redirect (>) write while script is still running?
2,753,350
6
2010-05-02T11:50:45Z
2,753,361
10
2010-05-02T11:53:03Z
[ "python", "linux", "bash", "shell", "command-line" ]
I wrote a short script that never terminates. This script continuously generates output that I have to check on every now and then. I'm running it on a lab computer through SSH, and redirecting the output to a file in my public\_html folder on that machine. ``` python script.py > ~/public_html/results.txt ``` However...
You need to flush the output `sys.stdout.flush()` (or smth) if you want to see it immediately. See [this](http://stackoverflow.com/questions/230751/how-to-flush-output-of-python-print)
Has Twisted changed its dependencies?
2,753,552
3
2010-05-02T13:13:50Z
2,753,597
10
2010-05-02T13:26:40Z
[ "python", "twisted" ]
I'm currently working on a Python/Twisted project which is to be distributed and tested on Planetlab. For some reason my code was working on friday and now that I wanted to test a minor change it refuses to work at all: ``` Traceback (most recent call last): File "acn_a4/src/node.py", line 6, in <module> from tw...
One of your own files, `/home/cdecker/dev/acn/acn_a4/src/operator.py` shadows Python's builtin `operator` module. You should rename your own `operator.py` to something else. You can see the problem here: ``` File "/usr/lib/python2.5/site-packages/Twisted-10.0.0-py2.5-linux-i686.egg/twisted/python/compat.py", line 146...
How to evaluate javascript code in Python
2,753,878
7
2010-05-02T15:10:15Z
2,753,887
10
2010-05-02T15:14:32Z
[ "javascript", "python" ]
I need to fetch some result on a webpage, which use some JavaScript code to generate the part I am interesting in like following ``` eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--)d[c]=k[c]||c;k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p....
[pyv8](http://code.google.com/p/pyv8/) is a set of bindings for the V8 JavaScript Engine (Google Chrome)
How to evaluate javascript code in Python
2,753,878
7
2010-05-02T15:10:15Z
2,753,905
7
2010-05-02T15:20:02Z
[ "javascript", "python" ]
I need to fetch some result on a webpage, which use some JavaScript code to generate the part I am interesting in like following ``` eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--)d[c]=k[c]||c;k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1;};while(c--)if(k[c])p=p....
Use a [spidermonkey binding](http://code.google.com/p/python-spidermonkey/) ``` from spidermonkey import Runtime rt = Runtime() cx = rt.new_context() result = cx.eval_script(whatyoupostedabove) ```
Python logger dynamic filename
2,754,126
3
2010-05-02T16:37:19Z
2,754,216
10
2010-05-02T17:05:21Z
[ "python", "logging" ]
I want to configure my Python logger in such a way so that each instance of logger should log in a file having the same name as the name of the logger itself. e.g.: ``` log_hm = logging.getLogger('healthmonitor') log_hm.info("Testing Log") # Should log to /some/path/healthmonitor.log log_sc = logging.getLogger('scri...
How about simply wrap the handler code in a function: ``` import os def myLogger(name): logger = logging.getLogger(name) logger.setLevel(logging.DEBUG) handler = logging.FileHandler(os.path.join('/some/path/', name + '.log'), 'w') logger.addHandler(handler) return logger log_hm = myLogger('healthm...
Geocoding an address on form submission?
2,755,027
7
2010-05-02T21:16:56Z
2,755,062
8
2010-05-02T21:25:30Z
[ "python", "django", "django-forms", "geocoding" ]
Trying to wrap my head around django forms and the django way of doing things. I want to create a basic web form that allows a user to input an address and have that address geocoded and saved to a database. I created a Location model: ``` class Location(models.Model): address = models.CharField(max_length=200) ...
You can override the model's save method. I geocode the data before saving. This is using googleapi, but it can be modified accordingly. ``` import urllib def save(self): location = "%s, %s, %s, %s" % (self.address, self.city, self.state, self.zip) if not self.latitude or not self.longitude: latlng =...
str.format() raises KeyError
2,755,201
23
2010-05-02T22:06:31Z
2,755,273
45
2010-05-02T22:30:04Z
[ "python", "string-formatting" ]
The following code raises a `KeyError` exception: ``` addr_list_formatted = [] addr_list_idx = 0 for addr in addr_list: # addr_list is a list addr_list_idx = addr_list_idx + 1 addr_list_formatted.append(""" "{0}" { "gamedir" "str" "address" "{1}" } """.format(addr...
The problem are those { and } characters you have there that doesn't specify a key for the formatting. You need to double them up, so change the code to: ``` addr_list_formatted.append(""" "{0}" {{ "gamedir" "str" "address" "{1}" }} """.format(addr_list_idx, addr)) ```
Python invalid syntax with "with" statement
2,755,849
11
2010-05-03T02:30:40Z
2,755,891
18
2010-05-03T02:45:27Z
[ "python", "syntax", "syntax-error" ]
I am working on writing a simple python application for linux (maemo). However I am getting `SyntaxError: invalid syntax` on line 23: `with open(file,'w') as fileh:` The code can be seen here: <http://pastebin.com/MPxfrsAp> I can not figure out what is wrong with my code, I am new to python and the "with" statement. ...
Most likely, you are using an earlier version of Python that doesn't support the `with` statement. Here's how to do the same thing without using `with`: ``` fileh = open(file, 'w') try: # Do things with fileh here finally: fileh.close() ```
How to use regular expression in lxml xpath?
2,755,950
16
2010-05-03T03:19:10Z
2,755,959
12
2010-05-03T03:22:48Z
[ "python", "regex", "xpath", "lxml" ]
I'm using construction like this: ``` doc = parse(url).getroot() links = doc.xpath("//a[text()='some text']") ``` But I need to select all links which have text beginning with "some text", so I'm wondering is there any way to use regexp here? Didn't find anything in lxml documentation
You can use the [starts-with()](http://www.w3schools.com/xpath/xpath_functions.asp#string) function: ``` doc.xpath("//a[starts-with(text(),'some text')]") ```
How to use regular expression in lxml xpath?
2,755,950
16
2010-05-03T03:19:10Z
2,756,994
27
2010-05-03T08:53:36Z
[ "python", "regex", "xpath", "lxml" ]
I'm using construction like this: ``` doc = parse(url).getroot() links = doc.xpath("//a[text()='some text']") ``` But I need to select all links which have text beginning with "some text", so I'm wondering is there any way to use regexp here? Didn't find anything in lxml documentation
You can do this (although you don't need regular expressions for the example). Lxml supports regular expressions from the [EXSLT](http://www.exslt.org/regexp/index.html) extension functions. (see the lxml docs for the [XPath class](http://codespeak.net/lxml/xpathxslt.html#the-xpath-class), but it also works for the `xp...
OptionParser python module - multiple entries of same variable?
2,756,062
6
2010-05-03T04:09:40Z
2,756,310
12
2010-05-03T05:41:31Z
[ "python", "shell", "optionparser" ]
I'm writing a little python script to get stats from several servers or a single server, and I'm using OptionParser to parse the command line input. ``` #!/usr/bin/python import sys from optparse import OptionParser ... parser.add_option("-s", "--server", dest="server", metavar="SERVER", type="string", ...
``` import optparse parser = optparse.OptionParser() parser.add_option('-t', '--test', action='append') options, args = parser.parse_args() for i, opt in enumerate(options.test): print 'option %s: %s' % (i, opt) ```
Pass elements of a list as arguments to a function in python
2,756,116
7
2010-05-03T04:30:27Z
2,756,136
12
2010-05-03T04:39:55Z
[ "python", "list", "arguments" ]
I'm building a simple interpreter in python and I'm having trouble handling differing numbers of arguments to my functions. My current method is to get a list of the commands/arguments as follows. ``` args = str(raw_input('>> ')).split() com = args.pop(0) ``` Then to execute com, I check to see if it is in my diction...
Try ``` commands[com](*args) ``` .
Retrieving my own data via FaceBook API
2,756,237
8
2010-05-03T05:13:13Z
2,762,858
7
2010-05-04T04:42:00Z
[ "python", "facebook" ]
I am building a website for a comedy group which uses Facebook as one of their marketing platforms; one of the requirements for the new site is to display all of their Facebook events on a calendar. Currently, I am just trying to put together a Python script which can pull some data from my own Facebook account, like ...
Just posting up my notes on the successful advice, should others find this post; Per Daniel and William's advice, I obtained the right permissions using the Connect options. From William, this link explains how the Facebook connection works <https://developers.facebook.com/docs/authentication/> This section on setti...
Django Date Input Parsing?
2,756,577
6
2010-05-03T07:01:28Z
2,756,604
7
2010-05-03T07:12:08Z
[ "python", "django", "datetime" ]
I'm trying to get a date for an event from a user. The input is just a simple html text input. My main problem is that I don't know how to parse the date. If I try to pass the raw string, I get a TypeError, as expected. Does Django have any date-parsing modules?
~~Django doesn't, so to speak, by Python does.~~ It seems I'm wrong here, as uptimebox's answer shows. Say you're parsing this string: 'Wed Apr 21 19:29:07 +0000 2010' (This is from Twitter's JSON API) You'd parse it into a datetime object like this: ``` import datetime JSON_time = 'Wed Apr 21 19:29:07 +0000 2010' ...
Django Date Input Parsing?
2,756,577
6
2010-05-03T07:01:28Z
2,756,808
7
2010-05-03T07:58:39Z
[ "python", "django", "datetime" ]
I'm trying to get a date for an event from a user. The input is just a simple html text input. My main problem is that I don't know how to parse the date. If I try to pass the raw string, I get a TypeError, as expected. Does Django have any date-parsing modules?
If you are using django.forms look at [DateField.input\_formats](http://docs.djangoproject.com/en/1.1/ref/forms/fields/#datefield). This argument allows to define several date formats. DateField tries to parse raw data according to those formats in order.
Check linux distro name
2,756,737
14
2010-05-03T07:41:24Z
2,756,755
12
2010-05-03T07:45:24Z
[ "python", "linux" ]
I have to get linux distro name from python script. There is dist method in platform module: ``` import platform platform.dist() ``` But it returns ``` >>> platform.dist() ('', '', '') ``` Under my Arch Linux. Why? How can I get the name. p.s. I have to check whether the distro is debian-based. --- Upd: I found ...
[Here](http://docs.python.org/library/platform.html)'s what I found: > ``` > platform.linux_distribution > ``` > > Tries to determine the name of the > Linux OS distribution name. It says `platform.dist` is deprecated since 2.6
Check linux distro name
2,756,737
14
2010-05-03T07:41:24Z
2,756,777
8
2010-05-03T07:49:45Z
[ "python", "linux" ]
I have to get linux distro name from python script. There is dist method in platform module: ``` import platform platform.dist() ``` But it returns ``` >>> platform.dist() ('', '', '') ``` Under my Arch Linux. Why? How can I get the name. p.s. I have to check whether the distro is debian-based. --- Upd: I found ...
Works for me on Ubuntu: ('Ubuntu', '10.04', 'lucid') I then used `strace` to find out what exactly the platform module is doing to find the distro and it is this part: ``` open("/etc/lsb-release", O_RDONLY|O_LARGEFILE) = 3 fstat64(3, {st_mode=S_IFREG|0644, st_size=102, ...}) = 0 fstat64(3, {st_mode=S_IFREG|0644, st_...
List in a Python class shares the same object over 2 different instances?
2,757,116
5
2010-05-03T09:25:45Z
2,757,167
8
2010-05-03T09:36:28Z
[ "python" ]
I created a class: ``` class A: aList = [] ``` now I have function that instantiate this class and add items into the aList. note: there are 2 items ``` for item in items: a = A(); a.aList.append(item); ``` I find that the first A and the second A object has the same number of items in their aList. I w...
You have defined the list as a class attribute. Class attributes are shared by all instances of your class. When you define the list in `__init__` as `self.aList`, then the list is an attribute of your instance (self) and then everything works as you expected.
File mode for creating+reading+appending+binary
2,757,887
22
2010-05-03T12:13:59Z
2,757,941
42
2010-05-03T12:26:04Z
[ "python", "file-io" ]
I need to open a file for reading and writing. If the file is not found, it should be created. It should also be treated as a binary for Windows. Can you tell me the file mode sequence I need to use for this? I tried 'r+ab' but that doesn't create the files if they are not found. Thanks
The mode is `ab+` the `r` is implied and 'a'ppend and ('w'rite '+' 'r'ead) are redundant. Since the CPython (i.e. regular python) `file` is based on the C stdio `FILE` type, here are the relevant lines from the fopen(3) man page: * w+ Open for reading and writing. The file is created if it does not exist, otherwis...
How to embed a Python interpreter in a PyQT widget
2,758,159
25
2010-05-03T13:00:09Z
4,610,944
12
2011-01-06T01:19:55Z
[ "python", "pyqt", "embed", "ipython" ]
I want to be able to bring up an interactive python terminal from my python application. Some, but not all, variables in my program needs to be exposed to the interpreter. Currently I use a sub-classed and modified `QPlainTextEdit` and route all "commands" there to `eval` or `exec`, and keep track of a separate namesp...
Bit late I know, but I recommend the *code.InteractiveConsole* class: <http://docs.python.org/py3k/library/code.html#code.InteractiveConsole>
Rename Files in Python
2,759,067
246
2010-05-03T15:17:38Z
2,759,103
25
2010-05-03T15:22:55Z
[ "python", "file-io" ]
I'm trying to rename some files in a directory using Python. Say I have a file called `CHEESE_CHEESE_TYPE.***` and want to remove `CHEESE_` so my resulting filename would be `CHEESE_TYPE` I'm trying to use the `os.path.split` but it's not working properly. I have also considered using string manipulations, but have n...
Here's a script based on your newest comment. ``` #!/usr/bin/env python from os import rename, listdir badprefix = "cheese_" fnames = listdir('.') for fname in fnames: if fname.startswith(badprefix*2): rename(fname, fname.replace(badprefix, '', 1)) ```
Rename Files in Python
2,759,067
246
2010-05-03T15:17:38Z
2,759,130
375
2010-05-03T15:25:56Z
[ "python", "file-io" ]
I'm trying to rename some files in a directory using Python. Say I have a file called `CHEESE_CHEESE_TYPE.***` and want to remove `CHEESE_` so my resulting filename would be `CHEESE_TYPE` I'm trying to use the `os.path.split` but it's not working properly. I have also considered using string manipulations, but have n...
Do you want something like this? ``` $ ls cheese_cheese_type.bar cheese_cheese_type.foo $ python >>> import os >>> for filename in os.listdir("."): ... if filename.startswith("cheese_"): ... os.rename(filename, filename[7:]) ... >>> $ ls cheese_type.bar cheese_type.foo ```
Rename Files in Python
2,759,067
246
2010-05-03T15:17:38Z
2,759,308
8
2010-05-03T15:54:11Z
[ "python", "file-io" ]
I'm trying to rename some files in a directory using Python. Say I have a file called `CHEESE_CHEESE_TYPE.***` and want to remove `CHEESE_` so my resulting filename would be `CHEESE_TYPE` I'm trying to use the `os.path.split` but it's not working properly. I have also considered using string manipulations, but have n...
Assuming you are already in the directory, and that the "first 8 characters" from your comment hold true always. (Although "CHEESE\_" is 7 characters... ? If so, change the 8 below to 7) ``` from glob import glob from os import rename for fname in glob('*.prj'): rename(fname, fname[8:]) ```
How can I list the contents of a directory in Python?
2,759,323
67
2010-05-03T15:56:03Z
2,759,329
14
2010-05-03T15:57:17Z
[ "python", "path" ]
Can’t be hard, but I’m having a mental block.
`glob.glob` or `os.listdir` will do it.
How can I list the contents of a directory in Python?
2,759,323
67
2010-05-03T15:56:03Z
2,759,331
108
2010-05-03T15:57:30Z
[ "python", "path" ]
Can’t be hard, but I’m having a mental block.
``` import os os.listdir("path") # returns list ```
How can I list the contents of a directory in Python?
2,759,323
67
2010-05-03T15:56:03Z
2,759,335
7
2010-05-03T15:58:06Z
[ "python", "path" ]
Can’t be hard, but I’m having a mental block.
The [`os` module](http://docs.python.org/library/os.html#os.listdir) handles all that stuff. > `os.listdir(path)` > > Return a list containing the names of the entries in the directory given by path. > The list is in arbitrary order. It does not include the special entries '.' and > '..' even if they are present in th...
How can I list the contents of a directory in Python?
2,759,323
67
2010-05-03T15:56:03Z
2,759,343
27
2010-05-03T15:58:40Z
[ "python", "path" ]
Can’t be hard, but I’m having a mental block.
[One way](http://diveintopython.net/file_handling/os_module.html): ``` import os os.listdir("/home/username/www/") ``` [Another way](http://docs.python.org/library/glob.html#glob.glob): ``` glob.glob("/home/username/www/*") ``` [Examples found here](http://diveintopython.net/file_handling/os_module.html). The `glo...
How can I list the contents of a directory in Python?
2,759,323
67
2010-05-03T15:56:03Z
2,759,553
20
2010-05-03T16:29:46Z
[ "python", "path" ]
Can’t be hard, but I’m having a mental block.
`os.walk` can be used if you need recursion: ``` import os start_path = '.' # current directory for path,dirs,files in os.walk(start_path): for filename in files: print os.path.join(path,filename) ```
How to maintain long-lived python projects w.r.t. dependencies and python versions?
2,759,623
10
2010-05-03T16:41:14Z
2,759,801
10
2010-05-03T17:11:04Z
[ "python", "installation", "dependencies", "multiple-versions" ]
short version: how can I get rid of the multiple-versions-of-python nightmare ? long version: over the years, I've used several versions of python, and what is worse, several *extensions* to python (e.g. pygame, pylab, wxPython...). Each time it was on a different setup, with different OSes, sometimes different archit...
I solve this using [virtualenv](http://pypi.python.org/pypi/virtualenv). I sympathise with wanting to avoid further layers of nightmare abstraction, but `virtualenv` is actually amazingly clean and simple to use. You literally do this (command line, Linux): ``` virtualenv my_env ``` This creates a new python binary a...
how to kill (or avoid) zombie processes with subprocess module
2,760,652
33
2010-05-03T19:29:32Z
2,761,237
13
2010-05-03T21:11:05Z
[ "python", "subprocess" ]
When I kick off a python script from within another python script using the subprocess module, a zombie process is created when the subprocess "completes". I am unable to kill this subprocess unless I kill my parent python process. Is there a way to kill the subprocess without killing the parent? I know I can do this ...
Not using `Popen.communicate()` or `call()` will result in a zombie process. If you don't need the output of the command, you can use `subprocess.call()`: ``` >>> import subprocess >>> subprocess.call(['grep', 'jdoe', '/etc/passwd']) 0 ``` If the output is important, you should use `Popen()` and `communicate()` to g...
how to kill (or avoid) zombie processes with subprocess module
2,760,652
33
2010-05-03T19:29:32Z
2,761,781
12
2010-05-03T23:01:40Z
[ "python", "subprocess" ]
When I kick off a python script from within another python script using the subprocess module, a zombie process is created when the subprocess "completes". I am unable to kill this subprocess unless I kill my parent python process. Is there a way to kill the subprocess without killing the parent? I know I can do this ...
A zombie process is not a real process; it's just a remaining entry in the process table until the parent process requests the child's return code. The actual process has ended and requires no other resources but said process table entry. We probably need more information about the processes you run in order to actual...
how to kill (or avoid) zombie processes with subprocess module
2,760,652
33
2010-05-03T19:29:32Z
12,956,839
14
2012-10-18T14:20:36Z
[ "python", "subprocess" ]
When I kick off a python script from within another python script using the subprocess module, a zombie process is created when the subprocess "completes". I am unable to kill this subprocess unless I kill my parent python process. Is there a way to kill the subprocess without killing the parent? I know I can do this ...
If you delete the subprocess object, using **del** to force garbage collection, that will cause the subprocess object to be deleted and then the defunct processes will go away without terminating your interpreter. You can try this out in the python command line interface first.
Problem with list slice syntax in python
2,761,003
6
2010-05-03T20:29:43Z
2,761,081
10
2010-05-03T20:47:55Z
[ "python", "syntax", "slice" ]
The extended indexing syntax is mentioned in python's doc. ``` slice([start], stop[, step]) ``` Slice objects are also generated when extended indexing syntax is used. For example: `a[start:stop:step]` or `a[start:stop, i]`. See [`itertools.islice()`](http://docs.python.org/library/itertools.html#itertools.islice) fo...
`a[start:stop,i]` calls the method `a.__getitem__(slice(start,stop,None),i)`. This raises a TypeError if `a` is a list, but it is valid and useful notation if `a` is a numpy array. In fact, I believe the developers of Numpy asked the developers of Python to extended valid Python slicing notation precisely so that nump...
Are classes necessary for creating methods (defs) in Python?
2,761,145
3
2010-05-03T20:57:53Z
2,761,154
12
2010-05-03T20:58:52Z
[ "python" ]
Are classes necessary for creating methods (defs) in Python?
No. However, `def`'s which aren't part of a class are usually called functions, not methods - but they are exactly the same thing, aside from not being associated with a class. ``` def myFunction(arg1, arg2): # do something here ```
Error Converting PIL B&W images to Numpy Arrays
2,761,645
3
2010-05-03T22:30:41Z
2,767,545
7
2010-05-04T17:33:06Z
[ "python", "numpy", "python-imaging-library" ]
I am getting weird errors when I try to convert a black and white PIL image to a numpy array. An example of the code I am working with is below. ``` if image.mode != '1': image = image.convert('1') #convert to B&W data = np.array(image) #Have also tried np.asarray(image) n_lines = data.shape[0] #nu...
I believe you've found a bug in PIL! (or possibly in numpy, but I'd wager it's on the PIL side of things...) @c's answer above gives one workaround (use im.getdata()), though I'm not sure why numpy.asarry(image) is segfaulting for him... (Old version of PIL and/or numpy, maybe?) It works for me, but produces gibberish...
Python: get default gateway for a local interface/ip address in linux
2,761,829
9
2010-05-03T23:11:47Z
6,556,951
14
2011-07-02T12:21:30Z
[ "python", "linux", "routing", "networking" ]
On Linux, how can I find the default gateway for a local ip address/interface using python? I saw the question "How to get internal IP, external IP and default gateway for UPnP", but the accepted solution only shows how to get the local IP address for a network interface on windows. Thanks.
For those people who don't want an extra dependency and don't like calling subprocesses, here's how you do it yourself by reading `/proc/net/route` directly: ``` import socket, struct def get_default_gateway_linux(): """Read the default gateway directly from /proc.""" with open("/proc/net/route") as fh: ...
Python: get default gateway for a local interface/ip address in linux
2,761,829
9
2010-05-03T23:11:47Z
24,026,579
7
2014-06-03T23:21:32Z
[ "python", "linux", "routing", "networking" ]
On Linux, how can I find the default gateway for a local ip address/interface using python? I saw the question "How to get internal IP, external IP and default gateway for UPnP", but the accepted solution only shows how to get the local IP address for a network interface on windows. Thanks.
For completeness (and to expand on alastair's answer), here is an example that uses "netifaces" (tested under Ubuntu 10.04, but this should be portable): ``` $ sudo easy_install netifaces Python 2.6.5 (r265:79063, Oct 1 2012, 22:04:36) ... $ ipython ... In [8]: import netifaces In [9]: gws=netifaces.gateways() In [10...
Format all elements of a list
2,762,058
4
2010-05-04T00:22:26Z
2,762,063
8
2010-05-04T00:24:16Z
[ "python", "list" ]
I want to print a list of numbers, but I want to format each member of the list before it is printed. For example, `theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]` I want the following output printed given the above list as an input: `[1.34, 7.42, 6.97, 4.55]` For any one member of the list, I know I ca...
If you just want to print the numbers you can use a simple loop: ``` for member in theList: print "%.2f" % member ``` If you want to store the result for later you can use a list comprehension: ``` formattedList = ["%.2f" % member for member in theList] ``` You can then print this list to get the output as in y...
How should I check that a given argument is a datetime.date object?
2,762,265
11
2010-05-04T01:31:10Z
2,762,296
21
2010-05-04T01:39:27Z
[ "python", "datetime" ]
I'm currently using an `assert` statement with `isinstance`. Because `datetime` is a subclass of `date`, I also need to check that it isn't an instance of `datetime`. Surely there's a better way? ``` from datetime import date, datetime def some_func(arg): assert isinstance(arg, date) and not isinstance(arg, datet...
I don't understand your motivation for rejecting instances of subclasses (given that by definition they support all the behavior the superclass supports!), but if that's really what you insist on doing, then: ``` if type(arg) is not datetime.date: raise TypeError('arg must be a datetime.date, not a %s' % type(arg)...
Finding maximum of a list of lists by sum of elements in Python
2,763,015
14
2010-05-04T05:32:29Z
2,763,021
39
2010-05-04T05:35:08Z
[ "python", "list", "haskell", "higher-order-functions" ]
What's the idiomatic way to do [maximumBy](http://haskell.org/ghc/docs/6.12.1/html/libraries/base-4.2.0.0/Data-Foldable.html#v%3amaximumBy) (higher order function taking a comparison function for the test), on a list of lists, where the comparison we want to make is the sum of the list, in Python? Here's a Haskell imp...
Since Python 2.5 you can use [max](http://docs.python.org/library/functions.html#max) with a key parameter: ``` >>> max(a, key=sum) [4, 5, 6] ```
Jythonc missing
2,763,129
10
2010-05-04T06:01:57Z
2,763,205
7
2010-05-04T06:20:28Z
[ "python", "jython" ]
I just installed Jython 2.5.1. I want to convert my Python file into Java class file and it is instructed on the website to use the jythonc command-line tool but I can't find it. Does anyone know where I could find it? Basically what i was trying to accomplish is to get my Python code running client-side in a browser ...
Jythonc was removed in Jython 2.2 and is no longer supported. The official way to embed Jython code in Java is to create an instance of the interpreter to run the Jython code directly. There is an article on this [here](http://wiki.python.org/jython/JythonMonthly/Articles/September2006/1). Personally I preferred the j...
Jythonc missing
2,763,129
10
2010-05-04T06:01:57Z
2,766,658
18
2010-05-04T15:29:06Z
[ "python", "jython" ]
I just installed Jython 2.5.1. I want to convert my Python file into Java class file and it is instructed on the website to use the jythonc command-line tool but I can't find it. Does anyone know where I could find it? Basically what i was trying to accomplish is to get my Python code running client-side in a browser ...
You can still compile your python-code to class-files: ``` import compileall; compileall.compile_dir('Lib'); # to compile yor Lib-Dir ``` should work with 2.5 jython i use it to create class-files to put in jars :-)
Python New-style Classes and the Super Function
2,763,335
2
2010-05-04T06:47:07Z
2,763,374
14
2010-05-04T06:55:38Z
[ "python", "class" ]
This is not the result I expect to see: ``` class A(dict): def __init__(self, *args, **kwargs): self['args'] = args self['kwargs'] = kwargs class B(A): def __init__(self, *args, **kwargs): super(B, self).__init__(args, kwargs) print 'Instance A:', A('monkey', banana=True) #Instance A:...
Try this instead: ``` super(B, self).__init__(*args, **kwargs) ``` Since the init function for A is expecting actual args/kwargs (and not just two arguments), you have to actually pass it the unpacked versions of args/kwargs so that they'll be repacked properly. Otherwise, the already-packed list of args and dict of...
How to print the sign + of a digit for positive numbers in Python
2,763,432
18
2010-05-04T07:07:02Z
2,763,445
30
2010-05-04T07:09:32Z
[ "python", "string-formatting" ]
Is there a better way to print the + sign of a digit on positive numbers? ``` integer1 = 10 integer2 = 5 sign = '' total = integer1-integer2 if total > 0: sign = '+' print 'Total:'+sign+str(total) ``` 0 should return 0 without +.
``` >>> print "%+d" % (-1) -1 >>> >>> print "%+d" % (1) +1 >>> print "%+d" % (0) +0 >>> ``` Here is [the documentation](http://docs.python.org/library/stdtypes.html#string-formatting-operations). \*\* Update\*\* If for whatever reason you can't use the `%` operator, you don't need a function: ``` >>> total = -10; pr...
How to print the sign + of a digit for positive numbers in Python
2,763,432
18
2010-05-04T07:07:02Z
2,763,589
31
2010-05-04T07:38:35Z
[ "python", "string-formatting" ]
Is there a better way to print the + sign of a digit on positive numbers? ``` integer1 = 10 integer2 = 5 sign = '' total = integer1-integer2 if total > 0: sign = '+' print 'Total:'+sign+str(total) ``` 0 should return 0 without +.
Use the [new string format](http://docs.python.org/library/string.html#formatstrings) ``` >>> '{0:+} number'.format(1) '+1 number' >>> '{0:+} number'.format(-1) '-1 number' >>> '{0:+} number'.format(-37) '-37 number' >>> '{0:+} number'.format(37) '+37 number' # As the questions ask for it, little trick for not printin...
Selenium Webdriver example in Python
2,763,610
8
2010-05-04T07:43:23Z
2,763,685
10
2010-05-04T07:57:13Z
[ "python", "selenium", "webdriver" ]
I had written a scipt in Java with Webdriver and it worked fine and below is the code for the sample ``` import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverBackedSelenium; import org.openq...
Did you read the instructions at [*python bindings for WebDriver*](http://code.google.com/p/selenium/wiki/PythonBindings) ? [`example2.py`](http://code.google.com/p/selenium/source/browse/trunk/py/test/selenium/webdriver/common/example2.py) is clear, although not a direct translation of your code: ``` import unittest...
How to replace only part of the match with python re.sub
2,763,750
23
2010-05-04T08:12:28Z
2,763,763
58
2010-05-04T08:15:15Z
[ "python", "regex" ]
I need to match two cases by one reg expression and do replacement 'long.file.name.jpg' -> 'long.file.name\_**suff**.jpg' 'long.file.name\_**a**.jpg' -> 'long.file.name\_**suff**.jpg' I'm trying to do the following ``` re.sub('(\_a)?\.[^\.]*$' , '_suff.',"long.file.name.jpg") ``` But this is cut the extension '.jp...
Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text. ``` re.sub(r'(\_a)?\.([^\.]*)$' , r'_suff.\2',"long.file.name.jpg") ```
How to replace only part of the match with python re.sub
2,763,750
23
2010-05-04T08:12:28Z
2,763,772
8
2010-05-04T08:17:02Z
[ "python", "regex" ]
I need to match two cases by one reg expression and do replacement 'long.file.name.jpg' -> 'long.file.name\_**suff**.jpg' 'long.file.name\_**a**.jpg' -> 'long.file.name\_**suff**.jpg' I'm trying to do the following ``` re.sub('(\_a)?\.[^\.]*$' , '_suff.',"long.file.name.jpg") ``` But this is cut the extension '.jp...
``` re.sub(r'(?:_a)?\.([^.]*)$', r'_suff.\1', "long.file.name.jpg") ```
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
2,764,017
129
2010-05-04T09:03:30Z
2,764,089
43
2010-05-04T09:16:50Z
[ "python", "boolean", "equality", "language-specifications" ]
Is it guaranteed that `False == 0` and `True == 1`, in Python? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing and, likely, future ones)? ``` 0 == False # True 1 == True # True ['zero', 'one'][False] # is 'zero' `...
Link to the PEP discussing the new bool type in Python 2.3: <http://www.python.org/dev/peps/pep-0285/>. When converting a bool to an int, the integer value is always 0 or 1, but when converting an int to a bool, the boolean value is True for all integers except 0. ``` >>> int(False) 0 >>> int(True) 1 >>> bool(5) True...
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
2,764,017
129
2010-05-04T09:03:30Z
2,764,099
96
2010-05-04T09:18:01Z
[ "python", "boolean", "equality", "language-specifications" ]
Is it guaranteed that `False == 0` and `True == 1`, in Python? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing and, likely, future ones)? ``` 0 == False # True 1 == True # True ['zero', 'one'][False] # is 'zero' `...
In Python 2.x this is *not* guaranteed as it is possible for `True` and `False` to be reassigned. However, even if this happens, boolean True and boolean False are still properly returned for comparisons. In Python 3.x `True` and `False` are keywords and will always be equal to `1` and `0`. Under normal circumstances...
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?
2,764,017
129
2010-05-04T09:03:30Z
2,764,161
13
2010-05-04T09:33:16Z
[ "python", "boolean", "equality", "language-specifications" ]
Is it guaranteed that `False == 0` and `True == 1`, in Python? For instance, is it in any way guaranteed that the following code will always produce the same results, whatever the version of Python (both existing and, likely, future ones)? ``` 0 == False # True 1 == True # True ['zero', 'one'][False] # is 'zero' `...
In Python 2.x, it is not guaranteed at all: ``` >>> False = 5 >>> 0 == False False ``` So it could change. In Python 3.x, True, False, and None are [reserved words](http://docs.python.org/release/3.0.1/whatsnew/3.0.html#changed-syntax), so the above code would not work. In general, with booleans you should assume th...
Is there a neater way to get the first occurrence of something?
2,764,328
2
2010-05-04T10:00:58Z
2,764,422
7
2010-05-04T10:18:43Z
[ "python", "iterator", "itertools" ]
I have a list which contains a number of things: ``` lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar'] ``` I'd like to get the first item in the list that fulfils a predicate, say `len(item) > 2`. Is there a neater way to do it than itertools' dropwhile and next? ``` first = next(itertools.dropwhile(lambda x: len(x) <...
``` >>> lista = ['a', 'b', 'foo', 'c', 'd', 'e', 'bar'] >>> next(i for i in lista if len(i) > 2) 'foo' ```
Python: get windows OS version and architecture
2,764,356
5
2010-05-04T10:05:35Z
2,770,780
7
2010-05-05T05:14:38Z
[ "python", "windows", "cpu-architecture" ]
First of all, I don't think this question is a duplicate of <http://stackoverflow.com/questions/2208828/detect-64bit-os-windows-in-python> because imho it has not been thoroughly answered. The only approaching answer is: > Use `sys.getwindowsversion()` or the existence of PROGRAMFILES(X86) (`if 'PROGRAMFILES(X86)...
These variables show your current runtime status on windows: ``` @rem Test environment using this table: @rem @rem Environment Variable 32bit Native 64bit Native WOW64 @rem PROCESSOR_ARCHITECTURE x86 AMD64 x86 @rem PROCESSOR_ARCHITEW6432 undefined undefined AMD64 @...
Not enough arguments for format string
2,764,520
11
2010-05-04T10:36:52Z
2,764,633
17
2010-05-04T10:56:31Z
[ "python", "format" ]
I have such code in Python: ``` def send_start(self, player): for p in self.players: player["socket"].send_cmd('<player id="%s" name="%s" you="%s" avatar="*.png" bank="%s" />'%(self.players.index(p)+1, p['name'], int(player["pid"]==p["pid"]), 0)) player["socket"].send_cmd('<game playerid="%s" />'%(self...
Your code would fail if `self.turnnow` is an empty tuple: ``` >>> var = () >>> print "%s" % (var) Traceback (most recent call last): File "<stdin>", line 2, in <module> TypeError: not enough arguments for format string >>> print "%s" % (var,) () ``` This is because a parenthesized expression in Python does *not* au...
Get current URL in Python
2,764,586
20
2010-05-04T10:47:42Z
2,764,822
46
2010-05-04T11:27:31Z
[ "python", "google-app-engine" ]
How would i get the current URL with Python, I need to grab the current URL so i can check it for query strings e.g ``` requested_url = "URL_HERE" url = urlparse(requested_url) if url[4]: params = dict([part.split('=') for part in url[4].split('&')]) ``` also this is running in Google App Engine
Try this: ``` self.request.url ``` Also, if you just need the querystring, this will work: ``` self.request.query_string ``` And, lastly, if you know the querystring variable that you're looking for, you can do this: ``` self.request.get("name-of-querystring-variable") ```
what is the correct way to close a socket in python 2.6?
2,765,152
3
2010-05-04T12:22:07Z
2,765,227
9
2010-05-04T12:31:47Z
[ "python", "sockets" ]
i have a simple server/client. and i am using the netcat as the client to test the server. if i stop the server before the client exit, i will not be able to start the server again for a while and i go this error: " [Errno 98] Address already in use " but if i close the client first, then the server stops, i will not ...
You're closing the socket just fine. However, the socket continues to use resources for a few minutes after the socket closes, so that if the remote end missed a packet the packet can be re-sent. You should be able to work around it by calling the following before you call `bind`: ``` s.setsockopt(socket.SOL_SOCKET, ...
Add windows commands in python
2,765,405
3
2010-05-04T12:56:33Z
2,765,445
8
2010-05-04T13:01:13Z
[ "python", "shutdown" ]
Can anyone tell me how to add the shutdown.exe to python and how . i also want to set and variables like shutdown.exe -f -s -t 60
The [subprocess module](http://docs.python.org/library/subprocess.html) allows you to run external programs from inside python. In particular [subprocess.call](http://docs.python.org/library/subprocess.html#subprocess.call) is a really convenient way to run programs where you don't care about anything other than the re...
error in writing data into file in python
2,765,617
2
2010-05-04T13:21:28Z
2,765,650
10
2010-05-04T13:25:46Z
[ "python", "file-io" ]
``` a='aa' >>> f=open("key.txt","w") >>> s=str(a) >>> f.write(s) ``` and still the key.txt file remains blank .. why?
Use ``` f.flush() ``` to flush the write to disk. Or, if you are done using `f`, you could use ``` f.close() ``` to flush and close the file.
Python: See if one set contains another entirely?
2,765,892
26
2010-05-04T13:55:39Z
2,765,908
41
2010-05-04T13:57:41Z
[ "python", "set" ]
Is there a fast way to check if one set entirely contains another? Something like: ``` >>>[1, 2, 3].containsAll([2, 1]) True >>>[1, 2, 3].containsAll([3, 5, 9]) False ```
Those are lists, but if you really mean sets you can use the issubset method. ``` >>> s = set([1,2,3]) >>> t = set([1,2]) >>> t.issubset(s) True >>> s.issuperset(t) True ``` For a list, you will not be able to do better than checking each element.
Python: See if one set contains another entirely?
2,765,892
26
2010-05-04T13:55:39Z
2,765,967
9
2010-05-04T14:06:34Z
[ "python", "set" ]
Is there a fast way to check if one set entirely contains another? Something like: ``` >>>[1, 2, 3].containsAll([2, 1]) True >>>[1, 2, 3].containsAll([3, 5, 9]) False ```
For completeness: this is equivalent to `issubset` (although arguably a bit less explicit/readable): ``` >>> set([1,2,3]) >= set([2,1]) True >>> set([1,2,3]) >= set([3,5,9]) False ```
Possible to use pyplot without DISPLAY?
2,766,149
13
2010-05-04T14:27:05Z
2,766,194
21
2010-05-04T14:32:33Z
[ "python", "x11", "matplotlib" ]
I'm working remotely on a machine that's pretty restrictive. I can't install any software, and it won't accept my X11 session, so I have no display. The machine currently has pylab installed, and I'd like to use it to plot something and then save it for viewing on another computer. However, it seems there's no way to e...
Use another backend, for example Agg or SVG: ``` import matplotlib matplotlib.use('Agg') ... matplotlib.savefig('out.png') ```
When to use "property" builtin: auxiliary functions and generators
2,766,601
8
2010-05-04T15:21:44Z
2,766,943
14
2010-05-04T16:07:33Z
[ "python", "properties" ]
I recently discovered Python's [`property` built-in](http://docs.python.org/library/functions.html#property), which disguises class method getters and setters as a class's property. I'm now being tempted to use it in ways that I'm pretty sure are inappropriate. Using the `property` keyword is clearly the right thing t...
* When you have a normal attribute and getting and/or setting it makes sense for a class's user, expose the attribute directly. One big reason that public members are anathema in some languages is that if you need to do something more complex later you would need an API change; in Python you can just define a property....
Including global package into a virtualenv that has been created with --no-site-packages
2,767,382
16
2010-05-04T17:11:29Z
3,399,920
11
2010-08-03T19:08:13Z
[ "python", "virtualenv", "easy-install", "pip" ]
I'd usually prefer to create virtualenvs with --no-site-packages option for more isolation, and also because default python global packages includes quite a lot of packages, and usually most of them are not needed. However I'd still want to keep a few select packages in global, like PIL or psycopg2. Is there a good way...
If you're using [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/) and you might be able to use the [postmkvirtualenv](http://www.doughellmann.com/docs/virtualenvwrapper/scripts.html#scripts-postmkvirtualenv) script to automatically create symlinks in the new virtualenv sitepackages directory....