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
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
116
2008-11-29T01:24:09Z
327,009
13
2008-11-29T01:28:24Z
[ "python", "performance" ]
I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? **UPDATE** This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido...
How many square roots are you really performing? Are you trying to write some 3D graphics engine in Python? If not, then why go with code which is cryptic over code that is easy to read? The time difference is would be less than anybody could notice in just about any application I could forsee. I really don't mean to p...
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
116
2008-11-29T01:24:09Z
327,011
57
2008-11-29T01:32:11Z
[ "python", "performance" ]
I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? **UPDATE** This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido...
As per comments, I've updated the code: ``` import time import math def timeit1(): s = time.time() for i in xrange(750000): z=i**.5 print "Took %f seconds" % (time.time() - s) def timeit2(arg=math.sqrt): s = time.time() for i in xrange(750000): z=arg(i) print "Took %f seconds"...
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
116
2008-11-29T01:24:09Z
327,024
8
2008-11-29T01:45:49Z
[ "python", "performance" ]
I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? **UPDATE** This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido...
In these micro-benchmarks, math.sqrt will be slower, because of the slight time it takes to lookup the sqrt in the math namespace. You can improve it slightly with ``` from math import sqrt ``` Even then though, running a few variations through timeit, show a slight (4-5%) performance advantage for "x\*\*.5" intere...
Which is faster in Python: x**.5 or math.sqrt(x)?
327,002
116
2008-11-29T01:24:09Z
327,048
13
2008-11-29T02:16:47Z
[ "python", "performance" ]
I've been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power? **UPDATE** This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works? I sent Guido...
* first rule of optimization: *don't do it* * second rule: *don't do it*, yet Here's some timings (Python 2.5.2, Windows): ``` $ python -mtimeit -s"from math import sqrt; x = 123" "x**.5" 1000000 loops, best of 3: 0.445 usec per loop $ python -mtimeit -s"from math import sqrt; x = 123" "sqrt(x)" 1000000 loops, best ...
Multiple Django Admin Sites on one Apache... When I log into one I get logged out of the other
327,142
3
2008-11-29T04:01:45Z
327,307
7
2008-11-29T07:27:35Z
[ "python", "django", "admin" ]
I have two Django projects and applications running on the same Apache installation. Both projects and both applications have the same name, for example myproject.myapplication. They are each in separately named directories so it looks like .../dir1/myproject/myapplication and .../dir2/myproject/myapplication. Everyth...
Set the [SESSION\_COOKIE\_DOMAIN](http://docs.djangoproject.com/en/dev/topics/http/sessions/#session-cookie-domain) option. You need to set the domain for each of your sites so the cookies don't override each other. You can also use SESSION\_COOKIE\_NAME to make the cookie names different for each site.
in python, is there a one line pythonic way to get a list of keys from a dictionary in sorted order?
327,191
2
2008-11-29T05:03:14Z
327,210
17
2008-11-29T05:20:37Z
[ "python", "iterator", "syntactic-sugar" ]
The list sort method is a modifier function that returns None. So if I want to iterate through all of the keys in a dictionary I cannot do: ``` for k in somedictionary.keys().sort(): dosomething() ``` instead, i must: ``` keys = somedictionary.keys() keys.sort() for k in keys: dosomething() ``` Is there a ...
``` for k in sorted(somedictionary.keys()): doSomething(k) ``` Note that you can also get all of the keys and values sorted by keys like this: ``` for k, v in sorted(somedictionary.iteritems()): doSomething(k, v) ```
Memory Efficient Alternatives to Python Dictionaries
327,223
32
2008-11-29T05:33:26Z
327,295
26
2008-11-29T07:06:58Z
[ "python", "memory", "data-structures" ]
In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2]...
Some measurements. I took 10MB of free e-book text and computed trigram frequencies, producing a 24MB file. Storing it in different simple Python data structures took this much space in kB, measured as RSS from running ps, where d is a dict, keys and freqs are lists, and a,b,c,freq are the fields of a trigram record: ...
Memory Efficient Alternatives to Python Dictionaries
327,223
32
2008-11-29T05:33:26Z
327,313
8
2008-11-29T07:36:31Z
[ "python", "memory", "data-structures" ]
In one of my current side projects, I am scanning through some text looking at the frequency of word triplets. In my first go at it, I used the default dictionary three levels deep. In other words, topDictionary[word1][word2][word3] returns the number of times these words appear in the text, topdictionary[word1][word2]...
Use tuples. Tuples can be keys to dictionaries, so you don't need to nest dictionaries. ``` d = {} d[ word1, word2, word3 ] = 1 ``` Also as a plus, you could use defaultdict * so that elements that don't have entries always return 0 * and so that u can say `d[w1,w2,w3] += 1` without checking if the key already exi...
How are Python's Built In Dictionaries Implemented
327,311
146
2008-11-29T07:35:31Z
327,378
8
2008-11-29T09:22:46Z
[ "python", "data-structures", "dictionary" ]
Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
[Pure Python Dictionary Implementation](http://pybites.blogspot.com/2008/10/pure-python-dictionary-implementation.html) > For those curious about how CPython's dict implementation works, I've written a Python implementation using the same algorithms.
How are Python's Built In Dictionaries Implemented
327,311
146
2008-11-29T07:35:31Z
334,953
8
2008-12-02T18:29:16Z
[ "python", "data-structures", "dictionary" ]
Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
Here's a link to the [actual implementation](http://svn.python.org/view/python/trunk/Objects/dictobject.c?rev=66801&view=auto "dict implementation") in the python SVN repository. That should be the most definite answer.
How are Python's Built In Dictionaries Implemented
327,311
146
2008-11-29T07:35:31Z
2,996,689
37
2010-06-08T11:00:37Z
[ "python", "data-structures", "dictionary" ]
Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
Python Dictionaries use [Open addressing](http://en.wikipedia.org/wiki/Hash_table#Open_addressing) ([reference inside Beautiful code](http://books.google.co.in/books?id=gJrmszNHQV4C&lpg=PP1&hl=sv&pg=PA298#v=onepage&q&f=false)) **NB!** *Open addressing*, a.k.a *closed hashing* should, as noted in Wikipedia, not be conf...
How are Python's Built In Dictionaries Implemented
327,311
146
2008-11-29T07:35:31Z
8,682,049
27
2011-12-30T17:15:04Z
[ "python", "data-structures", "dictionary" ]
Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
At PyCon 2010, Brandon Craig Rhodes gave an [excellent talk](http://www.youtube.com/watch?v=C4Kc8xzcA68) about the Python dictionary. It provides a great overview of the dictionary implementation with examples and visuals. If you have 45 minutes (or even just 15), I would recommend watching the talk before proceeding t...
How are Python's Built In Dictionaries Implemented
327,311
146
2008-11-29T07:35:31Z
9,022,835
241
2012-01-26T17:52:00Z
[ "python", "data-structures", "dictionary" ]
Does anyone know how the built in dictionary type for python is implemented? My understanding is that it is some sort of hash table, but I haven't been able to find any sort of definitive answer.
Here is everything about Python dicts that I was able to put together (probably more than anyone would like to know; but the answer is comprehensive). * Python dictionaries are implemented as **hash tables**. * Hash tables must allow for **hash collisions** i.e. even if two distinct keys have the same hash value, the ...
storing unbound python functions in a class object
327,483
11
2008-11-29T12:21:47Z
327,488
15
2008-11-29T12:28:33Z
[ "python", "function" ]
I'm trying to do the following in python: In a file called foo.py: ``` # simple function that does something: def myFunction(a,b,c): print "call to myFunction:",a,b,c # class used to store some data: class data: fn = None # assign function to the class for storage. data.fn = myFunction ``` And then in a file c...
``` data.fn = staticmethod(myFunction) ``` should do the trick.
Storing and updating lists in Python dictionaries: why does this happen?
327,534
19
2008-11-29T13:40:05Z
327,548
57
2008-11-29T13:46:42Z
[ "python", "dictionary", "list" ]
I have a list of data that looks like the following: ``` // timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 ``` ... and I want to make this look like: ``` 0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) ``` My plan was to use a dictionary, where the value of t is the key f...
Let's look at ``` d[t].append(c) ``` What is the value of `d[t]`? Try it. ``` d = {} t = 0 d[t] ``` What do you get? Oh. There's nothing in `d` that has a key of `t`. Now try this. ``` d[t] = [] d[t] ``` Ahh. Now there's something in `d` with a key of `t`. There are several things you can do. 1. Use example 2....
Storing and updating lists in Python dictionaries: why does this happen?
327,534
19
2008-11-29T13:40:05Z
327,575
9
2008-11-29T14:28:09Z
[ "python", "dictionary", "list" ]
I have a list of data that looks like the following: ``` // timestep,x_position,y_position 0,4,7 0,2,7 0,9,5 0,6,7 1,2,5 1,4,7 1,9,0 1,6,8 ``` ... and I want to make this look like: ``` 0, (4,7), (2,7), (9,5), (6,7) 1, (2,5), (4,7), (9,0), (6.8) ``` My plan was to use a dictionary, where the value of t is the key f...
I think you want to use setdefault. It's a bit weird to use but does exactly what you need. ``` d.setdefault(t, []).append(c) ``` The `.setdefault` method will return the element (in our case, a list) that's bound to the dict's key `t` if that key exists. If it doesn't, it will bind an empty list to the key `t` and r...
Suggestion to implement a text Menu without switch case
327,597
2
2008-11-29T15:01:28Z
327,741
12
2008-11-29T17:32:04Z
[ "python" ]
I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python? Thanks
You might do something like this: ``` def action1(): pass # put a function here def action2(): pass # blah blah def action3(): pass # and so on def no_such_action(): pass # print a message indicating there's no such action def main(): actions = {"foo": action1, "bar": action2, "baz": action3} ...
Read the last lineof the file
327,776
3
2008-11-29T18:03:03Z
327,825
9
2008-11-29T18:34:42Z
[ "python" ]
Imagine I have a file with Xpto,50,30,60 Xpto,a,v,c Xpto,1,9,0 Xpto,30,30,60 that txt file can be appended a lot of times and when I open the file I want only to get the values of the last line of the txt file... How can i do that on python? reading the last line? Thanks
I think my answer from the [last time this came up](http://stackoverflow.com/questions/260273/most-efficient-way-to-search-the-last-x-lines-of-a-file-in-python) was sadly overlooked. :-) > If you're on a unix box, > `os.popen("tail -10 " + > filepath).readlines()` will probably > be the fastest way. Otherwise, it > de...
Django equivalent for count and group by
327,807
82
2008-11-29T18:19:28Z
327,987
56
2008-11-29T20:44:21Z
[ "python", "django" ]
I have a model that looks like this: ``` class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) ``` I want select count (just the count) of items for each category, so in SQL it would be ...
(**Update**: Full ORM aggregation support is now included in [Django 1.1](http://docs.djangoproject.com/en/dev/releases/1.1/#aggregate-support). True to the below warning about using private APIs, the method documented here no longer works in post-1.1 versions of Django. I haven't dug in to figure out why; if you're on...
Django equivalent for count and group by
327,807
82
2008-11-29T18:19:28Z
1,317,837
120
2009-08-23T05:21:09Z
[ "python", "django" ]
I have a model that looks like this: ``` class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) ``` I want select count (just the count) of items for each category, so in SQL it would be ...
Here, as I just discovered, is how to do this with the Django 1.1 aggregation API: ``` from django.db.models import Count theanswer = Item.objects.values('category').annotate(Count('category')) ```
Django equivalent for count and group by
327,807
82
2008-11-29T18:19:28Z
1,341,667
51
2009-08-27T15:02:17Z
[ "python", "django" ]
I have a model that looks like this: ``` class Category(models.Model): name = models.CharField(max_length=60) class Item(models.Model): name = models.CharField(max_length=60) category = models.ForeignKey(Category) ``` I want select count (just the count) of items for each category, so in SQL it would be ...
Since I was a little confused about how grouping in Django 1.1 works I thought I'd elaborate here on how exactly you go about using it. First, to repeat what Michael said: > Here, as I just discovered, is how to do this with the Django 1.1 aggregation API: > > ``` > from django.db.models import Count > theanswer = Ite...
Create a List that contain each Line of a File
328,059
13
2008-11-29T21:55:53Z
328,068
38
2008-11-29T22:03:34Z
[ "python" ]
I'm trying to open a file and create a list with each line read from the file. ``` i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List ``` But this sample code gives me an error because of the `i+=1` saying that `index is out of range`. What's my problem here? How can I w...
It's a lot easier than that: ``` List = open("filename.txt").readlines() ``` This returns a list of each line in the file.
Create a List that contain each Line of a File
328,059
13
2008-11-29T21:55:53Z
31,923,407
10
2015-08-10T15:22:21Z
[ "python" ]
I'm trying to open a file and create a list with each line read from the file. ``` i=0 List=[""] for Line in inFile: List[i]=Line.split(",") i+=1 print List ``` But this sample code gives me an error because of the `i+=1` saying that `index is out of range`. What's my problem here? How can I w...
I did it this way ``` lines_list = open('file.txt').read().splitlines() ``` Every line comes with its end of line characters (\n\r); this way the characters are removed.
How to make a surface with a transparent background in pygame
328,061
18
2008-11-29T21:58:40Z
328,067
20
2008-11-29T22:02:45Z
[ "python", "transparency", "pygame" ]
Can someone give me some example code that creates a surface with a transparent background in pygame?
This should do it: ``` image = pygame.Surface([640,480], pygame.SRCALPHA, 32) image = image.convert_alpha() ``` Make sure that the color depth (32) stays explicitly set else this will not work.
How to make a surface with a transparent background in pygame
328,061
18
2008-11-29T21:58:40Z
353,739
8
2008-12-09T18:24:22Z
[ "python", "transparency", "pygame" ]
Can someone give me some example code that creates a surface with a transparent background in pygame?
You can also give it a colorkey, much like GIF file transparency. This is the most common way to make sprites. The original bitmap has the artwork, and has a certain color as background that will not be drawn, which is the colorkey: ``` surf.set_colorkey((255,0,255)) // Sets the colorkey to that hideous purple ``` Su...
How can you determine a point is between two other points on a line segment?
328,107
67
2008-11-29T22:37:13Z
328,110
24
2008-11-29T22:40:05Z
[ "python", "math", "geometry" ]
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point. How can you determine if another point c is on the line segment defined by a and b? I use python most, but examples in any language would be helpful.
Check if the cross product of `b-a` and `c-a` is`0`: that means all the points are collinear. If they are, check if `c`'s coordinates are between `a`'s and `b`'s. Use either the x or the y coordinates, as long as `a` and `b` are separate on that axis (or they're the same on both). ``` def is_on(a, b, c): "Return t...
How can you determine a point is between two other points on a line segment?
328,107
67
2008-11-29T22:37:13Z
328,122
84
2008-11-29T22:46:45Z
[ "python", "math", "geometry" ]
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point. How can you determine if another point c is on the line segment defined by a and b? I use python most, but examples in any language would be helpful.
Check if the **cross product** of (b-a) and (c-a) is 0, as tells Darius Bacon, tells you if the points a, b and c are aligned. But, as you want to know if c is between a and b, you also have to check that the **dot product** of (b-a) and (c-a) is *positive* and is *less* than the square of the distance between a and b...
How can you determine a point is between two other points on a line segment?
328,107
67
2008-11-29T22:37:13Z
328,193
26
2008-11-29T23:39:34Z
[ "python", "math", "geometry" ]
Let's say you have a two dimensional plane with 2 points (called a and b) on it represented by an x integer and a y integer for each point. How can you determine if another point c is on the line segment defined by a and b? I use python most, but examples in any language would be helpful.
Here's how I'd do it: ``` def distance(a,b): return sqrt((a.x - b.x)**2 + (a.y - b.y)**2) def is_between(a,c,b): return distance(a,c) + distance(c,b) == distance(a,b) ```
Extracting text from HTML file using Python
328,356
128
2008-11-30T02:28:04Z
328,389
69
2008-11-30T03:23:58Z
[ "python", "html", "text", "html-content-extraction" ]
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, ...
[html2text](http://www.aaronsw.com/2002/html2text/) is a Python program that does a pretty good job at this.
Extracting text from HTML file using Python
328,356
128
2008-11-30T02:28:04Z
1,463,802
8
2009-09-23T03:21:58Z
[ "python", "html", "text", "html-content-extraction" ]
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, ...
You can use html2text method in the stripogram library also. ``` from stripogram import html2text text = html2text(your_html_string) ``` To install stripogram run sudo easy\_install stripogram
Extracting text from HTML file using Python
328,356
128
2008-11-30T02:28:04Z
3,987,802
46
2010-10-21T13:14:38Z
[ "python", "html", "text", "html-content-extraction" ]
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, ...
Found myself facing just the same problem today. I wrote a very simple HTML parser to strip incoming content of all markups, returning the remaining text with only a minimum of formatting. ``` from HTMLParser import HTMLParser from re import sub from sys import stderr from traceback import print_exc class _DeHTMLPars...
Extracting text from HTML file using Python
328,356
128
2008-11-30T02:28:04Z
8,201,491
88
2011-11-20T12:34:09Z
[ "python", "html", "text", "html-content-extraction" ]
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, ...
**NOTE:** NTLK no longer supports `clean_html` function Original answer below. --- Use [NLTK](https://pypi.python.org/pypi/nltk) I wasted my 4-5 hours fixing the issues with html2text. Luckily i could encounter NLTK. It works magically. ``` import nltk from urllib import urlopen url = "http://news.bbc.co.uk/...
Extracting text from HTML file using Python
328,356
128
2008-11-30T02:28:04Z
16,423,634
10
2013-05-07T16:04:21Z
[ "python", "html", "text", "html-content-extraction" ]
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, ...
Here is a version of xperroni's answer which is a bit more complete. It skips script and style sections and translates charrefs (e.g., &#39;) and HTML entities (e.g., &amp;). It also includes a trivial plain-text-to-html inverse converter. ``` """ HTML <-> text conversions. """ from HTMLParser import HTMLParser, HTML...
Extracting text from HTML file using Python
328,356
128
2008-11-30T02:28:04Z
24,618,186
44
2014-07-07T19:18:20Z
[ "python", "html", "text", "html-content-extraction" ]
I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad. I'd like something more robust than using regular expressions that may fail on poorly formed HTML. I've seen many people recommend Beautiful Soup, ...
The best piece of code I found for extracting text without getting javascript or not wanted things : ``` import urllib from bs4 import BeautifulSoup url = "http://news.bbc.co.uk/2/hi/health/2284783.stm" html = urllib.urlopen(url).read() soup = BeautifulSoup(html) # kill all script and style elements for script in so...
Printing all instances of a class
328,851
31
2008-11-30T13:23:48Z
328,882
53
2008-11-30T13:56:48Z
[ "python", "class" ]
With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?
I see two options in this case: ## Garbage collector ``` import gc for obj in gc.get_objects(): if isinstance(obj, some_class): dome_something(obj) ``` This has the disadvantage of being very slow when you have a lot of objects, but works with types over which you have no control. ## Use a mixin and wea...
Printing all instances of a class
328,851
31
2008-11-30T13:23:48Z
9,460,070
10
2012-02-27T04:26:56Z
[ "python", "class" ]
With a class in Python, how do I define a function to print every single instance of the class in a format defined in the function?
You'll want to create a static list on your class, and add a `weakref` to each instance so the garbage collector can clean up your instances when they're no longer needed. ``` import weakref class A: instances = [] def __init__(self, name=None): self.__class__.instances.append(weakref.proxy(self)) ...
Pure Python rational numbers module for 2.5
329,333
6
2008-11-30T20:42:50Z
329,338
8
2008-11-30T20:47:25Z
[ "python", "rational-numbers" ]
Has anybody seen such a thing? Small self-sufficient modules are preferred.
[SymPy](http://code.google.com/p/sympy/) is a symbolic maths library written entirely in Python and has full support for rational numbers. From the [tutorial](http://docs.sympy.org/tutorial.html): ``` >>> from sympy import * >>> a = Rational(1,2) >>> a 1/2 >>> a*2 1 >>> Rational(2)**50/Rational(10)**50 1/8881784197...
Pure Python rational numbers module for 2.5
329,333
6
2008-11-30T20:42:50Z
329,453
9
2008-11-30T21:57:16Z
[ "python", "rational-numbers" ]
Has anybody seen such a thing? Small self-sufficient modules are preferred.
The [fractions module](http://docs.python.org/library/fractions.html) from 2.6 can be ripped out if necessary. Grab fractions.py, numbers.py, and abc.py; all pure python modules. You can get the single files from here (2.6 branch, 2.7 does not work): <http://hg.python.org/cpython/branches>
How to find all built in libraries in Python
329,498
5
2008-11-30T22:21:34Z
329,510
16
2008-11-30T22:26:58Z
[ "python" ]
I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch. What's included, and where can I get other good quality libraries from?
Firstly, the [python libary reference](http://www.python.org/doc/2.5.2/lib/lib.html) gives a blow by blow of what's actually included. And the [global module index](http://docs.python.org/modindex.html) contains a neat, alphabetized summary of those same modules. If you have dependencies on a library, you can trivially...
How to find all built in libraries in Python
329,498
5
2008-11-30T22:21:34Z
329,518
11
2008-11-30T22:34:52Z
[ "python" ]
I've recently started with Python, and am enjoying the "batteries included" design. I'e already found out I can import time, math, re, urllib, but don't know how to know that something is builtin rather than writing it from scratch. What's included, and where can I get other good quality libraries from?
run ``` pydoc -p 8080 ``` and point your browser to <http://localhost:8080/> You'll see everything that's installed and can spend lots of time discovering new things. :)
Python CMS for my own website?
329,706
5
2008-12-01T00:53:21Z
329,718
9
2008-12-01T01:01:11Z
[ "python", "django", "content-management-system", "web-testing" ]
I'm an accomplished web and database developer, and I'm interested in redesigning my own website. I have the following content goals: * Support a book I'm writing * Move my blog to my own site (from blogger.com) * Publish my articles (more persistent content than a blog) * Host a forum with light use * Embed slide sh...
1. **Is there another Python CMS?** Yes, there is. Are they better than Django? From some perspective, yes. Should you change? No. Learn Django, it's as good as or better than most. 2. **Perhaps all current Python CMS packages are too "alpha."** A shocking statement, IMO. However, if you think you can do better, by all...
In Python, is there a concise way to use a list comprehension with multiple iterators?
329,886
6
2008-12-01T02:44:03Z
329,904
14
2008-12-01T02:58:14Z
[ "python", "iterator", "list-comprehension" ]
Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following [Haskell code](http://www.haskell.org/haskellwiki/List_comprehension): ``` [(i,j) | i <- [1,2], j <- [1..4]] ``` which yields ``` [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] ``` Can I...
Are you asking about this? ``` [ (i,j) for i in range(1,3) for j in range(1,5) ] ```
In Python, is there a concise way to use a list comprehension with multiple iterators?
329,886
6
2008-12-01T02:44:03Z
329,978
7
2008-12-01T03:40:28Z
[ "python", "iterator", "list-comprehension" ]
Basically, I would like to build a list comprehension over the "cartesian product" of two iterators. Think about the following [Haskell code](http://www.haskell.org/haskellwiki/List_comprehension): ``` [(i,j) | i <- [1,2], j <- [1..4]] ``` which yields ``` [(1,1),(1,2),(1,3),(1,4),(2,1),(2,2),(2,3),(2,4)] ``` Can I...
Cartesian product is in the [itertools module](http://docs.python.org/library/itertools.html#itertools.product) (in 2.6). ``` >>> import itertools >>> list(itertools.product(range(1, 3), range(1, 5))) [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4)] ```
Python crypt module -- what's the correct use of salts?
329,956
9
2008-12-01T03:31:45Z
330,039
7
2008-12-01T04:20:23Z
[ "python", "linux", "cryptography", "crypt" ]
First, context: I'm trying to create a command-line-based tool (Linux) that requires login. Accounts on this tool have nothing to do with system-level accounts -- none of this looks at /etc/passwd. I am planning to store user accounts in a text file using the same format (roughly) as /etc/passwd. Despite not using th...
Python's crypt() is a wrapper for the system's crypt() function. From the Linux crypt() man page: ``` char *crypt(const char *key, const char *salt); key is a user’s typed password. salt is a two-character string chosen from the set [a–zA–Z0–9./]. This string is used to perturb the algorithm in one of 4096 ...
Replace textarea with rich text editor in Django Admin?
329,963
33
2008-12-01T03:32:46Z
330,087
19
2008-12-01T05:12:28Z
[ "python", "django", "admin" ]
I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?
There's an [add-on Django application](http://pypi.python.org/pypi/django-tinymce/) to provide [TinyMCE](http://tinymce.moxiecode.com/) support for Django admin forms without having to muck around with admin templates or Django newform internals.
Replace textarea with rich text editor in Django Admin?
329,963
33
2008-12-01T03:32:46Z
337,114
12
2008-12-03T13:34:31Z
[ "python", "django", "admin" ]
I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?
Take a look on this [snippet](http://www.djangosnippets.org/snippets/1035/) - basic idea is to include custom JS in your admin definitions which will replace standard text areas with rich-text editor. For jQuery/FCKEditor such JS could look like that: ``` $(document).ready(function() { $("textarea").each(function...
Replace textarea with rich text editor in Django Admin?
329,963
33
2008-12-01T03:32:46Z
346,257
9
2008-12-06T13:14:21Z
[ "python", "django", "admin" ]
I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?
I'd say: define your own ModelAdmin class and overwrite the widget used for particular field, like: ``` class ArticleAdminModelForm(forms.ModelForm): description = forms.CharField(widget=widgets.AdminWYMEditor) class Meta: model = models.Article ``` (AdminWYMEditor is a `forms.Textarea` subclass that...
How would one make Python objects persistent in a web-app?
330,367
6
2008-12-01T09:26:07Z
330,574
8
2008-12-01T11:29:48Z
[ "python", "web-applications", "concurrency", "persistence" ]
I'm writing a reasonably complex web application. The Python backend runs an algorithm whose state depends on data stored in several interrelated database tables which does not change often, plus user specific data which does change often. The algorithm's per-user state undergoes many small changes as a user works with...
Be cautious of premature optimization. Addition: The "Python backend runs an algorithm whose state..." is the session in the web framework. That's it. Let the Django framework maintain session state in cache. Period. "The algorithm's per-user state undergoes many small changes as a user works with the application." M...
How to quickly parse a list of strings
330,900
14
2008-12-01T13:51:42Z
330,908
7
2008-12-01T13:53:57Z
[ "python" ]
If I want to split a list of words separated by a delimiter character, I can use ``` >>> 'abc,foo,bar'.split(',') ['abc', 'foo', 'bar'] ``` But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ? ``` In: 'abc,"a string, with a comma","anothe...
The [CSV module](http://www.python.org/doc/2.5.2/lib/module-csv.html) should be able to do that for you
How to quickly parse a list of strings
330,900
14
2008-12-01T13:51:42Z
330,924
32
2008-12-01T13:59:22Z
[ "python" ]
If I want to split a list of words separated by a delimiter character, I can use ``` >>> 'abc,foo,bar'.split(',') ['abc', 'foo', 'bar'] ``` But how to easily and quickly do the same thing if I also want to handle quoted-strings which can contain the delimiter character ? ``` In: 'abc,"a string, with a comma","anothe...
``` import csv input = ['abc,"a string, with a comma","another, one"'] parser = csv.reader(input) for fields in parser: for i,f in enumerate(fields): print i,f # in Python 3 and up, print is a function; use: print(i,f) ``` Result: ``` 0 abc 1 a string, with a comma 2 another, one ```
Python style
331,767
3
2008-12-01T18:40:32Z
331,776
17
2008-12-01T18:44:39Z
[ "python", "coding-style" ]
Simple beginner question: I've created a small python script to toggle between two files I'm using for testing. My question is, what is a good python format style for the following code: ``` import filecmp import shutil local = "local.txt" remote = "remote.txt" config_file = "C:\some\path\file.txt" shutil.copyfile...
For the conditional statement, I would probably go with: ``` if filecmp.cmp(local, config_file): shutil.copyfile(remote, config_file) else: shutil.copyfile(local, config_file) ``` There's little need to use the inline `y if x else z` in this case, since the surrounding code is simple enough.
How to determine if a page is being redirected
331,855
4
2008-12-01T19:10:57Z
331,890
9
2008-12-01T19:23:33Z
[ "python", "http", "http-headers" ]
I need to check whether a page is being redirected or not without actually downloading the content. I just need the final URL. What's the best way of doing this is Python? Thanks!
If you specifically want to avoid downloading the content, you'll need to use the HEAD request method. I believe the `urllib` and `urllib2` libraries do not support HEAD requests, so you'll have to use the lower-level `httplib` library: ``` import httplib h = httplib.HTTPConnection('www.example.com') h.request('HEAD'...
Converting a PDF to a series of images with Python
331,918
32
2008-12-01T19:31:07Z
331,924
16
2008-12-01T19:33:44Z
[ "python", "pdf", "imagemagick", "jpeg", "python-imaging-library" ]
I'm attempting to use Python to convert a multi-page PDF into a series of JPEGs. I can split the PDF up into individual pages easily enough with available tools, but I haven't been able to find anything that can covert PDFs to images. PIL does not work, as it can't read PDFs. The two options I've found are using eithe...
ImageMagick has [Python bindings](http://www.imagemagick.org/download/python/).
Difference between class foo and class foo(object) in Python
332,255
28
2008-12-01T21:17:40Z
332,815
34
2008-12-02T01:59:21Z
[ "python" ]
I know `class foo(object)` is an old school way of defining a class. But I would like to understand in more detail the difference between these two.
Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes). This led to problems when you wanted to mix python-types and builtin types. The most common reason for this is subclassing. If you w...
How do you change the size of figures drawn with matplotlib?
332,289
518
2008-12-01T21:24:44Z
332,311
153
2008-12-01T21:28:56Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figure drawn with matplotlib?
The following seems to work: ``` from pylab import rcParams rcParams['figure.figsize'] = 5, 10 ``` This makes the figure's width 5 inches, and its height 10 **inches**. The Figure class then uses this as the default value for one of its arguments.
How do you change the size of figures drawn with matplotlib?
332,289
518
2008-12-01T21:24:44Z
334,462
43
2008-12-02T16:01:32Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figure drawn with matplotlib?
The first link in Google for `'matplotlib figure size'` is [AdjustingImageSize](http://www.scipy.org/Cookbook/Matplotlib/AdjustingImageSize) ([Google cache of the page](https://webcache.googleusercontent.com/search?q=cache:5oqjjm8c8UMJ:https://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/AdjustingImageSize.html+&...
How do you change the size of figures drawn with matplotlib?
332,289
518
2008-12-01T21:24:44Z
638,443
380
2009-03-12T12:41:35Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figure drawn with matplotlib?
[figure](http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure) tells you the call signature: ``` figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') ``` So `figure(figsize=(1,1))` creates an inch-by-inch image, which will be 80-by-80 pixels unless you also give a different...
How do you change the size of figures drawn with matplotlib?
332,289
518
2008-12-01T21:24:44Z
4,306,340
328
2010-11-29T17:30:40Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figure drawn with matplotlib?
If you've already got the figure created you can quickly do this: ``` fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 10.5) fig.savefig('test2png.png', dpi=100) ``` To propagate the size change to an existing gui window add `forward=True` ``` fig.set_size_inches(18.5, 10.5, forward=True) ```
How do you change the size of figures drawn with matplotlib?
332,289
518
2008-12-01T21:24:44Z
24,073,700
62
2014-06-06T03:24:00Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figure drawn with matplotlib?
Please try a simple code as following: ``` from matplotlib import pyplot as plt plt.figure(figsize=(1,1)) x = [1,2,3] plt.plot(x, x) plt.show() ``` You need to set the figure size before you plot.
Integer (representing a sequence of bits) reinterpretation as Character Array in Python
333,097
4
2008-12-02T05:03:37Z
333,116
9
2008-12-02T05:16:21Z
[ "python" ]
I've written some C code that I would like to port to python, as I feel python is a better 'concept' language. In my C code, I use memory reinterpretation to achieve my goals, for example: ``` sizeof(int) is 4 byte sizeof(char) is 1 byte char c[4]={0x01,0x30,0x00,0x80}; int* i=(int*)c; *i has the value 0x80003001 ...
You can use the [struct module](http://www.python.org/doc/2.5.2/lib/module-struct.html): ``` import struct # Pack a Python long as if it was a C unsigned integer, little endian bytes = struct.pack("<I", 0x78FF00AA) print [hex(ord(byte)) for byte in bytes] ['0xaa', '0x0', '0xff', '0x78'] ``` Read the documentation p...
string.split(text) or text.split() what's the difference?
333,706
9
2008-12-02T11:41:05Z
333,715
11
2008-12-02T11:46:16Z
[ "python" ]
There is one thing that I do not understand... Imagine you have a **text** = "hello world" and you want to split it. In some places I see people that want to split the **text** doing: ``` string.split(text) ``` In other places I see people just doing: ``` text.split() ``` What’s the difference? Why you do in on...
The `string.split(stringobj)` is a feature of the `string` module, which must be imported separately. Once upon a time, that was the only way to split a string. That's some old code you're looking at. The `stringobj.split()` is a feature of a string object, `stringobj`, which is more recent than the `string` module. B...
string.split(text) or text.split() what's the difference?
333,706
9
2008-12-02T11:41:05Z
333,727
20
2008-12-02T11:49:56Z
[ "python" ]
There is one thing that I do not understand... Imagine you have a **text** = "hello world" and you want to split it. In some places I see people that want to split the **text** doing: ``` string.split(text) ``` In other places I see people just doing: ``` text.split() ``` What’s the difference? Why you do in on...
Interestingly, the docstrings for the two are not completely the same in Python 2.5.1: ``` >>> import string >>> help(string.split) Help on function split in module string: split(s, sep=None, maxsplit=-1) split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as ...
How to detect that Python code is being executed through the debugger?
333,995
12
2008-12-02T13:58:30Z
334,090
13
2008-12-02T14:25:10Z
[ "python" ]
Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger? I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.
Python debuggers (as well as profilers and coverage tools) use the `sys.settrace` function (in the `sys` module) to register a callback that gets called when interesting events happen. If you're using Python 2.6, you can call `sys.gettrace()` to get the current trace callback function. If it's not `None` then you can ...
How to detect that Python code is being executed through the debugger?
333,995
12
2008-12-02T13:58:30Z
338,391
7
2008-12-03T19:13:56Z
[ "python" ]
Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger? I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.
A solution working with Python 2.4 (it should work with any version superior to 2.1) and Pydev: ``` import inspect def isdebugging(): for frame in inspect.stack(): if frame[1].endswith("pydevd.py"): return True return False ``` The same should work with pdb by simply replacing `pydevd.py` with `pdb.py`...
Passing a dictionary to a function in python as keyword parameters
334,655
165
2008-12-02T16:49:11Z
334,666
258
2008-12-02T16:53:34Z
[ "python", "function", "dictionary", "parameters", "keyword" ]
I'd like to call a function in python using a dictionary. Here is some code: ``` d = dict(param='test') def f(param): print param f(d) ``` This prints `{'param': 'test'}` but I'd like it to just print `test`. I'd like it to work similarly for more parameters: ``` d = dict(p1=1, p2=2) def f2(p1,p2): print...
Figured it out for myself in the end. It is simple, I was just missing the \*\* operator to unpack the dictionary So my example becomes: ``` d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(**d) ```
Passing a dictionary to a function in python as keyword parameters
334,655
165
2008-12-02T16:49:11Z
335,626
19
2008-12-02T22:03:11Z
[ "python", "function", "dictionary", "parameters", "keyword" ]
I'd like to call a function in python using a dictionary. Here is some code: ``` d = dict(param='test') def f(param): print param f(d) ``` This prints `{'param': 'test'}` but I'd like it to just print `test`. I'd like it to work similarly for more parameters: ``` d = dict(p1=1, p2=2) def f2(p1,p2): print...
In python, this is called "unpacking", and you can find a bit about it in the [tutorial](https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists). The documentation of it sucks, I agree, especially because of how fantasically useful it is.
Does PyS60 produce sis files that are native?
334,765
9
2008-12-02T17:30:18Z
386,298
14
2008-12-22T13:59:10Z
[ "python", "symbian", "s60", "pys60" ]
I am currently looking at developing a mobile apps for the S60 platform and is specifically looking at PyS60. It seems to suggest that the it can be compiled into native .sis files without the need for an embedded python interpreter. Reading through the documentations I could not find any statements where this is expli...
Once you've written your code in python, you can convert this to a .sis file using ensymble. <http://code.google.com/p/ensymble/> This software allows you to make your .py file into a .sis file using the py2sis option - however, it won't be much use on any phone without python installed, so you may also need to use e...
What's the best way to get the size of a folder and all the files inside from python?
335,078
6
2008-12-02T19:09:50Z
335,105
10
2008-12-02T19:17:59Z
[ "python" ]
If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.
You mean something like this? ``` import os for path, dirs, files in os.walk( root ): for f in files: print path, f, os.path.getsize( os.path.join( path, f ) ) ```
detecting if a module is imported inside the app engine environment
335,399
4
2008-12-02T20:48:08Z
335,464
11
2008-12-02T21:13:13Z
[ "python", "google-app-engine" ]
What I want to do is patch an existing python module that uses urllib2 to run on app engine, but I don't want to break it so it can be used elsewhere. So I'm looking for a quick solution to test if the module is imported in the app engine environment or not. Catching ImportError on urllib2 might not be the best solutio...
You could simply use sys.modules to test if a module has been imported (I'm using unicodedata as an example): ``` >>> import sys >>> 'unicodedata' in sys.modules False >>> import unicodedata >>> 'unicodedata' in sys.modules True ```
Lists in ConfigParser
335,695
77
2008-12-02T22:29:05Z
335,754
67
2008-12-02T22:56:44Z
[ "python", "configparser" ]
The typical ConfigParser generated file looks like: ``` [Section] bar=foo [Section 2] bar2= baz ``` Now, is there a way to index lists like, for instance: ``` [Section 3] barList={ item1, item2 } ``` Related question: [Python’s ConfigParser unique keys per section](http://stackoverflow.com/questions/28775...
There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like: ``` [Section 3] barList=item1,item2 ``` It's not pretty but it's functional for most simple lists.
Lists in ConfigParser
335,695
77
2008-12-02T22:29:05Z
8,048,529
60
2011-11-08T09:50:51Z
[ "python", "configparser" ]
The typical ConfigParser generated file looks like: ``` [Section] bar=foo [Section 2] bar2= baz ``` Now, is there a way to index lists like, for instance: ``` [Section 3] barList={ item1, item2 } ``` Related question: [Python’s ConfigParser unique keys per section](http://stackoverflow.com/questions/28775...
Coming late to this party, but I recently implemented this with a dedicated section in a config file for a list: ``` [paths] path1 = /some/path/ path2 = /another/path/ ... ``` and using `config.items( "paths" )` to get an iterable list of path items, like so: ``` path_items = config.items( "paths...
Lists in ConfigParser
335,695
77
2008-12-02T22:29:05Z
9,735,884
91
2012-03-16T10:48:22Z
[ "python", "configparser" ]
The typical ConfigParser generated file looks like: ``` [Section] bar=foo [Section 2] bar2= baz ``` Now, is there a way to index lists like, for instance: ``` [Section 3] barList={ item1, item2 } ``` Related question: [Python’s ConfigParser unique keys per section](http://stackoverflow.com/questions/28775...
Also a bit late, but maybe helpful for some. I am using a combination of ConfigParser and JSON: ``` [Foo] fibs: [1,1,2,3,5,8,13] ``` just read it with: ``` >>> json.loads(config.get("Foo","fibs")) [1, 1, 2, 3, 5, 8, 13] ``` You can even break lines if your list is long (thanks @peter-smit): ``` [Bar] files_to_chec...
Lists in ConfigParser
335,695
77
2008-12-02T22:29:05Z
11,866,695
34
2012-08-08T14:26:45Z
[ "python", "configparser" ]
The typical ConfigParser generated file looks like: ``` [Section] bar=foo [Section 2] bar2= baz ``` Now, is there a way to index lists like, for instance: ``` [Section 3] barList={ item1, item2 } ``` Related question: [Python’s ConfigParser unique keys per section](http://stackoverflow.com/questions/28775...
One thing a lot of people don't know is that multi-line configuration-values are allowed. For example: ``` ;test.ini [hello] barlist = item1 item2 ``` The value of `config.get('hello','barlist')` will now be: ``` "\nitem1\nitem2" ``` Which you easily can split with the splitlines method (don't forget to fi...
Lists in ConfigParser
335,695
77
2008-12-02T22:29:05Z
22,675,825
8
2014-03-27T00:20:03Z
[ "python", "configparser" ]
The typical ConfigParser generated file looks like: ``` [Section] bar=foo [Section 2] bar2= baz ``` Now, is there a way to index lists like, for instance: ``` [Section 3] barList={ item1, item2 } ``` Related question: [Python’s ConfigParser unique keys per section](http://stackoverflow.com/questions/28775...
I landed here seeking to consume this... ``` [global] spys = richard.sorge@cccp.gov, mata.hari@deutschland.gov ``` The answer is to split it on the comma and strip the spaces: ``` SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')] ``` To get a list result: ``` ['richard.sorge@cccp.gov', 'mata.hari...
How to handle a glade project with many windows
336,013
7
2008-12-03T01:39:50Z
339,212
9
2008-12-04T00:13:52Z
[ "python", "gtk", "pygtk", "glade" ]
I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I call it like... ``` self.wTree = gtk.glade.XML("interface...
In my projects, I always have one window per glade file. I'd recommend the same for your project. The following are the two main reasons: * It will be faster and use less memory, since each call to gtk.glade.XML() parses the whole thing. Sure you can pass in the root argument to avoid creating the widget tree for all...
Python: Invalid Token
336,181
13
2008-12-03T04:01:12Z
336,189
35
2008-12-03T04:04:50Z
[ "python", "octal" ]
Some of you may recognize this as Project Euler's problem number 11. The one with the grid. I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why ``` grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49,...
I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.
How to implement a minimal server for AJAX in Python?
336,866
35
2008-12-03T11:37:28Z
336,894
9
2008-12-03T11:50:13Z
[ "python", "ajax", "user-interface" ]
I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python `SimpleHTTPServer.SimpleHTTPRequestHandler`? A simple example would be a textfield and a bu...
Use the [WSGI reference implementation](https://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server). In the long run, you'll be happier. ``` from wsgiref.simple_server import make_server, demo_app httpd = make_server('', 8000, demo_app) print "Serving HTTP on port 8000..." # Respond to requests unti...
How to implement a minimal server for AJAX in Python?
336,866
35
2008-12-03T11:37:28Z
338,519
45
2008-12-03T20:01:15Z
[ "python", "ajax", "user-interface" ]
I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python `SimpleHTTPServer.SimpleHTTPRequestHandler`? A simple example would be a textfield and a bu...
O.K., I think I can now answer my own question. Here is an example implementation for calculating the square of a number on the server. Please let me know if there are any improvements or misconceptions. the python server file: ``` import threading import webbrowser import BaseHTTPServer import SimpleHTTPServer FILE...
Python optparse metavar
336,963
21
2008-12-03T12:36:12Z
336,992
25
2008-12-03T12:48:58Z
[ "python", "optparse" ]
I am not sure what `optparse`'s `metavar` parameter is used for. I see it is used all around, but I can't see its use. Can someone make it clear to me? Thanks.
As @[Guillaume](#336975) says, it's used for generating help. If you want to have an option that takes an argument, such as a filename, you can add the `metavar` parameter to the `add_option` call so your preferred argument name/descriptor is output in the help message. From [the current module documentation](http://do...
Python: item for item until stopterm in item?
337,223
3
2008-12-03T14:11:57Z
337,285
10
2008-12-03T14:28:58Z
[ "python" ]
Disclaimer: I'm fairly new to python! If I want all the lines of a file until (edit: and including) the line containing some string `stopterm`, is there a way of using the list syntax for it? I was hoping there would be something like: ``` usefullines = [line for line in file until stopterm in line] ``` For now, I'v...
``` from itertools import takewhile usefullines = takewhile(lambda x: not re.search(stopterm, x), lines) from itertools import takewhile usefullines = takewhile(lambda x: stopterm not in x, lines) ``` Here's a way that keeps the stopterm line: ``` def useful_lines(lines, stopterm): for line in lines: if ...
How to get a row-by-row MySQL ResultSet in python
337,479
41
2008-12-03T15:23:49Z
337,706
45
2008-12-03T16:17:12Z
[ "python", "mysql" ]
MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server. In Java, following the instructions [here](http://dev.mysql.com/doc/refman/5.1/en/connecto...
I think you have to connect passing `cursorclass = MySQLdb.cursors.SSCursor`: ``` MySQLdb.connect(user="user", passwd="password", db="mydb", cursorclass = MySQLdb.cursors.SSCursor ) ``` The default cursor fetches all the data at once, even if you do...
How to get a row-by-row MySQL ResultSet in python
337,479
41
2008-12-03T15:23:49Z
337,922
16
2008-12-03T17:09:52Z
[ "python", "mysql" ]
MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server. In Java, following the instructions [here](http://dev.mysql.com/doc/refman/5.1/en/connecto...
The limit/offset solution runs in quadratic time because mysql has to rescan the rows to find the offset. As you suspected, the default cursor stores the entire result set on the client, which may consume a lot of memory. Instead you can use a server side cursor, which keeps the query running and fetches results as ne...
Dynamic Keyword Arguments in Python?
337,688
25
2008-12-03T16:12:22Z
337,714
30
2008-12-03T16:19:03Z
[ "python" ]
Does python have the ability to create dynamic keywords? For example: ``` qset.filter(min_price__usd__range=(min_price, max_price)) ``` I want to be able to change the **usd** part based on a selected currency.
Yes, It does. Use `**kwargs` in a function definition. Example: ``` def f(**kwargs): print kwargs.keys() f(a=2, b="b") # -> ['a', 'b'] f(**{'d'+'e': 1}) # -> ['de'] ``` But why do you need that?
Dynamic Keyword Arguments in Python?
337,688
25
2008-12-03T16:12:22Z
337,733
10
2008-12-03T16:22:38Z
[ "python" ]
Does python have the ability to create dynamic keywords? For example: ``` qset.filter(min_price__usd__range=(min_price, max_price)) ``` I want to be able to change the **usd** part based on a selected currency.
You can easily do this by declaring your function like this: ``` def filter(**kwargs): ``` your function will now be passed a dictionary called kwargs that contains the keywords and values passed to your function. Note that, syntactically, the word `kwargs` is meaningless; the `**` is what causes the dynamic keyword ...
Dynamic Keyword Arguments in Python?
337,688
25
2008-12-03T16:12:22Z
337,735
19
2008-12-03T16:22:51Z
[ "python" ]
Does python have the ability to create dynamic keywords? For example: ``` qset.filter(min_price__usd__range=(min_price, max_price)) ``` I want to be able to change the **usd** part based on a selected currency.
If I understand what you're asking correctly, ``` qset.filter(**{ 'min_price_' + selected_currency + '_range' : (min_price, max_price)}) ``` does what you need.
Python, Popen and select - waiting for a process to terminate or a timeout
337,863
21
2008-12-03T16:53:17Z
337,912
15
2008-12-03T17:06:30Z
[ "python", "select", "timeout", "subprocess", "popen" ]
I run a subprocess using: ``` p = subprocess.Popen("subprocess", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) ``` This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect...
Have you tried using the Popen.Poll() method. You could just do this: ``` p = subprocess.Popen("subprocess", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) time.sleep(SECONDS_TO_WAIT) retcode = p.poll() if retcode is not None: # pr...
Python, Popen and select - waiting for a process to terminate or a timeout
337,863
21
2008-12-03T16:53:17Z
1,035,488
8
2009-06-23T21:58:58Z
[ "python", "select", "timeout", "subprocess", "popen" ]
I run a subprocess using: ``` p = subprocess.Popen("subprocess", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) ``` This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect...
This is what i came up with. Works when you need and don't need to timeout on thep process, but with a semi-busy loop. ``` def runCmd(cmd, timeout=None): ''' Will execute a command, read the output and return it back. @param cmd: command to execute @param timeout: process timeout in seconds @retur...
Python subprocess.call() fails when using pythonw.exe
337,870
5
2008-12-03T16:54:17Z
337,990
7
2008-12-03T17:26:53Z
[ "python", "multithreading", "subprocess" ]
I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe. ``` def runStuff(commandLine): outputFileName = 'somefile.txt' outputFile = open(outputFileName, "w") try: result = subprocess.call(commandLine, shell=True, stdout=outp...
`sys.stdin` and `sys.stdout` handles are invalid because pythonw does not provide console support as it runs as a deamon, so default arguments of `subprocess.call()` are failing. Deamon programs close stdin/stdout/stderr purposedly and use logging instead, so that you have to manage this yourself: I would suggest to u...
TimedRotatingFileHandler Changing File Name?
338,450
5
2008-12-03T19:37:51Z
338,566
15
2008-12-03T20:21:41Z
[ "python", "logging" ]
I am trying to implement the python logging handler called TimedRotatingFileHandler. When it rolls over to midnight it appends the current day in the form: "YYYY-MM-DD". ``` LOGGING_MSG_FORMAT = '%(name)-14s > [%(levelname)s] [%(asctime)s] : %(message)s' LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' logging.basicConfig...
"How can i change how it alters the filename?" Since it isn't documented, I elected to read the source. This is what I concluded from reading the source of `logging/handlers.py` ``` handler = logging.handlers.TimedRotatingFileHandler("C:\\isis_ops\\logs\\Rotate_Test",'midnight',1) handler.suffix = "%Y-%m-%d" # or any...
python ImportError No module named
338,768
186
2008-12-03T21:26:28Z
338,790
11
2008-12-03T21:31:53Z
[ "python", "importerror", "python-import" ]
I am very new at Python and I am getting this error: ``` Traceback (most recent call last): File "mountain.py", line 28, in ? from toolkit.interface import interface ImportError: No module named toolkit.interface ``` Python is installed in a local directory: My directory tree is like this: ``` (local director...
To mark a directory as a package you need a file named `__init__.py`, does this help?
python ImportError No module named
338,768
186
2008-12-03T21:26:28Z
338,858
33
2008-12-03T21:50:15Z
[ "python", "importerror", "python-import" ]
I am very new at Python and I am getting this error: ``` Traceback (most recent call last): File "mountain.py", line 28, in ? from toolkit.interface import interface ImportError: No module named toolkit.interface ``` Python is installed in a local directory: My directory tree is like this: ``` (local director...
Does ``` (local directory)/site-packages/toolkit ``` have a `__init__.py`? To make import *walk* through your directories every directory must have a `__init__.py` file.
python ImportError No module named
338,768
186
2008-12-03T21:26:28Z
339,220
159
2008-12-04T00:17:40Z
[ "python", "importerror", "python-import" ]
I am very new at Python and I am getting this error: ``` Traceback (most recent call last): File "mountain.py", line 28, in ? from toolkit.interface import interface ImportError: No module named toolkit.interface ``` Python is installed in a local directory: My directory tree is like this: ``` (local director...
Based on your comments to orip's post, I guess this is what happened: 1. You edited `__init__.py` on windows. 2. The windows editor added something non-printing, perhaps a carriage-return (end-of-line in Windows is CR/LF; in unix it is LF only), or perhaps a CTRL-Z (windows end-of-file). 3. You used WinSCP to copy the...
python ImportError No module named
338,768
186
2008-12-03T21:26:28Z
339,333
17
2008-12-04T01:11:08Z
[ "python", "importerror", "python-import" ]
I am very new at Python and I am getting this error: ``` Traceback (most recent call last): File "mountain.py", line 28, in ? from toolkit.interface import interface ImportError: No module named toolkit.interface ``` Python is installed in a local directory: My directory tree is like this: ``` (local director...
I solved my own problem, I will write a summary of the things that were wrong and the solution: The file needs to be called exactly `__init__.py`, if the extension is different such as my case `.py.bin` then python cannot move through the directories and then it cannot find the modules. To edit the files you need to u...
python ImportError No module named
338,768
186
2008-12-03T21:26:28Z
5,199,346
22
2011-03-04T21:14:56Z
[ "python", "importerror", "python-import" ]
I am very new at Python and I am getting this error: ``` Traceback (most recent call last): File "mountain.py", line 28, in ? from toolkit.interface import interface ImportError: No module named toolkit.interface ``` Python is installed in a local directory: My directory tree is like this: ``` (local director...
On \*nix, also make sure that PYTHONPATH is configured correctly, esp that it has the format ``` .:/usr/local/lib/python ``` (mind the .: at the beginning, so that it can search on the current directory, too)
python ImportError No module named
338,768
186
2008-12-03T21:26:28Z
23,210,066
13
2014-04-22T03:52:48Z
[ "python", "importerror", "python-import" ]
I am very new at Python and I am getting this error: ``` Traceback (most recent call last): File "mountain.py", line 28, in ? from toolkit.interface import interface ImportError: No module named toolkit.interface ``` Python is installed in a local directory: My directory tree is like this: ``` (local director...
I ran into something very similar when I did this exercise in LPTHW; I could never get Python to recognise that I had files in the directory I was calling from. But I was able to get it to work in the end. What I did, and what I recommend, is to try this: (NOTE: From your initial post, I am assuming you are using an \...
Nicest way to pad zeroes to string
339,007
647
2008-12-03T22:39:51Z
339,012
76
2008-12-03T22:41:49Z
[ "python", "string" ]
What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?
For numbers: ``` print "%05d" % number ``` See also: [Python: String formatting](http://docs.python.org/library/string.html#string-formatting). **EDIT**: It's worth noting that as of yesterday December 3rd, 2008, this method of formatting is deprecated in favour of the `format` string method: ``` print("{0:05d}".fo...
Nicest way to pad zeroes to string
339,007
647
2008-12-03T22:39:51Z
339,013
984
2008-12-03T22:42:04Z
[ "python", "string" ]
What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?
Strings: ``` >>> n = '4' >>> print n.zfill(3) 004 ``` And for numbers: ``` >>> n = 4 >>> print '%03d' % n 004 >>> print format(4, '03') # python >= 2.6 004 >>> print '{0:03d}'.format(4) # python >= 2.6 004 >>> print '{foo:03d}'.format(foo=4) # python >= 2.6 004 >>> print('{:03d}'.format(4)) # python >= 2.7 + pyth...
Nicest way to pad zeroes to string
339,007
647
2008-12-03T22:39:51Z
339,019
9
2008-12-03T22:44:58Z
[ "python", "string" ]
What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?
``` width = 10 x = 5 print "%0*d" % (width, x) > 0000000005 ``` See the print documentation for all the exciting details! **Update for Python 3.x (7.5 years later)** That last line should now be: ``` print("%0*d" % (width, x)) ``` I.e. `print()` is now a function, not a statement. Note that I still prefer the Old ...
Nicest way to pad zeroes to string
339,007
647
2008-12-03T22:39:51Z
339,024
200
2008-12-03T22:47:13Z
[ "python", "string" ]
What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?
Just use the [rjust](http://docs.python.org/2/library/stdtypes.html#string-methods) method of the string object. This example will make a string of 10 characters long, padding as necessary. ``` >>> t = 'test' >>> t.rjust(10, '0') >>> '000000test' ```
Nicest way to pad zeroes to string
339,007
647
2008-12-03T22:39:51Z
6,196,350
26
2011-06-01T04:40:02Z
[ "python", "string" ]
What is the nicest/shortest way to pad a string with zeroes to the left, so the string length has a specific length?
`str(n).zfill(width)` will work with `string`s, `int`s, `float`s... and is Python 2.*x* and 3.*x* compatible: ``` >>> n = 3 >>> str(n).zfill(5) '00003' >>> n = '3' >>> str(n).zfill(5) '00003' >>> n = '3.0' >>> str(n).zfill(5) '003.0' ```