content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
question comparing multiprocessing vs twisted
Got a situation where I'm going to be parsing websites. each site has to have it's own "parser" and possibly it's own way of dealing with cookies/etc..
I'm trying to get in my head which would be a better choice.
Choice I:
I can create a multiprocessing function, where the (masterspawn) app gets an input url, and in turn it spans a process/function within the masterspawn app that then handles all the setup/fetching/parsing of the page/URL.
This approach would have one master app running, and it in turn creates multiple instances of the internal function.. Should be fast, yes/no?
Choice II:
I could create a "Twisted" kind of server, that would essentially do the same thing as Choice I. The difference being that using "Twisted" would also impose some overhead. I'm trying to evaluate Twisted, with regards to it being a "Server" but i don't need it to perform the fetching of the url.
Choice III:
I could use scrapy. I'm inclined not to go this route as I don't want/need to use the overhead that scrapy appears to have. As i stated, each of the targeted URLs needs its own parse function, as well as dealing with the cookies...
My goal is to basically have the "architected" solution spread across multiple boxes, where each client box interfaces with a master server that allocates the urls to be parsed.
thanks for any comments on this..
-tom
A:
There are two dimensions to this question: concurrency and distribution.
Concurrency: either Twisted or multiprocessing will do the job of concurrently handling fetching/parsing jobs. I'm not sure though where your premise of the "Twisted overhead" comes from. On the contrary, the multiprocessing path would incur much more overhead, since a (relatively heavy-weight) OS-process would have to be spawned. Twisteds' way of handling concurrency is much more light-weight.
Distribution: multiprocessing won't distribute your fetch/parse jobs to different boxes. Twisted can do this, eg. using the AMP protocol building facilities.
I cannot comment on scrapy, never having used it.
A:
For this particular question I'd go with multiprocessing - it's simple to use and simple to understand. You don't particularly need twisted, so why take on the extra complication.
One other option you might want to consider: use a message queue. Have the master drop URLs onto a queue (eg. beanstalkd, resque, 0mq) and have worker processes pickup the URLs and process them. You'll get both concurrency and distribution: you can run workers on as many machines as you want.
| question comparing multiprocessing vs twisted | Got a situation where I'm going to be parsing websites. each site has to have it's own "parser" and possibly it's own way of dealing with cookies/etc..
I'm trying to get in my head which would be a better choice.
Choice I:
I can create a multiprocessing function, where the (masterspawn) app gets an input url, and in turn it spans a process/function within the masterspawn app that then handles all the setup/fetching/parsing of the page/URL.
This approach would have one master app running, and it in turn creates multiple instances of the internal function.. Should be fast, yes/no?
Choice II:
I could create a "Twisted" kind of server, that would essentially do the same thing as Choice I. The difference being that using "Twisted" would also impose some overhead. I'm trying to evaluate Twisted, with regards to it being a "Server" but i don't need it to perform the fetching of the url.
Choice III:
I could use scrapy. I'm inclined not to go this route as I don't want/need to use the overhead that scrapy appears to have. As i stated, each of the targeted URLs needs its own parse function, as well as dealing with the cookies...
My goal is to basically have the "architected" solution spread across multiple boxes, where each client box interfaces with a master server that allocates the urls to be parsed.
thanks for any comments on this..
-tom
| [
"There are two dimensions to this question: concurrency and distribution. \nConcurrency: either Twisted or multiprocessing will do the job of concurrently handling fetching/parsing jobs. I'm not sure though where your premise of the \"Twisted overhead\" comes from. On the contrary, the multiprocessing path would in... | [
2,
1
] | [] | [] | [
"multiprocessing",
"python",
"twisted"
] | stackoverflow_0003374943_multiprocessing_python_twisted.txt |
Q:
How do I choose a task_id using celery?
For now I get a task_id from the async_result and have to save it the get it back later.
Would be better if I knew what the task_id what made of so I can calculate it back instead of pulling from the DB. E.G: set a task with task_id=("%s-%s" % (user_id, datetime)).
A:
You can certainly use "natural ids", but then to be really useful they would have to
be reverseable, which doesn't work if you add that timestamp. Also the ids are unique, so two tasks can't have the same id (the behavior then is undefined)
If you have a task to refresh the timeline of a twitter user, then you know that you
only want one task running for each user id at any time, so you could use a natural id like:
"update-twitter-timeline-%s" % (user_id)
then always be able to get the result for that task, or revoke the task using that id, no need to manually store it somewhere and look it up.
| How do I choose a task_id using celery? | For now I get a task_id from the async_result and have to save it the get it back later.
Would be better if I knew what the task_id what made of so I can calculate it back instead of pulling from the DB. E.G: set a task with task_id=("%s-%s" % (user_id, datetime)).
| [
"You can certainly use \"natural ids\", but then to be really useful they would have to\nbe reverseable, which doesn't work if you add that timestamp. Also the ids are unique, so two tasks can't have the same id (the behavior then is undefined)\nIf you have a task to refresh the timeline of a twitter user, then you... | [
4
] | [] | [] | [
"celery",
"django",
"python"
] | stackoverflow_0003357489_celery_django_python.txt |
Q:
Clarifications on a python script file
Just need some clarification on how to design a python script file test.py.
When defining functions, do they have to go on the top of the file right after the imports?
should I be doing that main check in my file?
I want to run this file on my server as a cron job. If the file gets too big (I have my sqlalchemy definitions in it also), how can I break the file into multiple files? I want this easy to deploy by just dropping the files into a folder in my server.
A:
Most scripts look something like the following:
import module1
import module2
CONSTANT=...
def foo():
...
def bar():
....
class Baz():
....
def run(verbose=False):
....
if __name__=='__main__':
import optparse
def parse_options():
usage = 'usage: %prog [options]'
parser = optparse.OptionParser(usage=usage)
parser.add_option('-v', '--verbose', dest='verbose',
action='store_true',
default=False,
help="verbose")
return parser.parse_args()
def cli():
opt,args=parse_options()
run(verbose=opt.verbose)
cli()
So the body of your script is mainly composed of function/class definitions. There (usually) is very little code that isn't inside a function/class definition.
I would try to group the functions in whatever way facilitates organization and readability. If you believe a function can be reused in places other than that particular script, then place it in a module, and import that module into this script.
Define PYTHONPATH and PATH in your crontab. Then you should have no problem running your script from cron.
| Clarifications on a python script file | Just need some clarification on how to design a python script file test.py.
When defining functions, do they have to go on the top of the file right after the imports?
should I be doing that main check in my file?
I want to run this file on my server as a cron job. If the file gets too big (I have my sqlalchemy definitions in it also), how can I break the file into multiple files? I want this easy to deploy by just dropping the files into a folder in my server.
| [
"Most scripts look something like the following:\nimport module1\nimport module2\n\nCONSTANT=...\n\ndef foo():\n ...\n\ndef bar():\n ....\n\nclass Baz():\n ....\n\ndef run(verbose=False):\n ....\n\nif __name__=='__main__':\n import optparse\n def parse_options():\n usage = 'usage: %prog [optio... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0003379794_python.txt |
Q:
why are these C / Cython arrays defined as character, not integer arrays?
in an effort to solve question #3367795 here on SO i have to cope with a number of subproblems. one of these is: in said algorithm (levenshtein distance), several arrays are allocated in memory and initialized with the lines
cdef char *m1 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m2 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m3 = <char *>malloc( ( blen + 2 ) * sizeof( char ) )
#.........................................................................
for i from 0 <= i <= blen:
m2[ i ] = i
<...snip...>
blen here refers to the length of a Python bytes variable. now as far as i understand the algorithm (see my original post for the full code) and as the code for the initialization of m2 clearly shows, these arrays are meant to hold integer numbers, not characters, so one would think the correct allocations should look like
cdef int *m3 = <int *>malloc( ( blen + 2 ) * sizeof( int ) )
and so on. can anyone with a background in C elucidate to me why char is used? also, maybe more for people inclined to Cython, why is there a cast <char *>? one would think that char *x = malloc( ... ) should suffice to define x.
A:
Despite the misleading name, char types in C language are ordinary integral types, just like short, int, long and such. Of all integral types, chars have the smallest range and occupy the smallest amount of memory. So, if in your application it is important to save as much memory as possible, it might make sense to use char instead of int.
On some hardware platforms it might turn out that int types work faster than char types, so the selection of the specific type becomes a speed-vs-memory trade-off, but, once again, in many cases when the range of char is naturally sufficient, it might make more sense to use char instead of int.
A:
Quite simply, to save memory -- but please note carefully that declaring these arrays as char limits the result distance to either 127 or 255, depending on whether the C compiler defaults to signed char or unsigned char respectively. In C, char is an integer type -- you don't need an ord() to get its integer value.
Your original code contains no mention of this limitation. Note that if a char overflows, it does so silently and the code will produce incorrect results -- 127 + 1 -> -128 (signed); 255 + 1 -> 0 (unsigned).
You didn't respond to my comment on your original question: """What are the (a) maximum (b) average sizes of your strings? Do you really need to do the whole O(M*N) thing if the two strings are nothing like each other?""" ..... Please answer that now (edit your question); had you done so then, you would have had this question answered then.
Update: Reading the original post again, I've noticed a problem: The code that reads
m1, m2 = m2, m1
strcpy( m3, m2 )
is WRONG on three grounds: (1) it doesn't shuffle the rows properly (should do strcpy() before swapping m1 and m2) (2) strcpy() will not copy anything beyond the first null (zero byte) (3) there is no need to copy anything, just shuffle the pointers
m3, m2, m1 = m2, m1, m3
| why are these C / Cython arrays defined as character, not integer arrays? | in an effort to solve question #3367795 here on SO i have to cope with a number of subproblems. one of these is: in said algorithm (levenshtein distance), several arrays are allocated in memory and initialized with the lines
cdef char *m1 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m2 = <char *>calloc( blen + 2, sizeof( char ) )
cdef char *m3 = <char *>malloc( ( blen + 2 ) * sizeof( char ) )
#.........................................................................
for i from 0 <= i <= blen:
m2[ i ] = i
<...snip...>
blen here refers to the length of a Python bytes variable. now as far as i understand the algorithm (see my original post for the full code) and as the code for the initialization of m2 clearly shows, these arrays are meant to hold integer numbers, not characters, so one would think the correct allocations should look like
cdef int *m3 = <int *>malloc( ( blen + 2 ) * sizeof( int ) )
and so on. can anyone with a background in C elucidate to me why char is used? also, maybe more for people inclined to Cython, why is there a cast <char *>? one would think that char *x = malloc( ... ) should suffice to define x.
| [
"Despite the misleading name, char types in C language are ordinary integral types, just like short, int, long and such. Of all integral types, chars have the smallest range and occupy the smallest amount of memory. So, if in your application it is important to save as much memory as possible, it might make sense t... | [
8,
2
] | [] | [] | [
"c",
"cython",
"python"
] | stackoverflow_0003379795_c_cython_python.txt |
Q:
Calculation to get page count based on # of items
If I have 177 items, and each page has 10 items that means I'll have 18 pages.
I'm new to python and having used any of the math related functions.
How can I calculate 177/10 and then get round up so I get 18 and not 17.7
A:
import math
math.ceil(float(177)/10)
A:
You can do it with integer arithmetic:
items_per_page = 10
number_of_pages = (x + items_per_page - 1) // items_per_page
| Calculation to get page count based on # of items | If I have 177 items, and each page has 10 items that means I'll have 18 pages.
I'm new to python and having used any of the math related functions.
How can I calculate 177/10 and then get round up so I get 18 and not 17.7
| [
"import math\nmath.ceil(float(177)/10)\n\n",
"You can do it with integer arithmetic:\n\nitems_per_page = 10\nnumber_of_pages = (x + items_per_page - 1) // items_per_page\n\n"
] | [
7,
5
] | [] | [] | [
"math",
"python"
] | stackoverflow_0003379971_math_python.txt |
Q:
String formatting issues and concatenating a string with a number
I'm coming from a c# background, and I do this:
Console.Write("some text" + integerValue);
So the integer automatically gets converted to a string and it outputs.
In python I get an error when I do:
print 'hello' + 10
Do I have to convert to string everytime?
How would I do this in python?
String.Format("www.someurl.com/{0}/blah.html", 100);
I'm beginning to really like python, thanks for all your help!
A:
From Python 2.6:
>>> "www.someurl.com/{0}/blah.html".format(100)
'www.someurl.com/100/blah.html'
To support older environments, the % operator has a similar role:
>>> "www.someurl.com/%d/blah.html" % 100
'www.someurl.com/100/blah.html'
If you would like to support named arguments, then you can can pass a dict.
>>> url_args = {'num' : 100 }
>>> "www.someurl.com/%(num)d/blah.html" % url_args
'www.someurl.com/100/blah.html'
In general, when types need to be mixed, I recommend string formatting:
>>> '%d: %s' % (1, 'string formatting',)
'1: string formatting'
String formatting coerces objects into strings by using their __str__ methods.[*] There is much more detailed documentation available on Python string formatting in the docs. This behaviour is different in Python 3+, as all strings are unicode.
If you have a list or tuple of strings, the join method is quite convenient. It applies a separator between all elements of the iterable.
>>> ' '.join(['2:', 'list', 'of', 'strings'])
'2: list of strings'
If you are ever in an environment where you need to support a legacy environment, (e.g. Python <2.5), you should generally avoid string concatenation. See the article referenced in the comments.
[*] Unicode strings use the __unicode__ method.
>>> u'3: %s' % ':)'
u'3: :)'
A:
>>> "www.someurl.com/{0}/blah.html".format(100)
'www.someurl.com/100/blah.html'
you can skip 0 in python 2.7 or 3.1.
A:
Additionally to string formatting, you can always print like this:
print "hello", 10
Works since those are separate arguments and print converts non-string arguments to strings (and inserts a space in between).
A:
For string formatting that includes different types of values, use the % to insert the value into a string:
>>> intvalu = 10
>>> print "hello %i"%intvalu
hello 10
>>>
so in your example:
>>>print "www.someurl.com/%i/blah.html"%100
www.someurl.com/100/blah.html
In this example I'm using %i as the stand-in. This changes depending on what variable type you need to use. %s would be for strings. There is a list here on the python docs website.
| String formatting issues and concatenating a string with a number | I'm coming from a c# background, and I do this:
Console.Write("some text" + integerValue);
So the integer automatically gets converted to a string and it outputs.
In python I get an error when I do:
print 'hello' + 10
Do I have to convert to string everytime?
How would I do this in python?
String.Format("www.someurl.com/{0}/blah.html", 100);
I'm beginning to really like python, thanks for all your help!
| [
"From Python 2.6:\n>>> \"www.someurl.com/{0}/blah.html\".format(100)\n'www.someurl.com/100/blah.html'\n\nTo support older environments, the % operator has a similar role:\n>>> \"www.someurl.com/%d/blah.html\" % 100\n'www.someurl.com/100/blah.html'\n\nIf you would like to support named arguments, then you can can pa... | [
4,
3,
2,
1
] | [] | [] | [
"formatting",
"python"
] | stackoverflow_0003380029_formatting_python.txt |
Q:
Python Window Resize
Using Python + PyGTK.
Is there a signal/event way of checking for a window resize? If so then what is the easiest way of implementing and using this signal.
A:
a gtk.Window is also a gtk.Container, so it answers to the check-resize signal.
Here's minimal sample code:
import gtk
def changed(window):
print 'I have resized.'
w = gtk.Window()
w.connect('check-resize', changed)
w.show()
gtk.main()
| Python Window Resize | Using Python + PyGTK.
Is there a signal/event way of checking for a window resize? If so then what is the easiest way of implementing and using this signal.
| [
"a gtk.Window is also a gtk.Container, so it answers to the check-resize signal.\nHere's minimal sample code:\nimport gtk\n\ndef changed(window):\n print 'I have resized.'\n\nw = gtk.Window()\nw.connect('check-resize', changed)\nw.show()\ngtk.main()\n\n"
] | [
7
] | [] | [] | [
"gtk",
"pygtk",
"python"
] | stackoverflow_0003380003_gtk_pygtk_python.txt |
Q:
Python and MySQL compile version
How do I check if my python and mysql are 32 bit installations or 64 bit?
A:
You can use the file command :
file `which python`
file `which mysql`
The file command is available on all UNIX-based systems.
A:
readelf -h $(which mysqld) | grep Class
readelf -h $(which python) | grep Class
Seems to work for me. The readelf command is part of the GNU binutils.
| Python and MySQL compile version | How do I check if my python and mysql are 32 bit installations or 64 bit?
| [
"You can use the file command :\n\nfile `which python`\nfile `which mysql`\n\nThe file command is available on all UNIX-based systems.\n",
"readelf -h $(which mysqld) | grep Class\nreadelf -h $(which python) | grep Class\n\nSeems to work for me. The readelf command is part of the GNU binutils.\n"
] | [
3,
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003379142_mysql_python.txt |
Q:
Problem making a GET request and spoof User-Agent in urllib2
With this code, urllib2 make a GET request:
#!/usr/bin/python
import urllib2
req = urllib2.Request('http://www.google.fr')
req.add_header('User-Agent', '')
response = urllib2.urlopen(req)
With this one (which is almost the same), a POST request:
#!/usr/bin/python
import urllib2
headers = { 'User-Agent' : '' }
req = urllib2.Request('http://www.google.fr', '', headers)
response = urllib2.urlopen(req)
My question is: how can i make a GET request with the second code style ?
The documentation (http://docs.python.org/release/2.6.5/library/urllib2.html) says that
headers should be a dictionary, and
will be treated as if add_header() was
called with each key and value as
arguments
Yeah, except that in order to use the headers parameter, you have to pass data, and when data is passed, the request become a POST.
Any help will be very appreciated.
A:
Use:
req = urllib2.Request('http://www.google.fr', None, headers)
or:
req = urllib2.Request('http://www.google.fr', headers=headers)
| Problem making a GET request and spoof User-Agent in urllib2 | With this code, urllib2 make a GET request:
#!/usr/bin/python
import urllib2
req = urllib2.Request('http://www.google.fr')
req.add_header('User-Agent', '')
response = urllib2.urlopen(req)
With this one (which is almost the same), a POST request:
#!/usr/bin/python
import urllib2
headers = { 'User-Agent' : '' }
req = urllib2.Request('http://www.google.fr', '', headers)
response = urllib2.urlopen(req)
My question is: how can i make a GET request with the second code style ?
The documentation (http://docs.python.org/release/2.6.5/library/urllib2.html) says that
headers should be a dictionary, and
will be treated as if add_header() was
called with each key and value as
arguments
Yeah, except that in order to use the headers parameter, you have to pass data, and when data is passed, the request become a POST.
Any help will be very appreciated.
| [
"Use:\nreq = urllib2.Request('http://www.google.fr', None, headers)\n\nor:\nreq = urllib2.Request('http://www.google.fr', headers=headers)\n\n"
] | [
4
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0003380183_python_urllib2.txt |
Q:
How do I use gluLookAt properly?
I don't want to get into complex trigonometry to calculate rotations and things like that for my 3D world so gluLookAt seems like a nice alternative. According to the documentation all I need to do is place 3 coordinates for the cameras position, three for what I should be looking at and an "up" position. The last made no sense until I assumed it had to be at right angles with the line of sight in the direction the top of the screen should be.
It doesn't work like that at all. I have some python code. This is the code which initialises some data and some mode code for when I enter this part of the game:
def init(self):
self.game_over = False
self.z = -30
self.x = 0
def transfer(self):
#Make OpenGL use 3D
game.engage_3d(45,0.1,100)
gluLookAt(0,0,-30,0,0,0,0,1,0)
"game.engage_3d(45,0.1,100)" basically sets up the projection matrix to have a 45 degree angle of view and near and far coordinates of 0.1 and 100.
The first gluLookAt puts the camera in the correct position, nicely.
I have a cube drawn with the centre of (0,0,0) and it works fine without gluLookAt. Before I draw it I have this code:
gluLookAt(self.x,0,self.z,0,0,0,0,1,0)
if game.key(KEY_UP):
self.z += 2.0/game.get_fps()
if game.key(KEY_DOWN):
self.z -= 2.0/game.get_fps()
if game.key(KEY_LEFT):
self.x += 2.0/game.get_fps()
if game.key(KEY_RIGHT):
self.x -= 2.0/game.get_fps()
Now from that, the up position should always be the same as it's always at right angles. What I'd have thought it would do is move forward and back the z-axis with the up and down keys and left and right through the x-axis with the left and right keys. What actually happens, is when I use the left and right keys, the cube will rotate around the "eye" being accelerated by the keys. The up key causes another cube from nowhere to slice through the screen and hit the first cube. THe down key brings the mysterious cloned cube back. This can be combined with the rotation to give a completely different outcome as the documentation said would arise.
What on earth is wrong?
Thank you.
A:
(The intuition behind the "up" vector in gluLookAt is simple: Look at anything. Now tilt your head 90 degrees. Where you are hasn't changed, the direction you're looking at hasn't changed, but the image in your retina clearly has. What's the difference? Where the top of your head is pointing to. That's the up vector.)
But to answer your question: gluLookAt calls should not be concatenated. In other words, the only pattern in which it's OK to use gluLookAt if you don't know exactly how it works is the following:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(...);
# do not touch the modelview matrix anymore!
It seems from your code that you're doing something like this:
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(...);
# some stuff..
gluLookAt(...);
This will generate weird results, because gluLookAt multiplies the current matrix by the viewing matrix it computes. If you want to concatenate transformations you're really better off figuring out how to make glTranslate, glScale and glRotatef work for you. Even better, you should learn how the coordinate transformations work and stick to glMultMatrix.
| How do I use gluLookAt properly? | I don't want to get into complex trigonometry to calculate rotations and things like that for my 3D world so gluLookAt seems like a nice alternative. According to the documentation all I need to do is place 3 coordinates for the cameras position, three for what I should be looking at and an "up" position. The last made no sense until I assumed it had to be at right angles with the line of sight in the direction the top of the screen should be.
It doesn't work like that at all. I have some python code. This is the code which initialises some data and some mode code for when I enter this part of the game:
def init(self):
self.game_over = False
self.z = -30
self.x = 0
def transfer(self):
#Make OpenGL use 3D
game.engage_3d(45,0.1,100)
gluLookAt(0,0,-30,0,0,0,0,1,0)
"game.engage_3d(45,0.1,100)" basically sets up the projection matrix to have a 45 degree angle of view and near and far coordinates of 0.1 and 100.
The first gluLookAt puts the camera in the correct position, nicely.
I have a cube drawn with the centre of (0,0,0) and it works fine without gluLookAt. Before I draw it I have this code:
gluLookAt(self.x,0,self.z,0,0,0,0,1,0)
if game.key(KEY_UP):
self.z += 2.0/game.get_fps()
if game.key(KEY_DOWN):
self.z -= 2.0/game.get_fps()
if game.key(KEY_LEFT):
self.x += 2.0/game.get_fps()
if game.key(KEY_RIGHT):
self.x -= 2.0/game.get_fps()
Now from that, the up position should always be the same as it's always at right angles. What I'd have thought it would do is move forward and back the z-axis with the up and down keys and left and right through the x-axis with the left and right keys. What actually happens, is when I use the left and right keys, the cube will rotate around the "eye" being accelerated by the keys. The up key causes another cube from nowhere to slice through the screen and hit the first cube. THe down key brings the mysterious cloned cube back. This can be combined with the rotation to give a completely different outcome as the documentation said would arise.
What on earth is wrong?
Thank you.
| [
"(The intuition behind the \"up\" vector in gluLookAt is simple: Look at anything. Now tilt your head 90 degrees. Where you are hasn't changed, the direction you're looking at hasn't changed, but the image in your retina clearly has. What's the difference? Where the top of your head is pointing to. That's the up ve... | [
39
] | [] | [] | [
"graphics",
"opengl",
"pyopengl",
"python"
] | stackoverflow_0003380100_graphics_opengl_pyopengl_python.txt |
Q:
Escape quotes contained within certain html tags
I've done a mysqldump of a large database, ~300MB. It has made an error though, it has not escaped any quotes contained in any <o:p>...</o:p> tags. Here's a sample:
...Text here\' escaped correctly, <o:p> But text in here isn't. </o:p> Out here all\'s well again...
Is it possible to write a script (preferably in Python, but I'll take anything!) that would be able to scan and fix these errors automatically? There's quite a lot of them and Notepad++ can't handle a file of that size very well...
A:
If the "lines" your file is divided into are of reasonable lengths, and there are no binary sequences in it that "reading as text" would break, you can use fileinput's handy "make believe I'm rewriting a file in place" functionality:
import re
import fileinput
tagre = re.compile(r"<o:p>.*?</o:p>")
def sub(mo):
return mo.group().replace(r"'", r"\'")
for line in fileinput.input('thefilename', inplace=True):
print tagre.sub(sub, line),
If not, you'll have to simulate the "in-place rewriting" yourself, e.g. (oversimplified...):
with open('thefilename', 'rb') as inf:
with open('fixed', 'wb') as ouf:
while True:
b = inf.read(1024*1024)
if not b: break
ouf.write(tagre.sub(sub, b))
and then move 'fixed' to take place of 'thefilename' (either in code, or manually) if you need that filename to remain after the fixing.
This is oversimplified because one of the crucial <o:p> ... </o:p> parts might end up getting split between two successive megabyte "blocks" and therefore not identified (in the first example, I'm assuming each such part is always fully contained within a "line" -- if that's not the case then you should not use that code, but the following, anyway). Fixing this requires, alas, more complicated code...:
with open('thefilename', 'rb') as inf:
with open('fixed', 'wb') as ouf:
while True:
b = getblock(inf)
if not b: break
ouf.write(tagre.sub(sub, b))
with e.g.
partsofastartag = '<', '<o', '<o:', '<o:p'
def getblock(inf):
b = ''
while True:
newb = inf.read(1024 * 1024)
if not newb: return b
b += newb
if any(b.endswith(p) for p in partsofastartag):
continue
if b.count('<o:p>') != b.count('</o:p>'):
continue
return b
As you see, this is pretty delicate code, and therefore, what with it being untested, I can't know that it is correct for your problem. In particular, can there be cases of <o:p> that are NOT matched by a closing </o:p> or vice versa? If so, then a call to getblock could end up returning the whole file in quite a costly way, and even the RE matching and substitution might backfire (the latter would also occur if SOME of the single-quotes in such tags are already properly escaped, but not all).
If you have at least a GB or so, avoiding the delicate issues with block division, at least, IS feasible, since everything should fit in memory, making the code much simpler:
with open('thefilename', 'rb') as inf:
with open('fixed', 'wb') as ouf:
b = inf.read()
ouf.write(tagre.sub(sub, b))
However, the other issues mentioned above (possible unbalanced opening/closing tags, etc) might remain -- only you can study your existing defective data and see if it affords such a reasonably simple approach at fixing!
| Escape quotes contained within certain html tags | I've done a mysqldump of a large database, ~300MB. It has made an error though, it has not escaped any quotes contained in any <o:p>...</o:p> tags. Here's a sample:
...Text here\' escaped correctly, <o:p> But text in here isn't. </o:p> Out here all\'s well again...
Is it possible to write a script (preferably in Python, but I'll take anything!) that would be able to scan and fix these errors automatically? There's quite a lot of them and Notepad++ can't handle a file of that size very well...
| [
"If the \"lines\" your file is divided into are of reasonable lengths, and there are no binary sequences in it that \"reading as text\" would break, you can use fileinput's handy \"make believe I'm rewriting a file in place\" functionality:\n import re\n import fileinput\n\n tagre = re.compile(r\"<o:p>.*?</o:... | [
4
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0003380146_mysql_python.txt |
Q:
Check if specific wsgi handler is running
I am creating a mapping application that uses a WSGI service and needs a different config file for each map. Currently, I launch the service with:
import os, sys
tilecachepath = '/usr/local/lib/python2.6/dist-packages/TileCache-2.10-py2.6.egg/TileCache'
sys.path.append(tilecachepath)
from TileCache.Service import Service, wsgiHandler
from paste.request import parse_formvars
theService = {}
def wsgiApp (environ, start_response):
global theService
fields = parse_formvars(environ)
cfgs = fields['cfg']
theService = Service.load(cfgs)
return wsgiHandler(environ, start_response, theService)
application = wsgiApp
This is obviously launching way too many handlers! How can I determine if a specific handler is already running? Is there anything in the apache config that I need to adjust so that handlers time out properly?
A:
WSGI itself offers no way of knowing what layers are already wrapping a certain application, nor does Apache know about that. I would recommend having the wsgiHandler record its presence, so that you can avoid using it multiple times. If you can't alter the existing code, you can do it with your own wrappers for that code's layer (and use the environment, directly or indirectly, to do the recording of what's already active).
| Check if specific wsgi handler is running | I am creating a mapping application that uses a WSGI service and needs a different config file for each map. Currently, I launch the service with:
import os, sys
tilecachepath = '/usr/local/lib/python2.6/dist-packages/TileCache-2.10-py2.6.egg/TileCache'
sys.path.append(tilecachepath)
from TileCache.Service import Service, wsgiHandler
from paste.request import parse_formvars
theService = {}
def wsgiApp (environ, start_response):
global theService
fields = parse_formvars(environ)
cfgs = fields['cfg']
theService = Service.load(cfgs)
return wsgiHandler(environ, start_response, theService)
application = wsgiApp
This is obviously launching way too many handlers! How can I determine if a specific handler is already running? Is there anything in the apache config that I need to adjust so that handlers time out properly?
| [
"WSGI itself offers no way of knowing what layers are already wrapping a certain application, nor does Apache know about that. I would recommend having the wsgiHandler record its presence, so that you can avoid using it multiple times. If you can't alter the existing code, you can do it with your own wrappers for... | [
2
] | [] | [] | [
"apache",
"gis",
"mod_wsgi",
"python"
] | stackoverflow_0003380303_apache_gis_mod_wsgi_python.txt |
Q:
PyGTK connect_signals
Ok so I have a little test program here:
This is in my file that I load through gtk.Builder
<object class="GtkWindow" id="mainWindow">
<property name="default_width">500</property>
<property name="default_height">250</property>
<signal name="delete_event" handler="endProgram" />
</object>
I then use this:
def endProgram ():
print "end";
rofl = gtk.Builder();
rofl.add_from_file("mainwindow.ui");
win = rofl.get_object("mainWindow");
rofl.connect_signals("mainWindow");
win.show_all();
gtk.main();
Yet when I go to run that it complains that I am missing a handler for the mainWindow object.
I have tried doing rofl.connect_signals(win); as well
A:
Per the docs, connect_signals takes as the argument a mapping or instance, and
uses Python's introspective features
to look at the keys (if object is a
mapping) or attributes (if object is
an instance) and tries to match them
with the signal handler names given in
the interface description. The
callbacks referenced by each matched
key or attribute are connected to
their matching signals.
So for example when you pass "mainwindow", which is an instance of str, the attributes are e.g. such method names as upper, lower, isalpha, and the like -- nothing to do with anything at all that you might be remotely interested about. And why would you want the attributes of win to handle signals, either? IOW, what do you expect connect_signals to do?
A more typical example use can be found e.g. in this SO question and this tutorial, which offers among others the following Python example:
class TutorialTextEditor:
def on_window_destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
builder = gtk.Builder()
builder.add_from_file("tutorial.xml")
self.window = builder.get_object("window")
builder.connect_signals(self)
as you see, here connect_signals is used in the typical way -- i.e., passing an object (self) with an on_window_destroy method that (by introspection) will be used as the handler for the signal raised on window destruction.
| PyGTK connect_signals | Ok so I have a little test program here:
This is in my file that I load through gtk.Builder
<object class="GtkWindow" id="mainWindow">
<property name="default_width">500</property>
<property name="default_height">250</property>
<signal name="delete_event" handler="endProgram" />
</object>
I then use this:
def endProgram ():
print "end";
rofl = gtk.Builder();
rofl.add_from_file("mainwindow.ui");
win = rofl.get_object("mainWindow");
rofl.connect_signals("mainWindow");
win.show_all();
gtk.main();
Yet when I go to run that it complains that I am missing a handler for the mainWindow object.
I have tried doing rofl.connect_signals(win); as well
| [
"Per the docs, connect_signals takes as the argument a mapping or instance, and\n\nuses Python's introspective features\n to look at the keys (if object is a\n mapping) or attributes (if object is\n an instance) and tries to match them\n with the signal handler names given in\n the interface description. The\n... | [
3
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0003380426_pygtk_python.txt |
Q:
Replacing value in all cursor rows
Using SQLite and Python 3.1, I want to display currency data in a HTML table via. a template which accepts a cursor as a parameter. Hence all currency values must have 2 decimal places, but SQLite stores them as float type (even though the structure states decimal :-( ) so some must be converted before display (eg. I want 12.1 displayed as 12.10).
The code goes something like this (simplified for illustration)...
import sqlite3
con = sqlite3.connect("mydb")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select order_no, amount from orders where cust_id=123")
for row in cur:
row['amount'] = format(row['amount'],'%.2f')
The last command throws the error "# builtins.TypeError: 'sqlite3.Row' object does not support item assignment"
How can I solve the problem whereby the row object values cannot be changed? Could I convert the cursor to a list of dictionaries (one for each row, eg. [{'order_no':1, 'amount':12.1}, {'order_no':2, 'amount':6.32}, ...]), then format the 'amount' value for each item? If so, how can I do this?
Are there any better solutions for achieving my goal? Any help would be appreciated.
TIA,
Alan
A:
Yep:
cur.execute("select order_no, amount from orders where cust_id=123")
dictrows = [dict(row) for row in cur]
for r in dictrows:
r['amount'] = format(r['amount'],'%.2f')
There are other ways, but this one seems the simplest and most direct one.
A:
An alternative is to store your value as an integer number of cents (which is always an exact amount, no rounding), and then convert to dollars when displaying for reports using divmod:
>>> value_in_cents = 133
>>> print "$%d.%d" % divmod(value_in_cents,100)
$1.33
| Replacing value in all cursor rows | Using SQLite and Python 3.1, I want to display currency data in a HTML table via. a template which accepts a cursor as a parameter. Hence all currency values must have 2 decimal places, but SQLite stores them as float type (even though the structure states decimal :-( ) so some must be converted before display (eg. I want 12.1 displayed as 12.10).
The code goes something like this (simplified for illustration)...
import sqlite3
con = sqlite3.connect("mydb")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select order_no, amount from orders where cust_id=123")
for row in cur:
row['amount'] = format(row['amount'],'%.2f')
The last command throws the error "# builtins.TypeError: 'sqlite3.Row' object does not support item assignment"
How can I solve the problem whereby the row object values cannot be changed? Could I convert the cursor to a list of dictionaries (one for each row, eg. [{'order_no':1, 'amount':12.1}, {'order_no':2, 'amount':6.32}, ...]), then format the 'amount' value for each item? If so, how can I do this?
Are there any better solutions for achieving my goal? Any help would be appreciated.
TIA,
Alan
| [
"Yep:\ncur.execute(\"select order_no, amount from orders where cust_id=123\")\ndictrows = [dict(row) for row in cur]\nfor r in dictrows:\n r['amount'] = format(r['amount'],'%.2f')\n\nThere are other ways, but this one seems the simplest and most direct one.\n",
"An alternative is to store your value as an intege... | [
10,
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003380360_python_sqlite.txt |
Q:
Create Explorer.exe's File - Context Menu in WxPython application
I have a WxPython app that, among other things, has a integrated file-browser.
I want to be able to create a system-default file context menu (e.g. what you get if you right-click on a file in windows explorer) when a user right clicks on one of the items within my application.
Note: I already know how to create my own context menu (e.g. wx.EVT_LIST_ITEM_RIGHT_CLICK), I want the Windows context menu.
To clarify, I do not want, or need to modify the existing system context menu, I want to be able to display it for a specific file within my application.
Basically, I know what was right clicked on, and where the mouse pointer is (if it's needed). I want to create the system context menu there, just like it works in windows explorer.
A:
If you have python win32 installed, then look under the directory <PYTHON>/lib/site-packages/win32comext/shell/demos/servers. This contains a file context_menu.py which has sample code for creating a shell extension.
Update: I think you want the folder_view.py sample.
| Create Explorer.exe's File - Context Menu in WxPython application | I have a WxPython app that, among other things, has a integrated file-browser.
I want to be able to create a system-default file context menu (e.g. what you get if you right-click on a file in windows explorer) when a user right clicks on one of the items within my application.
Note: I already know how to create my own context menu (e.g. wx.EVT_LIST_ITEM_RIGHT_CLICK), I want the Windows context menu.
To clarify, I do not want, or need to modify the existing system context menu, I want to be able to display it for a specific file within my application.
Basically, I know what was right clicked on, and where the mouse pointer is (if it's needed). I want to create the system context menu there, just like it works in windows explorer.
| [
"If you have python win32 installed, then look under the directory <PYTHON>/lib/site-packages/win32comext/shell/demos/servers. This contains a file context_menu.py which has sample code for creating a shell extension.\nUpdate: I think you want the folder_view.py sample.\n"
] | [
0
] | [] | [] | [
"python",
"user_interface",
"windows_xp",
"wxpython"
] | stackoverflow_0003380986_python_user_interface_windows_xp_wxpython.txt |
Q:
Mod_Rewrite existing file check goes pear shaped, or passes wrong querystring
I'm using Apache, Python (fastcgi), mod_rewrite.
I want
http://foo/bar
to redirect internally to
http://main.py?q=foo/bar
Now my .htacess file contains
Options +ExecCGI
AddHandler cgi-script .py
DirectoryIndex main.py
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) main.py?q=$1
Normally works fine. Redirects to main.py with the query-string q=foo/bar
But if I have a script named foo.py it instead directs to foo.py instead of main.py.
I tried removing the RewriteConds and have the RewriteRule alone as a catch-all.
Then it always redirects to main.py ok, but the query-string passed to my script is q=main.py where it should be q=foo/bar
Now there's various kludges I could try involving restructuring my code, file layout etc, but I'd like figure out what's going on before it causes more problems down the track.
So I want to either a) stop it thinking that foo means foo.py or b) make it skip the existing file checks completely and pass on the correct query-string.
A:
It sounds like a problem with content negotiation. Try adding...
Options -Multiviews
...at the top of your .htaccess file.
A:
Your first problem is caused by MultiViews, which is resolving the non-existent resource foo/bar to the existing file foo.py, then likely passing it PATH_INFO of /bar. You can disable it in your .htaccess file by modifying your Options:
Options -MultiViews +ExecCGI
Using your original ruleset with MultiViews disabled should solve your problem. For the sake of completeness though, the reason why the query string ends up being q=main.py is because of the how the request is processed when you remove the rewrite conditions:
mod_rewrite receives the request, and foo/bar matches .* and is rewritten to main.py?q=foo/bar
mod_rewrite performs an internal redirect and assigns itself as the handler
The redirect is re-processed by mod_rewrite, and main.py matches .* and is rewritten to main.py?q=main.py
mod_rewrite performs an internal redirect and assigns itself as the handler
The redirect is re-processed by mod_rewrite, and main.py matches .* and is rewritten to main.py?q=main.py
mod_rewrite realizes that you're going to enter an infinite loop redirecting the same request to itself, and stops the redirection process
| Mod_Rewrite existing file check goes pear shaped, or passes wrong querystring | I'm using Apache, Python (fastcgi), mod_rewrite.
I want
http://foo/bar
to redirect internally to
http://main.py?q=foo/bar
Now my .htacess file contains
Options +ExecCGI
AddHandler cgi-script .py
DirectoryIndex main.py
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) main.py?q=$1
Normally works fine. Redirects to main.py with the query-string q=foo/bar
But if I have a script named foo.py it instead directs to foo.py instead of main.py.
I tried removing the RewriteConds and have the RewriteRule alone as a catch-all.
Then it always redirects to main.py ok, but the query-string passed to my script is q=main.py where it should be q=foo/bar
Now there's various kludges I could try involving restructuring my code, file layout etc, but I'd like figure out what's going on before it causes more problems down the track.
So I want to either a) stop it thinking that foo means foo.py or b) make it skip the existing file checks completely and pass on the correct query-string.
| [
"It sounds like a problem with content negotiation. Try adding...\nOptions -Multiviews\n\n...at the top of your .htaccess file.\n",
"Your first problem is caused by MultiViews, which is resolving the non-existent resource foo/bar to the existing file foo.py, then likely passing it PATH_INFO of /bar. You can disab... | [
1,
1
] | [] | [] | [
".htaccess",
"mod_rewrite",
"python"
] | stackoverflow_0003381036_.htaccess_mod_rewrite_python.txt |
Q:
How do I delete an object in a django relation (While keeping all related objects)?
I have the following model:
One
name (Char)
Many
one (ForeignKey,blank=True,null=True)
title (Char)
I want to delete a One instance and all related objects should loose their relation to the One instance. At the moment my code looks like this:
one=One.objects.get(<some criterion>)
more=Many.objects.filter(one=one)
for m in more
m.one=None
m.save()
#and finally:
one.delete()
what does the code do?
It finds the object, that should be deleted then searches for related objects, sets their ForeignKey to None and finally deletes the One instance. But somewhere in that process it also manages to kill all related objects (Many instances) in the process.
My question is: Why are those related objects deleted and how do I prevent this?
A:
The code given is correct. My problem when asking the question was a typo in my implementation.
shame on me
well... there is still a bit that could be improved on:
more=Many.objects.filter(one=one)
for m in more
m.one=None
m.save()
#and finally:
one.delete()
can be written as:
for m in one.many_set.all()
m.one=None
m.save()
one.delete()
which is equivalent to:
one.many_set.clear()
one.delete()
A:
You can use update() in first place:
Many.objects.filter(one=one).update(one=None)
I think that Django deletes related object on program level (without on delete cascade in DBMS). So probably your objects are in some kind of cache and Django still thinks that they are related to one object.
Try to list the related objects before you delete.
print one.many_set
one.delete()
If you still have any objects in this set you probably should fetch one from DB again, and then delete. Or you can use delete():
One.objects.filter(<criteria>).delete()
| How do I delete an object in a django relation (While keeping all related objects)? | I have the following model:
One
name (Char)
Many
one (ForeignKey,blank=True,null=True)
title (Char)
I want to delete a One instance and all related objects should loose their relation to the One instance. At the moment my code looks like this:
one=One.objects.get(<some criterion>)
more=Many.objects.filter(one=one)
for m in more
m.one=None
m.save()
#and finally:
one.delete()
what does the code do?
It finds the object, that should be deleted then searches for related objects, sets their ForeignKey to None and finally deletes the One instance. But somewhere in that process it also manages to kill all related objects (Many instances) in the process.
My question is: Why are those related objects deleted and how do I prevent this?
| [
"The code given is correct. My problem when asking the question was a typo in my implementation.\nshame on me\nwell... there is still a bit that could be improved on:\nmore=Many.objects.filter(one=one)\nfor m in more\n m.one=None\n m.save()\n#and finally:\none.delete()\n\ncan be written as:\nfor m in one.many... | [
2,
1
] | [] | [] | [
"django",
"django_database",
"python"
] | stackoverflow_0003375374_django_django_database_python.txt |
Q:
xml validation: validating a URI type
I'm using python's lxml to validate xmls against a schema. I have a schema with an element:
<xs:element name="link-url" type="xs:anyURL"/>
and I test, for example, this (part of an) xml:
<a link-url="server/path"/>
I would like this test to FAIL because the link-url doesn't start with http://. I tried switching anyURI to anyURL but this results in an exception - it's not a valid tag.
Is this possible with lxml? is it possible at all with schema validation?
A:
(I'm pretty sure xs:anyURL is not valid. The XML Schema standard calls it anyURI. And since link-url is an attribute, shouldn't you be using xs:attribute instead of xs:element?)
You could restrict the URIs by creating a new simpleType based on it, and put a restriction on the pattern. For example,
#!/usr/bin/env python2.6
from lxml import etree
from StringIO import StringIO
schema_doc = etree.parse(StringIO('''
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="httpURL">
<xs:restriction base="xs:anyURI">
<xs:pattern value='https?://.+'/>
<!-- accepts only http:// or https:// URIs. -->
</xs:restriction>
</xs:simpleType>
<xs:element name="a">
<xs:complexType>
<xs:attribute name="link-url" type="httpURL"/>
</xs:complexType>
</xs:element>
</xs:schema>
''')) #/
schema = etree.XMLSchema(schema_doc)
schema.assertValid(etree.parse(StringIO('<a link-url="http://sd" />')))
assert not schema(etree.parse(StringIO('<a link-url="server/path" />')))
| xml validation: validating a URI type | I'm using python's lxml to validate xmls against a schema. I have a schema with an element:
<xs:element name="link-url" type="xs:anyURL"/>
and I test, for example, this (part of an) xml:
<a link-url="server/path"/>
I would like this test to FAIL because the link-url doesn't start with http://. I tried switching anyURI to anyURL but this results in an exception - it's not a valid tag.
Is this possible with lxml? is it possible at all with schema validation?
| [
"(I'm pretty sure xs:anyURL is not valid. The XML Schema standard calls it anyURI. And since link-url is an attribute, shouldn't you be using xs:attribute instead of xs:element?)\nYou could restrict the URIs by creating a new simpleType based on it, and put a restriction on the pattern. For example,\n#!/usr/bin/env... | [
3
] | [] | [] | [
"python",
"validation",
"xml",
"xsd"
] | stackoverflow_0003381507_python_validation_xml_xsd.txt |
Q:
How can I vectorize a function in numpy with multiple arguments?
I am trying to do a fit to a given function using Scipy. Scipy.optimize.leastsq needs a vectorized function as one of the input parameters.
This all works fine, but now I have a more complicated function which is not vectorized automatically by Scipy/Numpy.
def f1(a, parameters):
b, c = parameters
result = scipy.integrate.quad(integrand, lower, upper, (a, b, c))
return result
or to give a closed example numpy.vectorize also does not work with
def f2(a, parameters):
b, c = parameters
return a+b+c
Is there a possibility to vectorize these functions in Scipy/Numpy?
Thank you for any help!
Alexander
A:
Sorry, I'm not sure what the question is. Python *args collects any number of args,
which a function can unpack as it pleases; see
docs.python.org/tutorial/...
import numpy as np
from scipy.integrate import quad
def f2( a, *args ):
print "args:", args
return a + np.sum( args, axis=0 )
x = np.ones(3)
print f2( x, x*2, x*3 )
def quadf( *args ):
print "quadf args:", args
return 1
quad( quadf, 0, 1, (2,3) )
| How can I vectorize a function in numpy with multiple arguments? | I am trying to do a fit to a given function using Scipy. Scipy.optimize.leastsq needs a vectorized function as one of the input parameters.
This all works fine, but now I have a more complicated function which is not vectorized automatically by Scipy/Numpy.
def f1(a, parameters):
b, c = parameters
result = scipy.integrate.quad(integrand, lower, upper, (a, b, c))
return result
or to give a closed example numpy.vectorize also does not work with
def f2(a, parameters):
b, c = parameters
return a+b+c
Is there a possibility to vectorize these functions in Scipy/Numpy?
Thank you for any help!
Alexander
| [
"Sorry, I'm not sure what the question is. Python *args collects any number of args,\nwhich a function can unpack as it pleases; see\ndocs.python.org/tutorial/...\nimport numpy as np\nfrom scipy.integrate import quad\n\ndef f2( a, *args ):\n print \"args:\", args\n return a + np.sum( args, axis=0 )\n\nx = np.... | [
2
] | [] | [] | [
"numpy",
"python",
"scipy"
] | stackoverflow_0003376018_numpy_python_scipy.txt |
Q:
Django: autoslug -> custom slugifier
I have a prob. I'm trying to create a custom slugify functiom. I use django.autoslug. Due to autoslug documentation I was able to create a custom slugifier, but it needs to be improved and I do not know how do I realize that.
So I have a string (book title) i.e. .NET Framework 4.0 with C# & VB in VisualStudio 2010. I want to slugify it so that it looks like this: dotnet-framework-4point0-with-cshapr-and-vb-in-visualstudio-2010
My current function looks like this:
def custom_slug(value, *args, **kwargs):
associations_dict = {'#':'sharp', '.':'dot', '&':'and'}
for searcg_char in associations_dict.keys():
if search_char in value:
value = value.replace(search_char, associations_dict[search_char])
return def_slugify(value)
As you can see, my function replaces all dots . with 'dot'. So my string will be changed into dotnet-framework-4dot0-with-csharp-and-vb-in-visualstudio-2010
I suggest, I should use RegEx, but I don't know how to do this and how do I replace matched string with right 'dot/point-replacement'
Ideas ?!
P.S. Sorry for bad English
A:
import re
point = re.compile( r"(?<=\d)\.(?=\d)" )
point.sub( value, "point" )
to change the . s that should be "point" , and then do str.replace to change the others.
Explanation
point matches a . which is sandwiched between two digits.
(?<=spam)ham(?=eggs) is a (positive) lookaround. It means "match ham, as long as it is preceded by spam and followed by eggs". In other words, it tells the regex engine to "look around" the pattern that it is matching.
| Django: autoslug -> custom slugifier | I have a prob. I'm trying to create a custom slugify functiom. I use django.autoslug. Due to autoslug documentation I was able to create a custom slugifier, but it needs to be improved and I do not know how do I realize that.
So I have a string (book title) i.e. .NET Framework 4.0 with C# & VB in VisualStudio 2010. I want to slugify it so that it looks like this: dotnet-framework-4point0-with-cshapr-and-vb-in-visualstudio-2010
My current function looks like this:
def custom_slug(value, *args, **kwargs):
associations_dict = {'#':'sharp', '.':'dot', '&':'and'}
for searcg_char in associations_dict.keys():
if search_char in value:
value = value.replace(search_char, associations_dict[search_char])
return def_slugify(value)
As you can see, my function replaces all dots . with 'dot'. So my string will be changed into dotnet-framework-4dot0-with-csharp-and-vb-in-visualstudio-2010
I suggest, I should use RegEx, but I don't know how to do this and how do I replace matched string with right 'dot/point-replacement'
Ideas ?!
P.S. Sorry for bad English
| [
"import re\npoint = re.compile( r\"(?<=\\d)\\.(?=\\d)\" )\npoint.sub( value, \"point\" )\n\nto change the . s that should be \"point\" , and then do str.replace to change the others.\nExplanation\npoint matches a . which is sandwiched between two digits.\n(?<=spam)ham(?=eggs) is a (positive) lookaround. It means \"... | [
0
] | [] | [] | [
"django",
"python",
"regex",
"slug"
] | stackoverflow_0003382492_django_python_regex_slug.txt |
Q:
How do I get some string values from Pylons controller be assigned to JavaScript variables with Mako?
I'm developing under Pylons using Mako templates. The problem is that I need to assign a string from some attribute of tmpl_context to a JavaScript variable in a page body. The additional problem is that this string can be quite arbitrary, ie can contain such characters like ", ', <, >, etc... Is there a common way to do such assignment?
I've tried something like:
<script>
...
var a = "${c.my_string}";
...
</script>
but I get quotation marks and HTML special characters escaped. But I would not like to disable filtering because of possible danger of executing of unexpected code.
A:
You have some arbitrary data in c.my_string, and therefore do not want to use "|n", right?
Quickiest way to escape it in JS-style escaping would be
var a = ${c.my_string.__repr__()|n}; # Note lack of "" around it!
However I'm unsure about <> characters (with something like </script> inserted), maybe you would also want to use .replace('<', '<');
For unicode you will need to also strip 'u' character from start of the string.
A:
if I understood what you want, try webhelpers.html.literal:
helper:
from webhelpers.html import literal
html:
<script>
document.write('${h.literal(c.my_string)}');
</script>
this is better than ${c.mystring|n} escaping html
| How do I get some string values from Pylons controller be assigned to JavaScript variables with Mako? | I'm developing under Pylons using Mako templates. The problem is that I need to assign a string from some attribute of tmpl_context to a JavaScript variable in a page body. The additional problem is that this string can be quite arbitrary, ie can contain such characters like ", ', <, >, etc... Is there a common way to do such assignment?
I've tried something like:
<script>
...
var a = "${c.my_string}";
...
</script>
but I get quotation marks and HTML special characters escaped. But I would not like to disable filtering because of possible danger of executing of unexpected code.
| [
"You have some arbitrary data in c.my_string, and therefore do not want to use \"|n\", right?\nQuickiest way to escape it in JS-style escaping would be\nvar a = ${c.my_string.__repr__()|n}; # Note lack of \"\" around it! \n\nHowever I'm unsure about <> characters (with something like </script> inserted), maybe you ... | [
2,
1
] | [] | [] | [
"escaping",
"mako",
"pylons",
"python",
"templating"
] | stackoverflow_0003382328_escaping_mako_pylons_python_templating.txt |
Q:
Python regex help needed
I need to get info from a website that outputs it between <font color="red">needed-info-here</font> OR <span style="font-weight:bold;">needed-info-here</span>, randomly.
I can get it when I use
start = '<font color="red">'
end = '</font>'
expression = start + '(.*?)' + end
match = re.compile(expression).search(web_source_code)
needed_info = match.group(1)
, but then I have to pick to fetch either <font> or <span>, failing, when the site uses the other tag.
How do I modify the regular expression so it would always succeed?
A:
Don't parse HTML with regex.
Regex is not the right tool to use for this problem. Look up BeautifulSoup or lxml.
A:
You can join two alternatives with a vertical bar:
start = '<font color="red">|<span style="font-weight:bold;">'
end = '</font>|</span>'
since you know that a font tag will always be closed by </font>, a span tag always by </span>.
However, consider also using a solid HTML parser such as BeautifulSoup, rather than rolling your own regular expressions, to parse HTML, which is particularly unsuitable in general for getting parsed by regular expressions.
A:
Although regular expressions are not your best choice for parsing HTML.
For the sake of education, here is a possible answer to your question:
start = '<(?P<tag>font|tag) color="red">'
end = '</(?P=tag)>'
expression = start + '(.*?)' + end
A:
expression = '(<font color="red">(.*?)</font>|<span style="font-weight:bold;">(.*?)</span>)'
match = re.compile(expression).search(web_source_code)
needed_info = match.group(2)
This would get the job done but you shouldn't really be using regex to parse html
A:
Regex and HTML are not such a good match, HTML has too many potential variations that will trip up your regex. BeautifulSoup is the standard tool to employ here, but I find pyparsing can be just as effective, and sometimes even simpler to construct when trying to locate a particular tag relative to a particular previous tag.
Here is how to address your question using pyparsing:
html = """ need to get info from a website that outputs it between <font color="red">needed-info-here</font> OR <span style="font-weight:bold;">needed-info-here</span>, randomly.
<font color="white">but not this info</font> and
<span style="font-weight:normal;">dont want this either</span>
"""
from pyparsing import *
font,fontEnd = makeHTMLTags("FONT")
# only match <font> tags with color="red"
font.setParseAction(withAttribute(color="red"))
# only match <span> tags with given style
span,spanEnd = makeHTMLTags("SPAN")
span.setParseAction(withAttribute(style="font-weight:bold;"))
# define full match patterns, define "body" results name for easy access
fontpattern = font + SkipTo(fontEnd)("body") + fontEnd
spanpattern = span + SkipTo(spanEnd)("body") + spanEnd
# now create a single pattern, matching either of the other patterns
searchpattern = fontpattern | spanpattern
# call searchString, and extract body element from each match
for text in searchpattern.searchString(html):
print text.body
Prints:
needed-info-here
needed-info-here
A:
I haven't used Python, but if you make expressions equal to the following, it should work:
/(?P<open><(font|span)[^>]*>)(?P<info>[^<]+)(?P<close><\/(font|span)>)/gi
Then just access your needed info with the name "info".
PS - I also agree about the "not parsing HTML with regex" rule, but if you know that it will appear in either font or span tags, then so be it...
Also, why use the font tag? I haven't used a font tag since I learned CSS.
| Python regex help needed | I need to get info from a website that outputs it between <font color="red">needed-info-here</font> OR <span style="font-weight:bold;">needed-info-here</span>, randomly.
I can get it when I use
start = '<font color="red">'
end = '</font>'
expression = start + '(.*?)' + end
match = re.compile(expression).search(web_source_code)
needed_info = match.group(1)
, but then I have to pick to fetch either <font> or <span>, failing, when the site uses the other tag.
How do I modify the regular expression so it would always succeed?
| [
"Don't parse HTML with regex.\nRegex is not the right tool to use for this problem. Look up BeautifulSoup or lxml.\n",
"You can join two alternatives with a vertical bar:\nstart = '<font color=\"red\">|<span style=\"font-weight:bold;\">'\nend = '</font>|</span>'\n\nsince you know that a font tag will always be cl... | [
7,
3,
1,
1,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003382552_python_regex.txt |
Q:
Can this program damage my monitor?
I made a Python program that switches the entire monitor back and forth between random colours very quickly. I'm wondering if it can harm my monitor somehow.
Also on an unrelated note, it's tripy to stair at the program for extended periods of time.
The program
import Tkinter
import random
class AppTk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.state("zoomed")
self.wm_attributes("-topmost", 1)
self.attributes('-toolwindow', True)
self.configure(bg='black')
self.switch()
def switch(self):
#self.BW()
#self.BG()
#self.C()
self.TC()
self.after(10, self.switch)
def BW(self):
U = random.randint(1,2)
if U == 1:
self.configure(bg='black')
if U == 2:
self.configure(bg='white')
def BG(self):
U = random.randint(1,2)
if U == 1:
self.configure(bg='black')
if U == 2:
self.configure(bg='lightgreen')
def C(self):
U = random.randint(1,14)
if U == 1:
self.configure(bg='black')
if U == 2:
self.configure(bg='white')
if U == 3:
self.configure(bg='pink')
if U == 4:
self.configure(bg='darkred')
if U == 5:
self.configure(bg='red')
if U == 6:
self.configure(bg='orange')
if U == 7:
self.configure(bg='yellow')
if U == 8:
self.configure(bg='green')
if U == 9:
self.configure(bg='lightgreen')
if U == 10:
self.configure(bg='darkgreen')
if U == 11:
self.configure(bg='lightblue')
if U == 12:
self.configure(bg='blue')
if U == 13:
self.configure(bg='darkblue')
if U == 14:
self.configure(bg='steelblue1')
def TC(self):
R = random.randint(1,255)
G = random.randint(1,255)
B = random.randint(1,255)
T = (R,G,B)
Colour = '#%02x%02x%02x' % T
self.configure(bg=Colour)
if __name__ == "__main__":
app = AppTk(None)
app.mainloop()
A:
I wouldn't say it would damage your monitor since there are programs that do this in an attempt to fix dead pixels. I can't remember any off the top of my head since I haven't used one in 3 years.
So it shouldn't do much, but then again you wouldn't be running this for extended periods of time, would you?
A:
No worry, you're not working at low enough levels to damage any of your hardware (on any semi-sane operating system, at least -- but I don't know any that's crazy enough to let application SW working at such a reasonable abstraction level to damage a monitor;-).
A:
A long time ago it was possible to damage CRT screens by using to large refresh frequencies (so the coils got overheated).
However since many years this is impossible, because the CRT have built-in electronics to detect the frequencies and show "unsupported mode" then.
Changing the color fastly is really no problem: It was never (the vertical refresh rate is always the same, even if you do not update a pixel) and it not a problem on flat panels.
| Can this program damage my monitor? | I made a Python program that switches the entire monitor back and forth between random colours very quickly. I'm wondering if it can harm my monitor somehow.
Also on an unrelated note, it's tripy to stair at the program for extended periods of time.
The program
import Tkinter
import random
class AppTk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.state("zoomed")
self.wm_attributes("-topmost", 1)
self.attributes('-toolwindow', True)
self.configure(bg='black')
self.switch()
def switch(self):
#self.BW()
#self.BG()
#self.C()
self.TC()
self.after(10, self.switch)
def BW(self):
U = random.randint(1,2)
if U == 1:
self.configure(bg='black')
if U == 2:
self.configure(bg='white')
def BG(self):
U = random.randint(1,2)
if U == 1:
self.configure(bg='black')
if U == 2:
self.configure(bg='lightgreen')
def C(self):
U = random.randint(1,14)
if U == 1:
self.configure(bg='black')
if U == 2:
self.configure(bg='white')
if U == 3:
self.configure(bg='pink')
if U == 4:
self.configure(bg='darkred')
if U == 5:
self.configure(bg='red')
if U == 6:
self.configure(bg='orange')
if U == 7:
self.configure(bg='yellow')
if U == 8:
self.configure(bg='green')
if U == 9:
self.configure(bg='lightgreen')
if U == 10:
self.configure(bg='darkgreen')
if U == 11:
self.configure(bg='lightblue')
if U == 12:
self.configure(bg='blue')
if U == 13:
self.configure(bg='darkblue')
if U == 14:
self.configure(bg='steelblue1')
def TC(self):
R = random.randint(1,255)
G = random.randint(1,255)
B = random.randint(1,255)
T = (R,G,B)
Colour = '#%02x%02x%02x' % T
self.configure(bg=Colour)
if __name__ == "__main__":
app = AppTk(None)
app.mainloop()
| [
"I wouldn't say it would damage your monitor since there are programs that do this in an attempt to fix dead pixels. I can't remember any off the top of my head since I haven't used one in 3 years. \nSo it shouldn't do much, but then again you wouldn't be running this for extended periods of time, would you?\n",
... | [
1,
1,
1
] | [] | [] | [
"hardware",
"monitor",
"python"
] | stackoverflow_0003380797_hardware_monitor_python.txt |
Q:
Where to put my sqlalchemy code in my script?
I had my sqlalchemy related code in my main() method in my script.
But then when I created a function, I wasn't able to reference my 'products' mapper because it was in the main() method.
Should I be putting the sqlalchemy related code (session, mapper, and classes) in global scope so all functions in my single file script can refer to it?
I was told a script is usually layout out as:
globals
functions
classes
main
But if I put sqlalchemy at the top to make it global, I have to move my classes to the top also.
A:
Typical approach is to define all mappings in separate model module, with one file per class/table.
Then you just import needed classes whenever need them.
| Where to put my sqlalchemy code in my script? | I had my sqlalchemy related code in my main() method in my script.
But then when I created a function, I wasn't able to reference my 'products' mapper because it was in the main() method.
Should I be putting the sqlalchemy related code (session, mapper, and classes) in global scope so all functions in my single file script can refer to it?
I was told a script is usually layout out as:
globals
functions
classes
main
But if I put sqlalchemy at the top to make it global, I have to move my classes to the top also.
| [
"Typical approach is to define all mappings in separate model module, with one file per class/table.\nThen you just import needed classes whenever need them. \n"
] | [
2
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003382739_python_sqlalchemy.txt |
Q:
Downloading an image, want to save to folder, check if file exists
So I have a recordset (sqlalchemy) of products that I am looping, and I want to download an image and save it to a folder.
If the folder doesn't exist, I want to create it.
Also, I want to first check if the image file exists in the folder. If it does, don't download just skip that row.
/myscript.py
/images/
I want the images folder to be a folder in the same directory as my script file, wherever it may be stored.
I have so far:
q = session.query(products)
for p in q:
if p.url:
req = urllib2.Request(p.url)
try:
response = urllib2.urlopen(req)
image = response.read()
???
except URLError e:
print e
A:
I think you can just use urllib.urlretrieve here:
import errno
import os
import urllib
def require_dir(path):
try:
os.makedirs(path)
except OSError, exc:
if exc.errno != errno.EEXIST:
raise
directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")
require_dir(directory)
filename = os.path.join(directory, "stackoverflow.html")
if not os.path.exists(filename):
urllib.urlretrieve("http://stackoverflow.com", filename)
A:
The filename should be in response.info()['Content-Disposition'] (as a filename=something after a semicolon in that string) -- if not (that header is missing, has no semicolon, or has no filename part), you can use urlparse.urlsplit(p.url) and get the os.path.basename of the last non-blank component (or, more pragmatically but that would deeply offend purists, just p.url.split('/')[-1] ;-).
So much for the filename, call it e.g. fn.
The directory where your script lives is sd = os.path.dirname(__file__).
Its images subdirectory is therefore clearly sdsd = os.path.join(sd, 'images').
To check if that subdirectory exists, and make it otherwise,
if not os.path.exists(sdsd): os.makedir(sdsd)
To check if the file you want to write already exists,
if os.path.exists(os.path.join(sdsd, fn)): ...
All of this code goes where you have ???. It's a lot, so it's clearly better to make it a function taking p.url and response as arguments (it can read image on its own;-) and possibly taking __file__ as well if you want the freedom to move that function into its own separate module later (I'd recommend that!).
Of course, you need to import os for all those os and os.path calls, and also import urlparse if you decide to use the latter standard library module.
| Downloading an image, want to save to folder, check if file exists | So I have a recordset (sqlalchemy) of products that I am looping, and I want to download an image and save it to a folder.
If the folder doesn't exist, I want to create it.
Also, I want to first check if the image file exists in the folder. If it does, don't download just skip that row.
/myscript.py
/images/
I want the images folder to be a folder in the same directory as my script file, wherever it may be stored.
I have so far:
q = session.query(products)
for p in q:
if p.url:
req = urllib2.Request(p.url)
try:
response = urllib2.urlopen(req)
image = response.read()
???
except URLError e:
print e
| [
"I think you can just use urllib.urlretrieve here:\nimport errno\nimport os\nimport urllib\n\ndef require_dir(path):\n try:\n os.makedirs(path)\n except OSError, exc:\n if exc.errno != errno.EEXIST:\n raise\n\ndirectory = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"imag... | [
10,
1
] | [] | [] | [
"download",
"file_io",
"python"
] | stackoverflow_0003382812_download_file_io_python.txt |
Q:
Proper way to edit existing entity in tipfy
I'm using a PersonEditHandler class in tipfy to edit a Person entity. I have
the get() and post() methods formed, but when I reference self.person
(to check if the get method found the existing person by key), I get
an 'object has no attribute' error.
This is because I never initialize it in the init method since I'm inheriting from RequestHandler and Jinja2Mixin. However, when I override init, I get another error: 'TypeError: init() takes exactly 1 argument (3 given)'
Here is the code:
class PersonEditHandler(RequestHandler, Jinja2Mixin):
def __init__(self):
PersonEditHandler.__init__(self)
# ...or 'super(PersonEditHandler, self).__init__()'
self.person = None
Am I having trouble because of multiple inheritance? What is the best
way to edit a retrieved record in tipfy without creating a new one?
A:
I would recommend foregoing the __init__ and rather adding a class attribute:
class PersonEditHandler(RequestHandler, Jinja2Mixin):
person = None
This way, when you access a self.person that's never been set on a specific instance self, it will defer to the class and you'll get None as desired; when you set self.person, it will set it on the entity, as desired.
Multiple inheritance with mixins is OK, in general, but it can make for somewhat murky problems with __new__ and __init__, as you've noticed (honestly I have no idea what class is whining about receiving three arguments here... though it would help if you showed the full traceback, finessing the problem as I just suggested is simpler;-).
| Proper way to edit existing entity in tipfy | I'm using a PersonEditHandler class in tipfy to edit a Person entity. I have
the get() and post() methods formed, but when I reference self.person
(to check if the get method found the existing person by key), I get
an 'object has no attribute' error.
This is because I never initialize it in the init method since I'm inheriting from RequestHandler and Jinja2Mixin. However, when I override init, I get another error: 'TypeError: init() takes exactly 1 argument (3 given)'
Here is the code:
class PersonEditHandler(RequestHandler, Jinja2Mixin):
def __init__(self):
PersonEditHandler.__init__(self)
# ...or 'super(PersonEditHandler, self).__init__()'
self.person = None
Am I having trouble because of multiple inheritance? What is the best
way to edit a retrieved record in tipfy without creating a new one?
| [
"I would recommend foregoing the __init__ and rather adding a class attribute:\nclass PersonEditHandler(RequestHandler, Jinja2Mixin): \n person = None\n\nThis way, when you access a self.person that's never been set on a specific instance self, it will defer to the class and you'll get None as desired; when you ... | [
1
] | [] | [] | [
"google_app_engine",
"multiple_inheritance",
"python",
"tipfy",
"web_applications"
] | stackoverflow_0003379084_google_app_engine_multiple_inheritance_python_tipfy_web_applications.txt |
Q:
active object in python for s60
How do I use active object in python for s60?
can anybody give me a code example?
A:
There's a simple example here:
def run(self):
self.lock = e32.Ao_lock()
self.lock.wait()
# restore old title etc. and finish
def exit_callback(self):
# unlocks the application and lets it finish
self.lock.signal()
and that same URL also contains a detailed explanation (and more info, tutorial and otherwise, on Python for S60).
| active object in python for s60 | How do I use active object in python for s60?
can anybody give me a code example?
| [
"There's a simple example here:\ndef run(self):\n self.lock = e32.Ao_lock()\n self.lock.wait()\n # restore old title etc. and finish\n\ndef exit_callback(self):\n # unlocks the application and lets it finish\n self.lock.signal()\n\nand that same URL also contains a detailed explanation (and more info... | [
1
] | [] | [] | [
"active_objects",
"pys60",
"python"
] | stackoverflow_0003382957_active_objects_pys60_python.txt |
Q:
Greedy versus Non-Greedy matching in Python re
Please help me to discover whether this is a bug in Python (2.6.5), in my competence at writing regexes, or in my understanding of pattern matching.
(I accept that a possible answer is "Upgrade your Python".)
I'm trying to parse a Yubikey token, allowing for the optional extras.
When I use this regex to match a token without any optional extras (that is, containing only the stuff that matches the two capture groups), the match fails:
r'^\t?[^a-z0-9]?([cbdefghijklnrtuv1-8]{0,32})\t?([cbdefghijklnrtuv1-8]{32})\t?\r?\n?$'
However, if I make the first group non-greedy:
r'^\t?[^a-z0-9]?([cbdefghijklnrtuv1-8]{0,32}?)\t?([cbdefghijklnrtuv1-8]{32})\t?\r?\n?$'
it succeeds.
So, OK, it's working, but I would have thought that the only difference in end result between these two regexes would be performance.
Both Expresso and Regex Coach like both patterns.
What have I missed?
Here are two of the strings I'm testing with.
No optional extras (the ones that can fail):
"vvbrentlnccnhgfgrtetilbvckjcegblehfvbihrdcui"
With optional extras (haven't failed so far; actual tabs are shown here as "_"):
"_!_8R5Gkruvfgheufhcnhllchgrfiutujfh_"
"_!1U4Knivdgvkfthrd_brvejhudrdnbunellrjjkkccfnggbdng_"
I've tried to reproduce it using the suggestion from Alex Martelli, and it doesn't fail in the raw Python environment, so I'm going to revisit my code (I'm actually hacking on yubikey-python); I'll report back in a day or so.
My apologies to everyone. I cannot reproduce the problem. When it occurred, I was reading input via getpass; I suspect that an accidental foreign keystroke got in the way.
I am going to close the question. If whoever upvoted the question wishes to remove their vote, that is fair.
Very sorry.
A:
I'd recommend using yubikey-python for Python interfacing to yubikey -- but, that's a side (and strictly pragmatical) issue;-).
In theory, there should be no cases where a choice between greedy and non-greedy causes a RE to match in one case and fail in another -- it should only affects what gets matched (and as you mention performance), not whether the match succeeds at all, since REs are supposed to backtrack for the purpose.
Problem is, I cannot reproduce the problem -- I don't have a yubikey at hand and the tests in this file show no differences between the two REs' match/no-match behavior.
Could you please post a couple of failing examples (where one matches and the other one doesn't), ideally by editing your question, so I can reproduce the problem and try to cut it down to its minimum? Sounds like there may be a RE bug, but without reproducible cases I can't check if and when it's been fixed, already reported, or what. Thanks!
Edit the OP has now posted one failing example but I still can't reproduce:
$ py26
Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> r1 = re.compile(r'^\t?[^a-z0-9]?([cbdefghijklnrtuv1-8]{0,32})\t?([cbdefghijklnrtuv1-8]{32})\t?\r?\n?$')
>>> r2 = re.compile(r'^\t?[^a-z0-9]?([cbdefghijklnrtuv1-8]{0,32}?)\t?([cbdefghijklnrtuv1-8]{32})\t?\r?\n?$'
... )
>>> nox="vvbrentlnccnhgfgrtetilbvckjcegblehfvbihrdcui"
>>> r1.match(nox)
<_sre.SRE_Match object at 0xcc458>
>>> r2.match(nox)
<_sre.SRE_Match object at 0xcc920>
>>>
i.e., match succeeds in both cases, as it should -- and that's exactly the same 2.6.5 Python version as the OP is using. OP, pls, show the results of this simple sequence of commands on your platform and tell us exactly what the platform is, since it looks like a weird platform-dependent bug... thanks!
A:
You're right: simply switching from greedy to non-greedy quantifiers should not cause a regex to stop working. It can change how quickly the regex matches (or fails to match), how much it matches, and which parts get captured in which groups, that's all.
(The following "solution" is not applicable, but the question still doesn't indicate that a case-insensitive match is being performed, so I'll leave it.)
Your problem is that the strings with the optional extras also have uppercase letters in them, and your regex only allows for lowercase letters. Stick a (?i) on the front or the regex and it works just fine.
| Greedy versus Non-Greedy matching in Python re | Please help me to discover whether this is a bug in Python (2.6.5), in my competence at writing regexes, or in my understanding of pattern matching.
(I accept that a possible answer is "Upgrade your Python".)
I'm trying to parse a Yubikey token, allowing for the optional extras.
When I use this regex to match a token without any optional extras (that is, containing only the stuff that matches the two capture groups), the match fails:
r'^\t?[^a-z0-9]?([cbdefghijklnrtuv1-8]{0,32})\t?([cbdefghijklnrtuv1-8]{32})\t?\r?\n?$'
However, if I make the first group non-greedy:
r'^\t?[^a-z0-9]?([cbdefghijklnrtuv1-8]{0,32}?)\t?([cbdefghijklnrtuv1-8]{32})\t?\r?\n?$'
it succeeds.
So, OK, it's working, but I would have thought that the only difference in end result between these two regexes would be performance.
Both Expresso and Regex Coach like both patterns.
What have I missed?
Here are two of the strings I'm testing with.
No optional extras (the ones that can fail):
"vvbrentlnccnhgfgrtetilbvckjcegblehfvbihrdcui"
With optional extras (haven't failed so far; actual tabs are shown here as "_"):
"_!_8R5Gkruvfgheufhcnhllchgrfiutujfh_"
"_!1U4Knivdgvkfthrd_brvejhudrdnbunellrjjkkccfnggbdng_"
I've tried to reproduce it using the suggestion from Alex Martelli, and it doesn't fail in the raw Python environment, so I'm going to revisit my code (I'm actually hacking on yubikey-python); I'll report back in a day or so.
My apologies to everyone. I cannot reproduce the problem. When it occurred, I was reading input via getpass; I suspect that an accidental foreign keystroke got in the way.
I am going to close the question. If whoever upvoted the question wishes to remove their vote, that is fair.
Very sorry.
| [
"I'd recommend using yubikey-python for Python interfacing to yubikey -- but, that's a side (and strictly pragmatical) issue;-).\nIn theory, there should be no cases where a choice between greedy and non-greedy causes a RE to match in one case and fail in another -- it should only affects what gets matched (and as ... | [
3,
0
] | [] | [] | [
"greedy",
"non_greedy",
"python",
"regex"
] | stackoverflow_0003382690_greedy_non_greedy_python_regex.txt |
Q:
Mako Templates : How to find the name of the template which the current template is included by?
I have multiple templates that include each other, such as :
t1.html :
...
<%include file="t2.html" args="docTitle='blablabla'" />
...
t2.html:
<%page args="docTitle='Undefined'"/>
<title>${docTitle}</title>
...
And what I want to do is to determine that t2 is included by t1 (or another one, so I can use its name). No specific way described in the documentation caught my eye, and I could've passed yet another argument (such as pagename='foobar'), but it feels more like a hack.
Is there a way to accomplish this, using a simple .render(blabla) call to render the page ?
A:
As far as I can tell, mako does not provide any information about 'parent' template to included. Moreover, it takes some care to delete any bits of information on that from context passed to included file.
Therefore only solution I see is to use CPython stack, to find nearest mako template frame and extract needed information from it. However this may be both slow and unreliable, and I would advice going with explicit passing of the name. It also relies on undocumented mako features, which may change later.
Here's stack-based solution:
In the template:
${h.get_previous_template_name()} # h is pylons-style helpers module. Substitute it with cherrypy appropriate way.
In the helpers.py (or w/e is appropriate for cherrypy):
import inspect
def get_previous_template_name():
stack = inspect.stack()
for frame_tuple in stack[2:]:
frame = frame_tuple[0]
if '_template_uri' in frame.f_globals:
return frame.f_globals['_template_uri']
This will return full uri, however, like 't1.html'. Tweak it to fit your needs.
| Mako Templates : How to find the name of the template which the current template is included by? | I have multiple templates that include each other, such as :
t1.html :
...
<%include file="t2.html" args="docTitle='blablabla'" />
...
t2.html:
<%page args="docTitle='Undefined'"/>
<title>${docTitle}</title>
...
And what I want to do is to determine that t2 is included by t1 (or another one, so I can use its name). No specific way described in the documentation caught my eye, and I could've passed yet another argument (such as pagename='foobar'), but it feels more like a hack.
Is there a way to accomplish this, using a simple .render(blabla) call to render the page ?
| [
"As far as I can tell, mako does not provide any information about 'parent' template to included. Moreover, it takes some care to delete any bits of information on that from context passed to included file.\nTherefore only solution I see is to use CPython stack, to find nearest mako template frame and extract neede... | [
1
] | [] | [] | [
"cherrypy",
"mako",
"python"
] | stackoverflow_0003382885_cherrypy_mako_python.txt |
Q:
How do I use owfs to read an iButton temperature logger?
I've installed owfs and am trying to read the data off a iButton temperature logger.
owfs lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by catting the files, e.g. cat onewire/{deviceid}/log/temperature.1, but the onewire/{deviceid}/log/temperature.ALL file is "broken" (possible too large, as histogram/temperature.ALL work fine).
A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?
I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.
Update: Using owpython (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:
>>> import ow
>>> ow.init("u") # initialize USB
>>> ow.Sensor("/").sensorList()
[Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")]
>>> x = ow.Sensor("/21.C4B912000000")
>>> print x.type, x.temperature
DS1921 22
x.log gives an AttributeError.
A:
I've also had problems with owfs. I found it to be an overengineered solution to what is a simple problem. Now I'm using the DigiTemp code without a problem. I found it to be flexible and reliable. For instance, I store the room's temperature in a log file every minute by running
/usr/local/bin/digitemp_DS9097U -c /usr/local/etc/digitemp.conf \
-q -t0 -n0 -d60 -l/var/log/temperature
To reach that point I downloaded the source file, untarred it and then did the following.
# Compile the hardware-specific command
make ds9097u
# Initialize the configuration file
./digitemp_DS9097U -s/dev/ttyS0 -i
# Run command to obtain temperature, and verify your setup
./digitemp_DS9097U -a
# Copy the configuration file to an accessible place
cp .digitemprc /usr/local/etc/digitemp.conf
I also hand-edited my configuration file to adjust it to my setup. This is how it ended-up.
TTY /dev/ttyS0
READ_TIME 1000
LOG_TYPE 1
LOG_FORMAT "%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F"
CNT_FORMAT "%b %d %H:%M:%S Sensor %s #%n %C"
HUM_FORMAT "%b %d %H:%M:%S Sensor %s C: %.2C F: %.2F H: %h%%"
SENSORS 1
ROM 0 0x10 0xD3 0x5B 0x07 0x00 0x00 0x00 0x05
In my case I also created a /etc/init.d/digitemp file and enabled it to run at startup.
#! /bin/sh
#
# System startup script for the temperature monitoring daemon
#
### BEGIN INIT INFO
# Provides: digitemp
# Required-Start:
# Should-Start:
# Required-Stop:
# Should-Stop:
# Default-Start: 2 3 5
# Default-Stop: 0 1 6
# Description: Start the temperature monitoring daemon
### END INIT INFO
DIGITEMP=/usr/local/bin/digitemp_DS9097U
test -x $DIGITEMP || exit 5
DIGITEMP_CONFIG=/root/digitemp.conf
test -f $DIGITEMP_CONFIG || exit 6
DIGITEMP_LOGFILE=/var/log/temperature
# Source SuSE config
. /etc/rc.status
rc_reset
case "$1" in
start)
echo -n "Starting temperature monitoring daemon"
startproc $DIGITEMP -c $DIGITEMP_CONFIG -q -t0 -n0 -d60 -l$DIGITEMP_LOGFILE
rc_status -v
;;
stop)
echo -n "Shutting down temperature monitoring daemon"
killproc -TERM $DIGITEMP
rc_status -v
;;
try-restart)
$0 status >/dev/null && $0 restart
rc_status
;;
restart)
$0 stop
$0 start
rc_status
;;
force-reload)
$0 try-restart
rc_status
;;
reload)
$0 try-restart
rc_status
;;
status)
echo -n "Checking for temperature monitoring service"
checkproc $DIGITEMP
rc_status -v
;;
*)
echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload}"
exit 1
;;
esac
rc_exit
A:
I don't think there is a clever way. owpython doesn't support that telling from the API documentation. I guess /proc is your safest bet. Maybe have a look at the source of the owpython module and check if you can find out how it works.
A:
Well I have just started to look at ibuttons and want to use python.
This looks more promising:
http://www.ohloh.net/p/pyonewire
| How do I use owfs to read an iButton temperature logger? | I've installed owfs and am trying to read the data off a iButton temperature logger.
owfs lets me mount the iButton as a fuse filesystem and I can see all the data. I'm having trouble figuring out what is the best way to access the data though. I can get individual readings by catting the files, e.g. cat onewire/{deviceid}/log/temperature.1, but the onewire/{deviceid}/log/temperature.ALL file is "broken" (possible too large, as histogram/temperature.ALL work fine).
A python script to read all files seems to work but takes a very long time. Is there a better way to do it? Does anyone have any examples?
I'm using Ubuntu 8.04 and couldn't get the java "one wire viewer" app to run.
Update: Using owpython (installed with owfs), I can get the current temperature but can't figure out how to get access to the recorded logs:
>>> import ow
>>> ow.init("u") # initialize USB
>>> ow.Sensor("/").sensorList()
[Sensor("/81.7FD921000000"), Sensor("/21.C4B912000000")]
>>> x = ow.Sensor("/21.C4B912000000")
>>> print x.type, x.temperature
DS1921 22
x.log gives an AttributeError.
| [
"I've also had problems with owfs. I found it to be an overengineered solution to what is a simple problem. Now I'm using the DigiTemp code without a problem. I found it to be flexible and reliable. For instance, I store the room's temperature in a log file every minute by running\n/usr/local/bin/digitemp_DS909... | [
3,
2,
2
] | [] | [] | [
"1wire",
"python",
"ubuntu"
] | stackoverflow_0000113185_1wire_python_ubuntu.txt |
Q:
django models filter() and extra()
I have a problem with the extra() method of queryset.
So, i retrieve my objects with :
invoices = Invoice.objects.select_related().filter(quantity__gt=0,begin__gte=values['start_day'],end__lte=values['end_day'])
So it works, I have my invoices.
After i use another time filter() :
invoices = invoices.filter(max__gte=duration)
It works too.
But, after, i need to use extra() because of my request, so i have that :
cond = 'discount="YES" AND priceeuro*(%d%%fixe)<=%d'
invoices = invoices.extra(where=[cond],params=[duration,price])
Well, it works but my invoices variable contains more elements that before.
It's like the two filter() weren't used.
If you know why,
thanks.
EDIT:
This is the SQL associated with the query:
WHERE
("invoice"."product_id" IN (
SELECT U0."id"
FROM "product" U0
WHERE U0."accommodation_id" IN (
SELECT U0."id"
FROM "accommodation" U0
WHERE U0."resort_id" IN (
SELECT U0."id"
FROM "resort" U0
WHERE U0."area_id" IN (
SELECT U0."id"
FROM "area" U0
WHERE U0."country_id" = 9
))))
AND "invoice"."quantity" > 0
AND "invoice"."end" <= 2010-12-31
AND "invoice"."begin" >= 2010-12-01
AND fixe % 7 = 0
AND (discount="YES" AND pricediscountincludedeuro*(7% fixe)<=250)OR(discount="NO" AND priceeuro*(7% fixe)<=250))
A:
Dump the SQL from the query set object:
print invoices.query
If the cause of your bug is not obvious from looking at the generated SQL, update your question and post the SQL for us to see.
EDIT 1 based on seeing the SQL
I'm questioning the very last line in your SQL (re-formatted):
...
AND (discount="YES" AND pricediscountincludedeuro*(7% fixe)<=250)
OR (discount="NO" AND priceeuro*(7% fixe)<=250)
)
It seems to me like you want those two 'discount' checks wrapped in another set of parentheses to form their own logical check:
...
AND (
(discount="YES" AND pricediscountincludedeuro*(7% fixe)<=250)
OR
(discount="NO" AND priceeuro*(7% fixe)<=250)
)
)
Without that explicit grouping, the OR is going to be compared independently of the other 'discount' check and that will cause it to include things that you've already excluded in the above predicates.
| django models filter() and extra() | I have a problem with the extra() method of queryset.
So, i retrieve my objects with :
invoices = Invoice.objects.select_related().filter(quantity__gt=0,begin__gte=values['start_day'],end__lte=values['end_day'])
So it works, I have my invoices.
After i use another time filter() :
invoices = invoices.filter(max__gte=duration)
It works too.
But, after, i need to use extra() because of my request, so i have that :
cond = 'discount="YES" AND priceeuro*(%d%%fixe)<=%d'
invoices = invoices.extra(where=[cond],params=[duration,price])
Well, it works but my invoices variable contains more elements that before.
It's like the two filter() weren't used.
If you know why,
thanks.
EDIT:
This is the SQL associated with the query:
WHERE
("invoice"."product_id" IN (
SELECT U0."id"
FROM "product" U0
WHERE U0."accommodation_id" IN (
SELECT U0."id"
FROM "accommodation" U0
WHERE U0."resort_id" IN (
SELECT U0."id"
FROM "resort" U0
WHERE U0."area_id" IN (
SELECT U0."id"
FROM "area" U0
WHERE U0."country_id" = 9
))))
AND "invoice"."quantity" > 0
AND "invoice"."end" <= 2010-12-31
AND "invoice"."begin" >= 2010-12-01
AND fixe % 7 = 0
AND (discount="YES" AND pricediscountincludedeuro*(7% fixe)<=250)OR(discount="NO" AND priceeuro*(7% fixe)<=250))
| [
"Dump the SQL from the query set object:\nprint invoices.query\n\nIf the cause of your bug is not obvious from looking at the generated SQL, update your question and post the SQL for us to see.\nEDIT 1 based on seeing the SQL\nI'm questioning the very last line in your SQL (re-formatted):\n...\n AND (discount=\"YES... | [
1
] | [] | [] | [
"django",
"orm",
"python"
] | stackoverflow_0003383197_django_orm_python.txt |
Q:
Combining static HTML, a Django backend and a PHP forum on one server?
I have a project coming up for client who is basically happy with how he manages his website. It's lots of HTML files (around 300 of them) that he insists on keeping flat HTML files so can easily edit and manage them using Dreamweaver. His site has a lot of traffic and so I'm looking into options of keeping things simple for him. He does insist on this method for the time being, I hope to win him around eventually. I'm slowly moving him off his expensive shared hosting package (he maxes it out constantly due to traffic) and getting him on a VPS so I have more control over what I can install and the resources are more flexible etc.
My issue is, there is some parts of the site that are in PHP. The small admin area he uses to do his newsletters for example sits separately away and he still requires this function. I'm thinking that since I'd have him on a server I can install what I like on, I want to start incorporating Django into the site. I'd much more prefer to do Django development for any admin type situation then trying to hack or make something with PHP. I know about the PHP frameworks out there, but they just don't appeal in this particular situation.
Due to this massive set of HTML files, is it possible to basically allow Django to carry on serving these up as they are... He can edit and upload them with Dreamweaver as he always has... But Django is 'there' for the admin side of it which he can do his newsletter? Eventually he is wanting translations for the pages and login for visitors (again which I'd like to do with Django) but for the time being I'm in this transitional period and wanting to do things step by step.
Aside note, he has a forum that is in PHP, which he also wants to keep... So I'm thinking a carefully setup combination of Nginx, FastCGI and Gunicorn so static, PHP and Django respectively can co-exist on the same server. Is this just foolish, or totally possible?
Any thoughts, guidance, tips or experience would be greatly appreciated so I take the best step forward.
A:
I see no problem with such setup, using lightweight frontend is recommended for django (or any other wsgi app) anyway. Although you should serve static html with nginx itself, not django.
A:
I recommend using Cherokee for ease of administration. (It's very fast too) It makes complex configuration very easy, it's all done by via a really nice web interface.
| Combining static HTML, a Django backend and a PHP forum on one server? | I have a project coming up for client who is basically happy with how he manages his website. It's lots of HTML files (around 300 of them) that he insists on keeping flat HTML files so can easily edit and manage them using Dreamweaver. His site has a lot of traffic and so I'm looking into options of keeping things simple for him. He does insist on this method for the time being, I hope to win him around eventually. I'm slowly moving him off his expensive shared hosting package (he maxes it out constantly due to traffic) and getting him on a VPS so I have more control over what I can install and the resources are more flexible etc.
My issue is, there is some parts of the site that are in PHP. The small admin area he uses to do his newsletters for example sits separately away and he still requires this function. I'm thinking that since I'd have him on a server I can install what I like on, I want to start incorporating Django into the site. I'd much more prefer to do Django development for any admin type situation then trying to hack or make something with PHP. I know about the PHP frameworks out there, but they just don't appeal in this particular situation.
Due to this massive set of HTML files, is it possible to basically allow Django to carry on serving these up as they are... He can edit and upload them with Dreamweaver as he always has... But Django is 'there' for the admin side of it which he can do his newsletter? Eventually he is wanting translations for the pages and login for visitors (again which I'd like to do with Django) but for the time being I'm in this transitional period and wanting to do things step by step.
Aside note, he has a forum that is in PHP, which he also wants to keep... So I'm thinking a carefully setup combination of Nginx, FastCGI and Gunicorn so static, PHP and Django respectively can co-exist on the same server. Is this just foolish, or totally possible?
Any thoughts, guidance, tips or experience would be greatly appreciated so I take the best step forward.
| [
"I see no problem with such setup, using lightweight frontend is recommended for django (or any other wsgi app) anyway. Although you should serve static html with nginx itself, not django.\n",
"I recommend using Cherokee for ease of administration. (It's very fast too) It makes complex configuration very easy, it... | [
2,
2
] | [] | [] | [
"django",
"html",
"php",
"python"
] | stackoverflow_0003382390_django_html_php_python.txt |
Q:
Python error - psycopg2: no appropriate 64-bit architecture?
I'm running Mac OSX. Until today I had Python 2.6 with psycopg2 running just fine, I was using it with Django and Pylons. I've just reintalled postgres (I don't know if this is connected) and suddenly I can't import psycopg2 into Python without a strange error:
>>> import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/psycopg2/__init__.py", line 69, in <module>
File "build/bdist.macosx-10.6-universal/egg/psycopg2/_psycopg.py", line 7, in <module>
File "build/bdist.macosx-10.6-universal/egg/psycopg2/_psycopg.py", line 6, in __bootstrap__
ImportError: /usr/lib/libpq.5.dylib: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode)
Trying with Python 2.5 gives a similar error:
>>> import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/lib/python2.5/site-packages/psycopg2/__init__.py", line 69, in <module>
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: dlopen(/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: /opt/local/lib/postgresql84/libpq.5.dylib
Referenced from: /opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/psycopg2/_psycopg.so
Reason: no suitable image found. Did find:
/usr/lib/libpq.5.dylib: no matching architecture in universal wrapper
I have no idea what this means, where it's come from, or what to do about it. Please can anyone help?
A:
Have you just upgraded to Snow Leopard by any chance? The Leopard version of Python is 32-bit, while the 64-bit is in Snow Leopard. It breaks some libraries that use native code that aren't available in 64-bit mode.
| Python error - psycopg2: no appropriate 64-bit architecture? | I'm running Mac OSX. Until today I had Python 2.6 with psycopg2 running just fine, I was using it with Django and Pylons. I've just reintalled postgres (I don't know if this is connected) and suddenly I can't import psycopg2 into Python without a strange error:
>>> import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.macosx-10.6-universal/egg/psycopg2/__init__.py", line 69, in <module>
File "build/bdist.macosx-10.6-universal/egg/psycopg2/_psycopg.py", line 7, in <module>
File "build/bdist.macosx-10.6-universal/egg/psycopg2/_psycopg.py", line 6, in __bootstrap__
ImportError: /usr/lib/libpq.5.dylib: no appropriate 64-bit architecture (see "man python" for running in 32-bit mode)
Trying with Python 2.5 gives a similar error:
>>> import psycopg2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/lib/python2.5/site-packages/psycopg2/__init__.py", line 69, in <module>
from _psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
ImportError: dlopen(/opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/psycopg2/_psycopg.so, 2): Library not loaded: /opt/local/lib/postgresql84/libpq.5.dylib
Referenced from: /opt/local/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/psycopg2/_psycopg.so
Reason: no suitable image found. Did find:
/usr/lib/libpq.5.dylib: no matching architecture in universal wrapper
I have no idea what this means, where it's come from, or what to do about it. Please can anyone help?
| [
"Have you just upgraded to Snow Leopard by any chance? The Leopard version of Python is 32-bit, while the 64-bit is in Snow Leopard. It breaks some libraries that use native code that aren't available in 64-bit mode.\n"
] | [
0
] | [] | [] | [
"postgresql",
"psycopg2",
"python"
] | stackoverflow_0003383263_postgresql_psycopg2_python.txt |
Q:
Pythonic way to intercept calls to a function?
For testing things that query the environment (e.g., os.getenv, sys.version, etc.), it's often more convenient to make the queries lie than to actually fake up the environment. Here's a context manager that does this for one os.getenv call at a time:
from __future__ import with_statement
from contextlib import contextmanager
import os
@contextmanager
def fake_env(**fakes):
'''fakes is a dict mapping variables to their values. In the
fake_env context, os.getenv calls try to return out of the fakes
dict whenever possible before querying the actual environment.
'''
global os
original = os.getenv
def dummy(var):
try: return fakes[var]
except KeyError: return original(var)
os.getenv = dummy
yield
os.getenv = original
if __name__ == '__main__':
print os.getenv('HOME')
with fake_env(HOME='here'):
print os.getenv('HOME')
print os.getenv('HOME')
But this only works for os.getenv and the syntax gets a bit clunky if I allow for functions with multiple arguments. I guess between ast and code/exec/eval I could extend it to take the function to override as a parameter, but not cleanly. Also, I would then be on my way to Greenspun's Tenth. Is there a better way?
A:
You could easily just pass os.getenv itself as the first argument, then analyze it in the context manager much more simply than ast, code, etc etc:
>>> os.getenv.__name__
'getenv'
>>> os.getenv.__module__
'os'
After that, for reasonably general purpose use, you could have the result object to be returned, or a mapping from arguments (probably tuples thereof) to results. The faker context manager could also optionally accept a callable to be used for faking.
For example, with maximum simplicity:
import sys
def faker(original, fakefun):
original = os.getenv
themod = sys.modules[original.__module__]
thename = original.__name__
def dummy(*a, **k):
try: return fakefun(*a, **k)
except BaseException: return original(*a, **k)
setattr(themod, thename, dummy)
yield
setattr(themod, thename, original)
Your specific example could become:
with faker(os.getenv, dict(HOME='here').__getitem__):
...
Of course, a little more complexity may be warranted if e.g. you want to propagate certain exceptions rather than punting to the original function, or shortcut some common cases where providing a fakefun callable is clunky, and so on. But there's no reason such a general faker need be much more complex than your specific one.
A:
Why not write your own (fake) sys, os, &c. modules?
import fakeSys as sys
| Pythonic way to intercept calls to a function? | For testing things that query the environment (e.g., os.getenv, sys.version, etc.), it's often more convenient to make the queries lie than to actually fake up the environment. Here's a context manager that does this for one os.getenv call at a time:
from __future__ import with_statement
from contextlib import contextmanager
import os
@contextmanager
def fake_env(**fakes):
'''fakes is a dict mapping variables to their values. In the
fake_env context, os.getenv calls try to return out of the fakes
dict whenever possible before querying the actual environment.
'''
global os
original = os.getenv
def dummy(var):
try: return fakes[var]
except KeyError: return original(var)
os.getenv = dummy
yield
os.getenv = original
if __name__ == '__main__':
print os.getenv('HOME')
with fake_env(HOME='here'):
print os.getenv('HOME')
print os.getenv('HOME')
But this only works for os.getenv and the syntax gets a bit clunky if I allow for functions with multiple arguments. I guess between ast and code/exec/eval I could extend it to take the function to override as a parameter, but not cleanly. Also, I would then be on my way to Greenspun's Tenth. Is there a better way?
| [
"You could easily just pass os.getenv itself as the first argument, then analyze it in the context manager much more simply than ast, code, etc etc:\n>>> os.getenv.__name__\n'getenv'\n>>> os.getenv.__module__\n'os'\n\nAfter that, for reasonably general purpose use, you could have the result object to be returned, o... | [
4,
1
] | [] | [] | [
"macros",
"python",
"scope",
"testing"
] | stackoverflow_0003383219_macros_python_scope_testing.txt |
Q:
How can one find Class of calling function in python?
I am trying to determine the owning class of a calling function in python. For example, I have two classes, ClassA and ClassB. I want to know when classb_instance.call_class_a_method() is the caller of class_a.class_a_method() such that:
class ClassA(object):
def class_a_method(self):
# Some unknown process would occur here to
# define caller.
if caller.__class__ == ClassB:
print 'ClassB is calling.'
else:
print 'ClassB is not calling.'
class ClassB(object):
def __init__(self):
self.class_a_instance = ClassA()
def call_class_a_method(self):
self.class_a_instance.class_a_method()
classa_instance = ClassA()
classa_instance.class_a_method()
classb_instance = ClassB()
classb_instance.call_class_a_method()
the output would be:
'ClassB is not calling.'
'ClassB is calling.'
It seems as though inspect should be able to do this, but I cant puzzle out how.
A:
Well, if you want to traverse call stack and find which class (if any) did call it, its trivial:
def class_a_method(self):
stack = inspect.stack()
frame = stack[1][0]
caller = frame.f_locals.get('self', None)
If you want to check whether caller is of type ClassB, you should use isinstance(caller, ClassB) rather than comparsion on __class__. However this is generally un-pythonic, since python is duck-typed.
As others stated, most likely your app needs redesign to avoid using inspect.stack. Its CPython implementation feature, and is not guaranteed to be present in other Python implementations. Besides, its just Wrong Thing To Do.
A:
A function does not "have" a class -- one or more classes may (but need not) refer to a given function object, e.g.:
def f(self): return g()
class One(object): bah = f
class Two(object): blup = f
def g(): ...
One.bah and Two.blup are both set as references to the same function object f (and turn into unbound or bound method objects when accessed on the classes or their instances, but that leaves no trace in the stack). So, the stack upon
One().f()
vs
Two().f()
as seen from the g() that's called in either case, is pretty hard indeed to distinguish -- as would be that resulting from, e.g.,
f('blah bloh blup')
with no "classes" involved at all (though the type of the string being used as f's self argument would be;-).
I recommend not relying on introspection -- especially the wild and wooly kind, with lots of heuristics, that would be needed to get any semi-useful info here -- for any production code requirements: rearchitect to avoid that need.
For purely debugging purposes, in this case, you could walk the stack until you find a calling function with a first argument named self and introspect the type of the value bound to that argument name -- but as I mentioned that's entirely heuristical, since nothing forces your callers to name their first argument self if and only if their functions are meant to be methods in some class.
Such heuristic introspection would produce type objects One, Two, and str, in the three examples of code I just gave -- as you see, definitely not good for much else than debugging;-).
If you clarify better exactly what you're trying to accomplish through this attempted introspection, we might of course be able to help you better.
A:
class ClassA( object ):
def class_a_method( self ):
if any( "call_class_a_method" in tup for tup in inspect.stack( ) ):
print( 'ClassB is calling.' )
else:
print( 'ClassB is not calling.' )
# ClassB is not calling.
# ClassB is calling.
Why do you actually need this? It's a nasty hack because it's not something you should have to do.
A:
Usually the caller knows and should use the proper parameters, not to do magic in called class.
Do you need maybe factory class/function which record the Class or to write decorator for that?
| How can one find Class of calling function in python? | I am trying to determine the owning class of a calling function in python. For example, I have two classes, ClassA and ClassB. I want to know when classb_instance.call_class_a_method() is the caller of class_a.class_a_method() such that:
class ClassA(object):
def class_a_method(self):
# Some unknown process would occur here to
# define caller.
if caller.__class__ == ClassB:
print 'ClassB is calling.'
else:
print 'ClassB is not calling.'
class ClassB(object):
def __init__(self):
self.class_a_instance = ClassA()
def call_class_a_method(self):
self.class_a_instance.class_a_method()
classa_instance = ClassA()
classa_instance.class_a_method()
classb_instance = ClassB()
classb_instance.call_class_a_method()
the output would be:
'ClassB is not calling.'
'ClassB is calling.'
It seems as though inspect should be able to do this, but I cant puzzle out how.
| [
"Well, if you want to traverse call stack and find which class (if any) did call it, its trivial:\ndef class_a_method(self):\n stack = inspect.stack()\n frame = stack[1][0]\n caller = frame.f_locals.get('self', None)\n\nIf you want to check whether caller is of type ClassB, you should use isinstance(caller... | [
7,
4,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003383417_python.txt |
Q:
Alternative ways to instantiate a class in Python
I am currently writing my python classes and instantiate them like this
class calculations_class():
def calculate(self):
return True
Calculations = calculations_class()
I was wondering if I was doing this correctly, or if there were any other ways to instantiate them. Thanks!
A:
Apart from the naming convention issue which other answers have correctly pointed out, you're basically fine: calling a class is indeed by far the most common way of instantiating that class. If you need any per-instance initialization (most typically setting some instance-attributes to initial values), be sure to define an __init__ method that performs it:
class Calculations(object):
def __init__(self):
self.running_total = 0 # or w/ever
def calculate(self):
...
calc = Calculations()
The other, rare ways of instantiating a class typically occur when you want to bypass the initialization part for some reason (e.g., in the course of de-serializing an instance from some file, database, or communication from other processes -- the pickle module is a good example of needing such advanced approaches). I don't think you should worry about them at all at this stage of your Python learning experience.
A:
Well, class names tend to be capitalized (and camelcase) and instance names tend to be lowercase, but further that's the way to go.
class CalculationsClass():
def calculate(self):
return True
my_calc_instance = CalculationsClass()
A:
That is correct.
A:
This is the right way. Only thing you should do differently: class names should start with an uppercase letter, and variables with a lowercase one.
| Alternative ways to instantiate a class in Python | I am currently writing my python classes and instantiate them like this
class calculations_class():
def calculate(self):
return True
Calculations = calculations_class()
I was wondering if I was doing this correctly, or if there were any other ways to instantiate them. Thanks!
| [
"Apart from the naming convention issue which other answers have correctly pointed out, you're basically fine: calling a class is indeed by far the most common way of instantiating that class. If you need any per-instance initialization (most typically setting some instance-attributes to initial values), be sure t... | [
7,
4,
1,
0
] | [
"I tend to use the following format:\nclass CCalculations(): #Classes always begin with \"C\"\n def __init__(self):\n self.foo = 0\n self.fooBar = 0 #Variables use camelCase\n\n def DoCalculations(self): #Methods use uppercase\n return true\n\n def getFoo(self): \n ... | [
-2
] | [
"python"
] | stackoverflow_0003383383_python.txt |
Q:
How to get first top five objects with django.views.generic.date_based.archive_index?
I'm trying to display the latest 5 posts using a generic view like this:
urlpatterns = patterns('',
(r'^$', 'django.views.generic.date_based.archive_index',
{
'queryset': Post.objects.all()[:5],
'date_field': 'created_on',
'template_name': 'index.html'}
})
However I am getting
AssertionError at /
Cannot filter a query once a slice has
been taken.
What can I do?
A:
num_latest: The number of latest objects to send to the template context. By default, it's 15.
| How to get first top five objects with django.views.generic.date_based.archive_index? | I'm trying to display the latest 5 posts using a generic view like this:
urlpatterns = patterns('',
(r'^$', 'django.views.generic.date_based.archive_index',
{
'queryset': Post.objects.all()[:5],
'date_field': 'created_on',
'template_name': 'index.html'}
})
However I am getting
AssertionError at /
Cannot filter a query once a slice has
been taken.
What can I do?
| [
"num_latest: The number of latest objects to send to the template context. By default, it's 15.\n"
] | [
2
] | [] | [] | [
"django",
"django_generic_views",
"django_queryset",
"python"
] | stackoverflow_0003383693_django_django_generic_views_django_queryset_python.txt |
Q:
Do I reference the session when making any db calls in sqlalchemy?
In this tutorial it says (http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html) to select all rows of an entity like:
s = products.select()
rs = s.execute()
I get an error saying:
This select object is not bound and does not support direct execution ...
Do I need to reference the session object?
I just want to get all rows in my products table (i've already mapped everything, and I already inserted thousands of rows so that part works)
A:
Since that tutorial is built for SQLALchemy 0.2, it is likely that you aren't using that old of a version. In the latest documentation using the connection and passing the select statement to it is the preferred method. Try this instead:
query = users.select()
result = conn.execute(query)
Ref: http://www.sqlalchemy.org/docs/05/sqlexpression.html#selecting
| Do I reference the session when making any db calls in sqlalchemy? | In this tutorial it says (http://www.rmunn.com/sqlalchemy-tutorial/tutorial.html) to select all rows of an entity like:
s = products.select()
rs = s.execute()
I get an error saying:
This select object is not bound and does not support direct execution ...
Do I need to reference the session object?
I just want to get all rows in my products table (i've already mapped everything, and I already inserted thousands of rows so that part works)
| [
"Since that tutorial is built for SQLALchemy 0.2, it is likely that you aren't using that old of a version. In the latest documentation using the connection and passing the select statement to it is the preferred method. Try this instead:\nquery = users.select()\nresult = conn.execute(query)\n\nRef: http://www.sqla... | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003382751_python_sqlalchemy.txt |
Q:
Pythonic way to assign an instance of a subclass to a variable when a specific string is presented to the constructor of the parent class
I want to be able to create an instance of a parent class X, with a string "Q" as an extra argument.
This string is to be a name being an identifier for a subclass Q of the parent class X.
I want the instance of the parent class to become (or be replaced with) an instance of the subclass.
I am aware that this is probably a classic problem (error?). After some searching I haven't found a suitable solution though.
I came up with the following solution myself;
I added a dictionary of possible identifiers as keys for their baseclass-instances to the init-method of the parent class.
Then assigned the class-attribute of the corresponding subclass to the current instances class-attribute.
I required the argument of the init-method not to be the default value to prevent infinite looping.
Following is an example of what the code looks like in practice;
class SpecialRule:
""""""
name="Special Rule"
description="This is a Special Rule."
def __init__(self, name=None):
""""""
print "SpecialInit"
if name!=None:
SPECIAL_RULES={
"Fly" : FlyRule(),
"Skirmish" : SkirmishRule()
} #dictionary coupling names to SpecialRuleclasses
self.__class__= SPECIAL_RULES[name].__class__
def __str__(self):
""""""
return self.name
class FlyRule(SpecialRule):
""""""
name="Fly"
description="Flies."
def __init__(self):
""""""
print "FlyInit"+self.name
SpecialRule.__init__(self)
def addtocontainer(self, container):
"""this instance messes with the attributes of its containing class when added to some sort of list"""
class SkirmishRule(SpecialRule):
""""""
name="Skirmish"
description="Skirmishes."
def __init__(self):
""""""
SpecialRule.__init__(self)
def addtocontainer(self, container):
"""this instance messes with the attributes of its containing class when added to some sort of list"""
test=SpecialRule("Fly")
print "evaluating resulting class"
print test.description
print test.__class__
</pre></code>
output:
>
SpecialInit
FlyInitFly
SpecialInit
evaluating resulting class
Flies.
main.FlyRule
>
Is there a more pythonic solution and are there foresee-able problems with mine?
(And am I mistaken that its a good programming practice to explicitly call the .__init__(self) of the parent class in .__init__ of the subclass?).
My solution feels a bit ... wrong ...
Quick recap so far;
Thanks for the quick answers
@ Mark Tolonen's solution
I've been looking into the __new__-method, but when I try to make A, B and C in Mark Tolonen's example subclasses of Z, I get the error that class Z isn't defined yet. Also I'm not sure if instantiating class A the normal way ( with variable=A() outside of Z's scope ) is possible, unless you already have an instance of a subclass made and call the class as an attribute of an instance of a subclass of Z ... which doesn't seem very straightforward. __new__ is quite interesting so I'll fool around with it a bit more, your example is easier to grasp than what I got from the pythondocs.
@ Greg Hewgill's solution
I tried the staticmethod-solution and it seems to work fine. I looked into using a seperate function as a factory before but I guessed it would get hard to manage a large program with a list of loose strands of constructor code in the main block, so I'm very happy to integrate it in the class.
I did experiment a bit seeing if I could turn the create-method into a decorated .__call__() but it got quite messy so I'll leave it at that.
A:
I would solve this by using a function that encapsulates the choice of object:
class SpecialRule:
""""""
name="Special Rule"
description="This is a Special Rule."
@staticmethod
def create(name=None):
""""""
print "SpecialCreate"
if name!=None:
SPECIAL_RULES={
"Fly" : FlyRule,
"Skirmish" : SkirmishRule
} #dictionary coupling names to SpecialRuleclasses
return SPECIAL_RULES[name]()
else:
return SpecialRule()
I have used the @staticmethod decorator to allow you to call the create() method without already having an instance of the object. You would call this like:
SpecialRule.create("Fly")
A:
Look up the __new__ method. It is the correct way to override how a class is created vs. initialized.
Here's a quick hack:
class Z(object):
class A(object):
def name(self):
return "I'm A!"
class B(object):
def name(self):
return "I'm B!"
class C(object):
def name(self):
return "I'm C!"
D = {'A':A,'B':B,'C':C}
def __new__(cls,t):
return cls.D[t]()
| Pythonic way to assign an instance of a subclass to a variable when a specific string is presented to the constructor of the parent class | I want to be able to create an instance of a parent class X, with a string "Q" as an extra argument.
This string is to be a name being an identifier for a subclass Q of the parent class X.
I want the instance of the parent class to become (or be replaced with) an instance of the subclass.
I am aware that this is probably a classic problem (error?). After some searching I haven't found a suitable solution though.
I came up with the following solution myself;
I added a dictionary of possible identifiers as keys for their baseclass-instances to the init-method of the parent class.
Then assigned the class-attribute of the corresponding subclass to the current instances class-attribute.
I required the argument of the init-method not to be the default value to prevent infinite looping.
Following is an example of what the code looks like in practice;
class SpecialRule:
""""""
name="Special Rule"
description="This is a Special Rule."
def __init__(self, name=None):
""""""
print "SpecialInit"
if name!=None:
SPECIAL_RULES={
"Fly" : FlyRule(),
"Skirmish" : SkirmishRule()
} #dictionary coupling names to SpecialRuleclasses
self.__class__= SPECIAL_RULES[name].__class__
def __str__(self):
""""""
return self.name
class FlyRule(SpecialRule):
""""""
name="Fly"
description="Flies."
def __init__(self):
""""""
print "FlyInit"+self.name
SpecialRule.__init__(self)
def addtocontainer(self, container):
"""this instance messes with the attributes of its containing class when added to some sort of list"""
class SkirmishRule(SpecialRule):
""""""
name="Skirmish"
description="Skirmishes."
def __init__(self):
""""""
SpecialRule.__init__(self)
def addtocontainer(self, container):
"""this instance messes with the attributes of its containing class when added to some sort of list"""
test=SpecialRule("Fly")
print "evaluating resulting class"
print test.description
print test.__class__
</pre></code>
output:
>
SpecialInit
FlyInitFly
SpecialInit
evaluating resulting class
Flies.
main.FlyRule
>
Is there a more pythonic solution and are there foresee-able problems with mine?
(And am I mistaken that its a good programming practice to explicitly call the .__init__(self) of the parent class in .__init__ of the subclass?).
My solution feels a bit ... wrong ...
Quick recap so far;
Thanks for the quick answers
@ Mark Tolonen's solution
I've been looking into the __new__-method, but when I try to make A, B and C in Mark Tolonen's example subclasses of Z, I get the error that class Z isn't defined yet. Also I'm not sure if instantiating class A the normal way ( with variable=A() outside of Z's scope ) is possible, unless you already have an instance of a subclass made and call the class as an attribute of an instance of a subclass of Z ... which doesn't seem very straightforward. __new__ is quite interesting so I'll fool around with it a bit more, your example is easier to grasp than what I got from the pythondocs.
@ Greg Hewgill's solution
I tried the staticmethod-solution and it seems to work fine. I looked into using a seperate function as a factory before but I guessed it would get hard to manage a large program with a list of loose strands of constructor code in the main block, so I'm very happy to integrate it in the class.
I did experiment a bit seeing if I could turn the create-method into a decorated .__call__() but it got quite messy so I'll leave it at that.
| [
"I would solve this by using a function that encapsulates the choice of object:\nclass SpecialRule:\n \"\"\"\"\"\"\n name=\"Special Rule\"\n description=\"This is a Special Rule.\"\n @staticmethod\n def create(name=None):\n \"\"\"\"\"\"\n print \"SpecialCreate\"\n if name!=None:\... | [
3,
3
] | [] | [] | [
"python",
"subclass",
"variable_assignment"
] | stackoverflow_0003383733_python_subclass_variable_assignment.txt |
Q:
How to extend distutils with a simple pre uninstall script?
I found Question#1321270 for post install. My main target for the moment is bdist_wininst, but i did not find anything related to uninstall...
For clarification:
I want to register a com server after installation and de-register it before uninstall.
Extended answer:
ars' answer seems correct, however, for the completeness of things (I think the docs leave some room for improvements on this topic...):
I have NOT as was suggested by mention of Question#1321270 extended distutils.command.install, but written a new python sript called scripts/install.py and set the following in setup.py:
setup(
...
scripts=['scripts\install.py'],
options = {
...
"bdist_wininst" : {
"install_script" : "install.py",
...
},
}
)
The install.py is definitively being called on install. It seems, though that it is (despite to what the docs say) not being called on uninstall...
A:
The same post-install script will run at uninstall with different arguments. See the docs for more info:
This script will be run at installation time on the target system after all the files have been copied, with argv1 set to -install, and again at uninstallation time before the files are removed with argv1 set to -remove.
| How to extend distutils with a simple pre uninstall script? | I found Question#1321270 for post install. My main target for the moment is bdist_wininst, but i did not find anything related to uninstall...
For clarification:
I want to register a com server after installation and de-register it before uninstall.
Extended answer:
ars' answer seems correct, however, for the completeness of things (I think the docs leave some room for improvements on this topic...):
I have NOT as was suggested by mention of Question#1321270 extended distutils.command.install, but written a new python sript called scripts/install.py and set the following in setup.py:
setup(
...
scripts=['scripts\install.py'],
options = {
...
"bdist_wininst" : {
"install_script" : "install.py",
...
},
}
)
The install.py is definitively being called on install. It seems, though that it is (despite to what the docs say) not being called on uninstall...
| [
"The same post-install script will run at uninstall with different arguments. See the docs for more info:\n\nThis script will be run at installation time on the target system after all the files have been copied, with argv1 set to -install, and again at uninstallation time before the files are removed with argv1 s... | [
1
] | [] | [] | [
"distutils",
"python",
"setuptools"
] | stackoverflow_0003383801_distutils_python_setuptools.txt |
Q:
Zipping Collections
How do you zip two sequences in Clojure? IOW, What is the Clojure equivalent of Python zip(a, b)?
EDIT:
I know how to define such a function. I was just wondering whether standard library provides such a function already. (I would be *very* surprised if it doesn't.)
A:
You can easily define function like Python's zip:
(defn zip
[& colls]
(apply map vector colls))
In case of (zip a b), this becomes (map vector a b)
A:
if you want the input to be lists you can define a zip function like this
(defn zip [m] (apply map list m))
and call it like this
(zip '((1 2 3) (4 5 6)))
this call produces ((1 4) (2 5) (3 6))
A:
Is this is close enough?
(seq (zipmap [1 2 3] [4 5 6]))
;=> ([3 6] [2 5] [1 4])
| Zipping Collections | How do you zip two sequences in Clojure? IOW, What is the Clojure equivalent of Python zip(a, b)?
EDIT:
I know how to define such a function. I was just wondering whether standard library provides such a function already. (I would be *very* surprised if it doesn't.)
| [
"You can easily define function like Python's zip:\n(defn zip\n [& colls]\n (apply map vector colls))\n\nIn case of (zip a b), this becomes (map vector a b)\n",
"if you want the input to be lists you can define a zip function like this\n(defn zip [m] (apply map list m))\n\nand call it like this \n(zip '((1 2 3)... | [
3,
0,
0
] | [] | [] | [
"clojure",
"python",
"sequence",
"zip"
] | stackoverflow_0003382688_clojure_python_sequence_zip.txt |
Q:
Python daemonize
I would like to daemonize a python process, and now want to ask if it is good practice to have a daemon running, like a parent process and call another class which opens 10-30 threads.
I'm planning on writing a monitoring script for group of servers and would like to check every server every 5 mins, that each server is checked exactly 5minutes.
I would like to have it this way ( sort of speak, ps auxf style output ):
|monitor-daemon.py
\-check-server.py
\-check-server.py
....
Thank you!
A:
Maybe you should use http://pypi.python.org/pypi/python-daemon
A:
You can use supervisord for this. You can configure tasks to respond to events. The events can be manually created or automatically by monitoring processes or based on regular intervals.
It is fully customizable and written in Python.
Example:
[program:your_daemon_name]
command=your_daemon_process
# Add extra options here according to the manual...
[eventlistener:your_monitor_name]
command=your_monitor_process
events=PROCESS_STATE_RUNNING # Will be triggered after a program changes from starting to running
# Add extra options here according to the manual...
Or if you want the eventlistener to respond to the process output use the event PROCESS_COMMUNICATION_STDOUT or TICK_60 for a check every minute. The logs can be redirected to files and such so you can always view the state.
| Python daemonize | I would like to daemonize a python process, and now want to ask if it is good practice to have a daemon running, like a parent process and call another class which opens 10-30 threads.
I'm planning on writing a monitoring script for group of servers and would like to check every server every 5 mins, that each server is checked exactly 5minutes.
I would like to have it this way ( sort of speak, ps auxf style output ):
|monitor-daemon.py
\-check-server.py
\-check-server.py
....
Thank you!
| [
"Maybe you should use http://pypi.python.org/pypi/python-daemon\n",
"You can use supervisord for this. You can configure tasks to respond to events. The events can be manually created or automatically by monitoring processes or based on regular intervals.\nIt is fully customizable and written in Python.\nExample:... | [
8,
1
] | [
"There's really not much to creating your own daemonize function: The source for Advanced Programming in the Unix Environment (2nd edition) is freely available: http://www.apuebook.com/src.tar.gz -- you're looking for the apue.2e/daemons/init.c file.\nThere is a small helper program that does all the work of creati... | [
-2
] | [
"daemon",
"python"
] | stackoverflow_0003383741_daemon_python.txt |
Q:
From a python cgi can I write to Lighttpd log file?
I have a python cgi script (just python, I didn't use any framework). It's served using Lighttpd on openSUSE. I would like to redirect my logging statements (like logging.info and so on) to be included to Lighttpd log file. If this can't be done, how can I create my own log file?
A:
Your goal of logging to the lighttpd log file looks unlikely: http://redmine.lighttpd.net/boards/2/topics/16
It does seem that you could use the FastCGI interface to provide a place to write error messages.
Here's a simple tutorial on using python's logger facility to write to your own log files: http://docs.python.org/library/logging.html
| From a python cgi can I write to Lighttpd log file? | I have a python cgi script (just python, I didn't use any framework). It's served using Lighttpd on openSUSE. I would like to redirect my logging statements (like logging.info and so on) to be included to Lighttpd log file. If this can't be done, how can I create my own log file?
| [
"Your goal of logging to the lighttpd log file looks unlikely: http://redmine.lighttpd.net/boards/2/topics/16\nIt does seem that you could use the FastCGI interface to provide a place to write error messages.\nHere's a simple tutorial on using python's logger facility to write to your own log files: http://docs.pyt... | [
1
] | [] | [] | [
"cgi",
"lighttpd",
"logging",
"python"
] | stackoverflow_0003384021_cgi_lighttpd_logging_python.txt |
Q:
Mercurial: Permission Denied for hgwebdir
Yesterday I setup Apache to serve my Mercurial repositories and got everything working properly. I then tested pushing changes back to this repository and was presented with an error, and now that error pops up for every single operation I attempt - even just a simple GET request of the repositories! Here is the error:
mod_wsgi (pid=1771): Target WSGI script '/var/hg/hgweb.wsgi' cannot be loaded as Python module.
mod_wsgi (pid=1771): Exception occurred processing WSGI script '/var/hg/hgweb.wsgi'.
Traceback (most recent call last):
File "/var/hg/hgweb.wsgi", line 18, in ?
application = hgwebdir(config)
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/__init__.py", line 15, in hgwebdir
return hgwebdir_mod.hgwebdir(*args, **kwargs)
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/hgwebdir_mod.py", line 52, in __init__
self.refresh()
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/hgwebdir_mod.py", line 82, in refresh
self.repos = findrepos(paths)
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/hgwebdir_mod.py", line 36, in findrepos
for path in util.walkrepos(roothead, followsym=True, recurse=recurse):
File "/usr/lib64/python2.4/site-packages/mercurial/util.py", line 1164, in walkrepos
for hgname in walkrepos(fname, True, seen_dirs):
File "/usr/lib64/python2.4/site-packages/mercurial/util.py", line 1146, in walkrepos
for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
File "/usr/lib64/python2.4/os.py", line 276, in walk
onerror(err)
File "/usr/lib64/python2.4/site-packages/mercurial/util.py", line 1127, in errhandler
raise err
OSError: [Errno 13] Permission denied: './dev/fd'
My repository directory is owned by apache, the user running Apache. I dont know why './dev/fd' is being operated on either. I've restarted the server numerous times, recreated the repository directory, but I still get this error no matter what! I dont have access to restart the machine, so that is not an option. But it seems to have gotten in a very bad persistent state, and I dont know how to fix it. Any help is appreciated!
A:
This turned out to be a configuration error on my part, and rather than delete the question I'll post the resolution here in case someone has this problem in the future.
Here was the hgweb.config I was using:
[paths]
/ = /var/hg/repos/*
#[web]
style = gitweb
allow_archive = bz2 gz zip
maxchanges = 200
allow_push = *
push_ssl = false
Two problems here, one is obvious. I had the [web] header commented out, and I assume that many of the options are not valid for the [paths] section. Also, after re-reading the Hg docs again, the push_ssl directive does not belong in the hgweb.config file, but rather in each repository's .hg/hgrc (or the ~/.hgrc of the user that runs apache). After fixing these, things are working perfectly!
| Mercurial: Permission Denied for hgwebdir | Yesterday I setup Apache to serve my Mercurial repositories and got everything working properly. I then tested pushing changes back to this repository and was presented with an error, and now that error pops up for every single operation I attempt - even just a simple GET request of the repositories! Here is the error:
mod_wsgi (pid=1771): Target WSGI script '/var/hg/hgweb.wsgi' cannot be loaded as Python module.
mod_wsgi (pid=1771): Exception occurred processing WSGI script '/var/hg/hgweb.wsgi'.
Traceback (most recent call last):
File "/var/hg/hgweb.wsgi", line 18, in ?
application = hgwebdir(config)
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/__init__.py", line 15, in hgwebdir
return hgwebdir_mod.hgwebdir(*args, **kwargs)
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/hgwebdir_mod.py", line 52, in __init__
self.refresh()
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/hgwebdir_mod.py", line 82, in refresh
self.repos = findrepos(paths)
File "/usr/lib64/python2.4/site-packages/mercurial/hgweb/hgwebdir_mod.py", line 36, in findrepos
for path in util.walkrepos(roothead, followsym=True, recurse=recurse):
File "/usr/lib64/python2.4/site-packages/mercurial/util.py", line 1164, in walkrepos
for hgname in walkrepos(fname, True, seen_dirs):
File "/usr/lib64/python2.4/site-packages/mercurial/util.py", line 1146, in walkrepos
for root, dirs, files in os.walk(path, topdown=True, onerror=errhandler):
File "/usr/lib64/python2.4/os.py", line 276, in walk
onerror(err)
File "/usr/lib64/python2.4/site-packages/mercurial/util.py", line 1127, in errhandler
raise err
OSError: [Errno 13] Permission denied: './dev/fd'
My repository directory is owned by apache, the user running Apache. I dont know why './dev/fd' is being operated on either. I've restarted the server numerous times, recreated the repository directory, but I still get this error no matter what! I dont have access to restart the machine, so that is not an option. But it seems to have gotten in a very bad persistent state, and I dont know how to fix it. Any help is appreciated!
| [
"This turned out to be a configuration error on my part, and rather than delete the question I'll post the resolution here in case someone has this problem in the future.\nHere was the hgweb.config I was using:\n[paths]\n/ = /var/hg/repos/*\n\n#[web]\nstyle = gitweb\nallow_archive = bz2 gz zip\nmaxchanges = 200\nal... | [
3
] | [] | [] | [
"apache",
"mercurial",
"python"
] | stackoverflow_0003383426_apache_mercurial_python.txt |
Q:
Storing and replaying binary network data with python
I have a Python application which sends 556 bytes of data across the network at a rate of 50 Hz. The binary data is generated using struct.pack() which returns a string, which is subsequently written to a UDP socket.
As well as transmitting this data, I would like to save this data to file as space-efficiently as possible, including a timestamp for each message, so that I can replay the data at a later time. What would be the best way of doing this using Python?
I have mulled over using a logging object, but have not yet found out whether Python can read in log files so that I can replay the data. Also, I don't know whether the logging object can handle binary data.
Any tips would be much appreciated! Although Wireshark would be an option, I'd rather store the data using my application so that I can automatically start new data files each time I run the program.
A:
Python's logging system is intended to process human-readable strings, and it's intended to be easy to enable or disable depending on whether it's you (the developer) or someone else running your program. Don't use it for something that your application always needs to output.
The simplest way to store the data is to just write the same 556-byte string that you send over the socket out to a file. If you want to have timestamps, you could precede each 556-byte message with the time of sending, converted to an integer, and packed into 4 or 8 bytes using struct.pack(). The exact method would depend on your specific requirements, e.g. how precise you need the time to be, and whether you need absolute time or just relative to some reference point.
A:
One possibility for a compact timestamp for replay purposes...: set the time as a floating point number of seconds since the epoch with time.time(), multiply by 50 since you said you're repeating this 50 times a second (the resulting unit, one fiftieth of a second, is sometimes called "a jiffy"), truncate to int, subtract from the similar int count of jiffies since the epoch that you measured at the start of your program, and struct.pack the result into an unsigned int with the number of bytes you need to represent the intended duration -- for example, with 2 bytes for this timestamp, you could represent runs of about 1200 seconds (20 minutes), but if you plan longer runs you'd need 4 bytes (3 bytes is just too unwieldy IMHO;-).
Not all operating systems have time.time() returning decent precision, so you may need more devious means if you need to run on such unfortunately limited OSs. (That's VERY os-dependent, of course). What OSs do you need to support...?
Anyway...: for even more compactness, use a slightly higher multiplier than 50 (say 10000) for more accuracy, and store, each time, the difference wrt the previous timestamp -- since that difference should not be much different from a jiffy (if I understand your spec correctly) that should be about 200 or so of these "tenth-thousands of a second" and you can store a single unsigned byte (and have no limit wrt the duration of runs you're storing for future replay). This depends even more on accurate returns from time.time() of course.
If your 556-byte binary data is highly compressible, it will be worth your while to use gzip to store the stream of timestamp-then-data in compressed form; this is best assessed empirically on your actual data, though.
| Storing and replaying binary network data with python | I have a Python application which sends 556 bytes of data across the network at a rate of 50 Hz. The binary data is generated using struct.pack() which returns a string, which is subsequently written to a UDP socket.
As well as transmitting this data, I would like to save this data to file as space-efficiently as possible, including a timestamp for each message, so that I can replay the data at a later time. What would be the best way of doing this using Python?
I have mulled over using a logging object, but have not yet found out whether Python can read in log files so that I can replay the data. Also, I don't know whether the logging object can handle binary data.
Any tips would be much appreciated! Although Wireshark would be an option, I'd rather store the data using my application so that I can automatically start new data files each time I run the program.
| [
"Python's logging system is intended to process human-readable strings, and it's intended to be easy to enable or disable depending on whether it's you (the developer) or someone else running your program. Don't use it for something that your application always needs to output.\nThe simplest way to store the data i... | [
4,
1
] | [] | [] | [
"binary_data",
"python",
"serialization"
] | stackoverflow_0003384319_binary_data_python_serialization.txt |
Q:
How to build an undo storage with limit?
I want build a data structure to store limited undo buffer, take store 6 dict data for example with below pseudocode:
rawdict1 = {1}
buffer = [{1}]
rawdict1 = {2}
buffer = [{2}{1}] # {1} stored on the postion
rawdict1 = {3}
buffer = [{3}{2}{1}]
...
rawdict1 = {5}
buffer = [{5}{4}{3}{2}{1}] # max length limited to 5
rawdict1 = {6}
buffer = [{6}{5}{4}{3}{2}] # {1} has been deleted because exceed the limit
when I want to restore the rawdict1 later, I can use something looks like:
rawdict1 = buffer[5] # restore the 5th dict.
My question is, can existing buildin data type or standard library type can be used for such a purpose?
And is it possible such a structure can store multi-types in one structure instance, say, if I want to store dict and self-defined class in one go?
Thanks!
Rgs,
KC
A:
Perhaps use something like this:
import collections
class UndoBuffer(object):
def __init__(self,value,max_length=5):
self.max_length=max_length
self._buffer=collections.deque([value],max_length)
@property
def data(self):
return self._buffer[-1]
@data.setter
def data(self,value):
self._buffer.append(value)
def restore(self,index):
self.data=self._buffer[index]
Make an UndoBuffer object
rawdict=UndoBuffer('{1}')
Setting the data attribute automatically stores the value in _buffer:
print(rawdict._buffer)
# deque(['{1}'], maxlen=5)
print(rawdict.data)
# {1}
Changing the value of rawdict.data appends the value to rawdict._buffer:
rawdict.data = '{2}'
print(rawdict._buffer)
# deque(['{1}', '{2}'], maxlen=5)
Buf if you access rawdict.data you just get the most recent value:
print(rawdict.data)
# {2}
Change the value a few more times. '{1}' gets dropped when the buffer is filled to its maximum length:
rawdict.data = '{3}'
rawdict.data = '{4}'
rawdict.data = '{5}'
print(rawdict._buffer)
# deque(['{1}', '{2}', '{3}', '{4}', '{5}'], maxlen=5)
rawdict.data = '{6}'
print(rawdict._buffer)
# deque(['{2}', '{3}', '{4}', '{5}', '{6}'], maxlen=5)
Restoring the value from rawdict._buffer:
rawdict.restore(0) # set rawdict.data to rawdict._buffer[0]
print(rawdict.data)
# {2}
print(rawdict._buffer)
# deque(['{3}', '{4}', '{5}', '{6}', '{2}'], maxlen=5)
A:
You cannot do it on a barename (such as rawdict1) because there is no way for you to intercept assignments to a barename and make them do sometime "on the side" such as saving the previous value. It's easy to do on a decorated name, e.g.:
undoable.rawdict1 = {1}
and the like, by making undoable an instance of a class with an appropriate __setitem__ which appends the previous value (if any) to a list, and pops the 0th item if the list is getting too long. But that would not suffice for other "undoable" actions besides assignment, such as undoable.rawdict1.update(whatever) -- you sure you don't need that?
A:
You can quickly subclass the list to only allow limited storage.
class LimitedStack(list):
def __init__(self,limit=6):
list.__init__(self)
self.limit = limit
def append(self,obj):
if len(self) == self.limit:
list.pop(self,0)
list.append(self,obj)
Python lists do not have to be of a certain type like the generic lists in C#. They will store any object you append to them.
A:
The collections module, as of python 2.6, contains the "deque" collection. It behaves as you need:
>>> import collections
>>> buffer = collections.deque([],6)
>>> buffer.extend(range(6))
>>> buffer
deque([0, 1, 2, 3, 4, 5], maxlen=6)
>>> buffer.append(6)
>>> buffer
deque([1, 2, 3, 4, 5, 6], maxlen=6)
>>> buffer[-1]
6
A:
Rockford Lhotka's CSLA.NET framework contains an Undo architecture. Perhaps you could study it and figure out what he did, or even use it out of the box.
| How to build an undo storage with limit? | I want build a data structure to store limited undo buffer, take store 6 dict data for example with below pseudocode:
rawdict1 = {1}
buffer = [{1}]
rawdict1 = {2}
buffer = [{2}{1}] # {1} stored on the postion
rawdict1 = {3}
buffer = [{3}{2}{1}]
...
rawdict1 = {5}
buffer = [{5}{4}{3}{2}{1}] # max length limited to 5
rawdict1 = {6}
buffer = [{6}{5}{4}{3}{2}] # {1} has been deleted because exceed the limit
when I want to restore the rawdict1 later, I can use something looks like:
rawdict1 = buffer[5] # restore the 5th dict.
My question is, can existing buildin data type or standard library type can be used for such a purpose?
And is it possible such a structure can store multi-types in one structure instance, say, if I want to store dict and self-defined class in one go?
Thanks!
Rgs,
KC
| [
"Perhaps use something like this:\nimport collections\n\nclass UndoBuffer(object):\n def __init__(self,value,max_length=5):\n self.max_length=max_length\n self._buffer=collections.deque([value],max_length)\n @property\n def data(self):\n return self._buffer[-1]\n @data.setter\n d... | [
2,
1,
1,
1,
0
] | [] | [] | [
"fifo",
"python",
"storage",
"undo"
] | stackoverflow_0003384643_fifo_python_storage_undo.txt |
Q:
How do I track a blob using OpenCV and Python
I've gotten OpenCV working with Python and I can even detect a face through my webcam. What I really want to do though, is see movement and find the point in the middle of the blob of movement. The camshift sample is close to what I want, but I don't want to have to select which portion of the video to track. Bonus points for being able to predict the next frame.
Here's the code I have currently:
#!/usr/bin/env python
import cv
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class CamShiftDemo:
def __init__(self):
self.capture = cv.CaptureFromCAM(0)
cv.NamedWindow( "CamShiftDemo", 1 )
self.storage = cv.CreateMemStorage(0)
self.cascade = cv.Load("/usr/local/share/opencv/haarcascades/haarcascade_mcs_upperbody.xml")
self.last_rect = ((0, 0), (0, 0))
def run(self):
hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0,180)], 1 )
backproject_mode = False
i = 0
while True:
i = (i + 1) % 12
frame = cv.QueryFrame( self.capture )
if i == 0:
found = cv.HaarDetectObjects(frame, self.cascade, self.storage, 1.2, 2, 0, (20, 20))
for p in found:
# print p
self.last_rect = (p[0][0], p[0][1]), (p[0][2], p[0][3])
print self.last_rect
cv.Rectangle( frame, self.last_rect[0], self.last_rect[1], cv.CV_RGB(255,0,0), 3, cv.CV_AA, 0 )
cv.ShowImage( "CamShiftDemo", frame )
c = cv.WaitKey(7) % 0x100
if c == 27:
break
if __name__=="__main__":
demo = CamShiftDemo()
demo.run()
A:
Found a solution at How do I track motion using OpenCV in Python?
| How do I track a blob using OpenCV and Python | I've gotten OpenCV working with Python and I can even detect a face through my webcam. What I really want to do though, is see movement and find the point in the middle of the blob of movement. The camshift sample is close to what I want, but I don't want to have to select which portion of the video to track. Bonus points for being able to predict the next frame.
Here's the code I have currently:
#!/usr/bin/env python
import cv
def is_rect_nonzero(r):
(_,_,w,h) = r
return (w > 0) and (h > 0)
class CamShiftDemo:
def __init__(self):
self.capture = cv.CaptureFromCAM(0)
cv.NamedWindow( "CamShiftDemo", 1 )
self.storage = cv.CreateMemStorage(0)
self.cascade = cv.Load("/usr/local/share/opencv/haarcascades/haarcascade_mcs_upperbody.xml")
self.last_rect = ((0, 0), (0, 0))
def run(self):
hist = cv.CreateHist([180], cv.CV_HIST_ARRAY, [(0,180)], 1 )
backproject_mode = False
i = 0
while True:
i = (i + 1) % 12
frame = cv.QueryFrame( self.capture )
if i == 0:
found = cv.HaarDetectObjects(frame, self.cascade, self.storage, 1.2, 2, 0, (20, 20))
for p in found:
# print p
self.last_rect = (p[0][0], p[0][1]), (p[0][2], p[0][3])
print self.last_rect
cv.Rectangle( frame, self.last_rect[0], self.last_rect[1], cv.CV_RGB(255,0,0), 3, cv.CV_AA, 0 )
cv.ShowImage( "CamShiftDemo", frame )
c = cv.WaitKey(7) % 0x100
if c == 27:
break
if __name__=="__main__":
demo = CamShiftDemo()
demo.run()
| [
"Found a solution at How do I track motion using OpenCV in Python?\n"
] | [
4
] | [] | [] | [
"opencv",
"python",
"webcam"
] | stackoverflow_0003374422_opencv_python_webcam.txt |
Q:
Python extensions - performance
I am using Boost.Python to extend python program functionality. Python scripts do a lot of calls to native modules so I am really concerned about the performance of python-to-cpp type conversion and data marshaling.
I decided to try exposing methods natively through Python C API. May be somebody already tried that before ? Any success ... at least in theory ?
The problem I run into is that how to convert PyObject* back to class instance, PyArg_parse provides O& option, but what I am looking is simply a pointer to C++ object in memory... how can I get it in function ?
if ( PyArg_ParseTuple(args, "O", &pyTestClass ) )
{
// how to get TestClass from pyTestClass ??
}
Thanks
A:
I haven't tried Boost.Python, but I've extended Python using raw C as well as Cython. I recommend Cython; if you're careful enough you can get code with the same efficiency as raw C but with a lot less boilerplate code.
Regarding efficiency, it's relative. It depends on what you want to do and how you do it. For example, what I've done very often is write the inner loop of some image processing or matrix operation in C, and have this function be called by Python with pointers to matrices as arguments. The matrices themselves don't get copied, so the overhead is minimal.
| Python extensions - performance | I am using Boost.Python to extend python program functionality. Python scripts do a lot of calls to native modules so I am really concerned about the performance of python-to-cpp type conversion and data marshaling.
I decided to try exposing methods natively through Python C API. May be somebody already tried that before ? Any success ... at least in theory ?
The problem I run into is that how to convert PyObject* back to class instance, PyArg_parse provides O& option, but what I am looking is simply a pointer to C++ object in memory... how can I get it in function ?
if ( PyArg_ParseTuple(args, "O", &pyTestClass ) )
{
// how to get TestClass from pyTestClass ??
}
Thanks
| [
"I haven't tried Boost.Python, but I've extended Python using raw C as well as Cython. I recommend Cython; if you're careful enough you can get code with the same efficiency as raw C but with a lot less boilerplate code. \nRegarding efficiency, it's relative. It depends on what you want to do and how you do it. For... | [
1
] | [] | [] | [
"boost",
"native",
"performance",
"python"
] | stackoverflow_0003384854_boost_native_performance_python.txt |
Q:
Python 3.2 - GIL - good/bad?
Python 3.2 ALPHA is out.
From the Change Log, it appears the GIL has been entirely rewritten.
A few questions:
Is having a GIL good or bad? (and
why).
Is the new GIL better? If so, how?
UPDATE:
I'm fairly new to Python. So all of this is new to my but I do at least understand that the existence of a GIL with CPython is a huge deal.
Question though, why does CPython not just clone the interpreter like Perl does in an attempt to remove the need for the GIL?
A:
The best explanation I've seen as to why the GIL sucks is here:
http://www.dabeaz.com/python/GIL.pdf
And the same guy has a presentation on the new GIL here:
http://www.dabeaz.com/python/NewGIL.pdf
If that's all that's been done it still sucks - just not as bad. Multiple threads will behave better. Multi-core will still do nothing for you with a single python app.
A:
Is having a GIL good or bad? (and why).
Neither -- or both. It's necessary for thread synchronization.
Is the new GIL better? If so, how?
Have you run any benchmarks? If not, then perhaps you should (1) run a benchmark, (2) post the benchmark in the question and (3) ask specific questions about the benchmark results.
Discussing the GIL in vague, handwaving ways is largely a waste of time.
Discussing the GIL in the specific context of your benchmark, however, can lead to a solution to your performance problem.
Question though, why does CPython not just clone the interpreter like Perl does in an attempt to remove the need for the GIL?
Read this: http://perldoc.perl.org/perlthrtut.html
First, Perl didn't support threads at all. Older Perl interpreters had a buggy module that didn't work correctly.
Second, the newer Perl interpreter has this feature.
The biggest difference between Perl ithreads and the old 5.005 style threading, or for that matter, to most other threading systems out there, is that by default, no data is shared. When a new Perl thread is created, all the data associated with the current thread is copied to the new thread, and is subsequently private to that new thread!
Since the Perl (only specific data is shared) model is different from Python's (all data is shared) model, copying the Perl interpreter would fundamentally break Python's threads. The Perl thread model is fundamentally different.
A:
Is the new GIL better? If so, how?
Well, it at least replaces op-count switching to proper time-count. This does not increase overall performance (and could even hurt it due to more often switching), but this makes threads more responsive and eliminates cases when ALL threads get locked if one of them uses computation-heavy single op-code (like call to external function which does not release GIL).
why does CPython not just clone the interpreter like Perl does in an attempt to remove the need for the GIL?
GIL is complex issue, it should not be viewed as Ultimate Evil. It brings us thread-safety.
As for perl, perl is a) dead, b) too old. Guys at Google are working on bringing LLVM goodies to CPython, which, among others, will improve GIL behavior (no complete GIL removal yet, tho): http://code.google.com/p/unladen-swallow/
| Python 3.2 - GIL - good/bad? | Python 3.2 ALPHA is out.
From the Change Log, it appears the GIL has been entirely rewritten.
A few questions:
Is having a GIL good or bad? (and
why).
Is the new GIL better? If so, how?
UPDATE:
I'm fairly new to Python. So all of this is new to my but I do at least understand that the existence of a GIL with CPython is a huge deal.
Question though, why does CPython not just clone the interpreter like Perl does in an attempt to remove the need for the GIL?
| [
"The best explanation I've seen as to why the GIL sucks is here:\nhttp://www.dabeaz.com/python/GIL.pdf\nAnd the same guy has a presentation on the new GIL here:\nhttp://www.dabeaz.com/python/NewGIL.pdf\nIf that's all that's been done it still sucks - just not as bad. Multiple threads will behave better. Multi-core ... | [
25,
4,
1
] | [] | [] | [
"interpreter",
"locking",
"multithreading",
"python"
] | stackoverflow_0003384385_interpreter_locking_multithreading_python.txt |
Q:
rendering multipe html pages
I'm working on a project and i need to use multiple html pages to interact with my code
like:
viewing index.html first:-
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
and then when i press the sign out button the program should view this page:-
path = os.path.join(os.path.dirname(__file__), 'signOut.html')
self.response.out.write(template.render(path, template_values))
the problem is that the program views the two pages together at one time and this is not what i want.
could you plz tell me how can I view them seperately
A:
You need something like this:
class MainPage(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class SignOutPage(webapp.RequestHandler):
def get(self):
path = os.path.join(os.path.dirname(__file__), 'signOut.html')
self.response.out.write(template.render(path, template_values))
application = webapp.WSGIApplication(
[('/', MainPage),
('/signout', SignOutPage)],
debug=True)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
Your two pages will then be available at http://yourapp.appspot.com/ and http://yourapp.appspot.com/signout
This assumes that your app.yaml is mapping both urls to your .py file.
| rendering multipe html pages | I'm working on a project and i need to use multiple html pages to interact with my code
like:
viewing index.html first:-
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
and then when i press the sign out button the program should view this page:-
path = os.path.join(os.path.dirname(__file__), 'signOut.html')
self.response.out.write(template.render(path, template_values))
the problem is that the program views the two pages together at one time and this is not what i want.
could you plz tell me how can I view them seperately
| [
"You need something like this:\nclass MainPage(webapp.RequestHandler):\n def get(self):\n path = os.path.join(os.path.dirname(__file__), 'index.html') \n self.response.out.write(template.render(path, template_values))\n\nclass SignOutPage(webapp.RequestHandler):\n def get(self):\n ... | [
2
] | [] | [] | [
"google_app_engine",
"html",
"python"
] | stackoverflow_0003385119_google_app_engine_html_python.txt |
Q:
Python dictionary error
In the below code d_arr is an array of dictionaries
def process_data(d_arr):
flag2 = 0
for dictionaries in d_arr:
for k in dictionaries:
if ( k == "*TYPE" ):
""" Here we determine the type """
if (dictionaries[k].lower() == "name"):
dictionaries.update({"type" : 0})
func = name(dictionaries)
continue
elif (dictionaries[k].lower() == "ma"):
dictionaries.update({"type" : 1})
func = DCC(dictionaries)
logging.debug(type(func))
continue
When the above is done i get an error saying
for k in dictionaries:
RuntimeError: dictionary changed size during iteration
2010-08-02 05:26:44,167 DEBUG Returning
Is this forbidden to do something like this
A:
That error is pretty informative; you can't change the size of a dictionary you are currently iterating over.
The solution is to get the keys all at once and iterate over them:
# Do this
for k in dictionaries.keys():
# Not this
for k in dictionaries:
A:
It is, indeed, forbidden. Moreover, you don't really need a loop over all keys here, given that the weirdly named dictionaries appears to be a single dict; rather than the for k in dictionaries: (or the workable for k in dictionaries.keys() that @Triptych's answer suggests), you could use...:
tp = dictionaries.get('*TYPE')
if tp is not None:
""" Here we determine the type """
if tp.lower() == 'name':
dictionaries.update({"type" : 0})
func = name(dictionaries)
elif tp.lower() == "ma":
dictionaries.update({"type" : 1})
func = DCC(dictionaries)
logging.debug(type(func))
This is going to be much faster if dictionaries has any considerable length, for you're reaching directly for the one entry you care about, rather than looping over all entries to check each of them for the purpose of seeing if it is the one you care about.
Even if you've chosen to omit part of your code, so that after this start the loop on dictionaries is still needed, I think my suggestion is still preferable because it lets you get any alteration to dictionaries done and over with (assuming of course that you don't keep altering it in the hypothetical part of your code I think you may have chosen to omit;-).
| Python dictionary error | In the below code d_arr is an array of dictionaries
def process_data(d_arr):
flag2 = 0
for dictionaries in d_arr:
for k in dictionaries:
if ( k == "*TYPE" ):
""" Here we determine the type """
if (dictionaries[k].lower() == "name"):
dictionaries.update({"type" : 0})
func = name(dictionaries)
continue
elif (dictionaries[k].lower() == "ma"):
dictionaries.update({"type" : 1})
func = DCC(dictionaries)
logging.debug(type(func))
continue
When the above is done i get an error saying
for k in dictionaries:
RuntimeError: dictionary changed size during iteration
2010-08-02 05:26:44,167 DEBUG Returning
Is this forbidden to do something like this
| [
"That error is pretty informative; you can't change the size of a dictionary you are currently iterating over.\nThe solution is to get the keys all at once and iterate over them:\n# Do this\nfor k in dictionaries.keys():\n\n# Not this\nfor k in dictionaries:\n\n",
"It is, indeed, forbidden. Moreover, you don't r... | [
3,
3
] | [] | [] | [
"python"
] | stackoverflow_0003385219_python.txt |
Q:
Confused how to import modules in python
If I want to use a 3rd party module like a python s3 module (boto http://boto.s3.amazonaws.com/index.html) or http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134.
Once I download the .py files, what do I do?
Where does the python interpreter look when I import a module?
Is there a 'lightweight' way of installing a module so it makes deploying to a server easier?
A:
Look in the import statement reference, a long and involved description.
The simple method is to include the module's location in sys.path.
I'm quoting the starting paragraph only:
Once the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), searching for the module or package can begin. The first place checked is sys.modules, the cache of all modules that have been imported previously. If the module is found there then it is used in step (2) of import.
If the module is not found in the cache, then sys.meta_path is searched (the specification for sys.meta_path can be found in PEP 302). The object is a list of finder objects which are queried in order as to whether they know how to load the module by calling their find_module() method with the name of the module. If the module happens to be contained within a package (as denoted by the existence of a dot in the name), then a second argument to find_module() is given as the value of the path attribute from the parent package (everything up to the last dot in the name of the module being imported). If a finder can find the module it returns a loader (discussed later) or returns None.
If none of the finders on sys.meta_path are able to find the module then some implicitly defined finders are queried. Implementations of Python vary in what implicit meta path finders are defined. The one they all do define, though, is one that handles sys.path_hooks, sys.path_importer_cache, and sys.path.
A:
It looks in the directory that you are currently working from. For example, if you are trying to import it from inside /test/my_file.py, you can place the module in /test/ and simply import module_name
| Confused how to import modules in python | If I want to use a 3rd party module like a python s3 module (boto http://boto.s3.amazonaws.com/index.html) or http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134.
Once I download the .py files, what do I do?
Where does the python interpreter look when I import a module?
Is there a 'lightweight' way of installing a module so it makes deploying to a server easier?
| [
"Look in the import statement reference, a long and involved description.\nThe simple method is to include the module's location in sys.path.\nI'm quoting the starting paragraph only:\n\nOnce the name of the module is known (unless otherwise specified, the term “module” will refer to both packages and modules), sea... | [
1,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0003385204_module_python.txt |
Q:
How to wrap a python dict?
I want to implement a class that will wrap -- not subclass -- the python dict object, so that when a change is detected in a backing store I can re-create the delegated dict object. I intend to check for changes in the backing store each time the dict is accessed for a read.
Supposing I was to create an object to act like this; what methods would I need to implement?
A:
You can subclass the ABC (abstract base class) collections.Mapping (or collections.MutableMapping if you also want to allow code using your instances to alter the simulated/wrapped dictionary, e.g. by indexed assignment, pop, etc).
If you do so, then, as the docs I pointed to imply somewhat indirectly, the methods you need to implement are
__len__
__iter__
__getitem__
(for a Mapping) -- you should also implement
__contains__
because by delegating to the dict you're wrapping it can be done much faster than the iterating approach the ABC would have to apply otherwise.
If you need to supply a MutableMapping then you also need to implement 2 more methods:
__setitem__
__delitem__
A:
In addition to what's already been suggested, you might want to take a look at UserDict.
For an example of a dict like object, you can read through django's session implementation, specifically the SessionBase class.
A:
I think it depends on which methods you use. Probably __getitem__, __setitem__, __iter__ and __len__ as most things can be implemented in terms of those. But you'll want to look at some use cases, particularly with __iter__. Something like this:
for key in wrapped_dictionary:
do_something(wrapped_dictionary[key])
...is going to be slow if you hit the data source on each iteration, not to mention that it might not even work if the data source is changing out from under you. So you'll want to maybe throw some sort of exception there and implement iteritems as an alternative, loading all the key-value pairs in one batch before you loop over them.
The Python docs have item listings where you can look for methods and use-cases.
| How to wrap a python dict? | I want to implement a class that will wrap -- not subclass -- the python dict object, so that when a change is detected in a backing store I can re-create the delegated dict object. I intend to check for changes in the backing store each time the dict is accessed for a read.
Supposing I was to create an object to act like this; what methods would I need to implement?
| [
"You can subclass the ABC (abstract base class) collections.Mapping (or collections.MutableMapping if you also want to allow code using your instances to alter the simulated/wrapped dictionary, e.g. by indexed assignment, pop, etc).\nIf you do so, then, as the docs I pointed to imply somewhat indirectly, the method... | [
13,
3,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003385269_dictionary_python.txt |
Q:
Private Variables and Methods in Python
Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python
Which should I use _foo (an underscore) or __bar (double underscore) for private members and methods in Python?
A:
Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:
>>> class A(object):
... def __foo(self):
... pass
...
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()
So therefore __ prefix is useful when you need the mangling to occur, for example to not clash with names up or below inheritance chain. For other uses, single underscore would be better, IMHO.
EDIT, regarding confusion on __, PEP-8 is quite clear on that:
If your class is intended to be subclassed, and you have attributes
that you do not want subclasses to use, consider naming them with
double leading underscores and no trailing underscores. This invokes
Python's name mangling algorithm, where the name of the class is
mangled into the attribute name. This helps avoid attribute name
collisions should subclasses inadvertently contain attributes with the
same name.
Note 3: Not everyone likes name mangling. Try to balance the
need to avoid accidental name clashes with potential use by
advanced callers.
So if you don't expect subclass to accidentally re-define own method with same name, don't use it.
A:
The double underscore. It mangles the name in such a way that it can't be accessed simply through __fieldName from outside the class, which is what you want to begin with if they're to be private. (Though it's still not very hard to access the field.)
class Foo:
def __init__(self):
self.__privateField = 4;
print self.__privateField # yields 4 no problem
foo = Foo()
foo.__privateField
# AttributeError: Foo instance has no attribute '__privateField'
It will be accessible through _Foo__privateField instead. But it screams "I'M PRIVATE DON'T TOUCH ME", which is better than nothing.
A:
Double underscore. That mangles the name. The variable can still be accessed, but it's generally a bad idea to do so.
Use single underscores for semi-private (tells python developers "only change this if you absolutely must") and doubles for fully private.
| Private Variables and Methods in Python |
Possible Duplicate:
The meaning of a single- and a double-underscore before an object name in Python
Which should I use _foo (an underscore) or __bar (double underscore) for private members and methods in Python?
| [
"Please note that there is no such thing as \"private method\" in Python. Double underscore is just name mangling:\n>>> class A(object):\n... def __foo(self):\n... pass\n... \n>>> a = A()\n>>> A.__dict__.keys()\n['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']\n>>> a._A__foo()\n\nSo there... | [
71,
42,
10
] | [
"Because thats coding convention.\nSee here for more.\n"
] | [
-4
] | [
"double_underscore",
"private",
"private_members",
"private_methods",
"python"
] | stackoverflow_0003385317_double_underscore_private_private_members_private_methods_python.txt |
Q:
Programming thunderbird Email Client?
Anyone has C#/Ruby/Python/Java or Perl scripts to get all the emails in a folder in Thunderbird client and download all the attachments?
I have more than 200 resumes as attachment kept in Resumes folder of thunderbird and I need to download the attachment and categories them. Any API reference to program thunderbird would be great..
I found this http://kb.mozillazine.org/Calling_Thunderbird_from_other_programs but I am looking for specific code samples..
Other references
https://developer.mozilla.org/en/pyxpcom
A:
If you are happy using existing tools, instead of writing your own, you could give the Thunderbird Add-on AttachmentExtractor a try.
A:
Give this a try:
How To Bulk Export Thunderbird Email & Attachments
http://blog.taragana.com/index.php/archive/how-to-bulk-export-thunderbird-email-attachments/
| Programming thunderbird Email Client? | Anyone has C#/Ruby/Python/Java or Perl scripts to get all the emails in a folder in Thunderbird client and download all the attachments?
I have more than 200 resumes as attachment kept in Resumes folder of thunderbird and I need to download the attachment and categories them. Any API reference to program thunderbird would be great..
I found this http://kb.mozillazine.org/Calling_Thunderbird_from_other_programs but I am looking for specific code samples..
Other references
https://developer.mozilla.org/en/pyxpcom
| [
"If you are happy using existing tools, instead of writing your own, you could give the Thunderbird Add-on AttachmentExtractor a try.\n",
"Give this a try:\nHow To Bulk Export Thunderbird Email & Attachments\nhttp://blog.taragana.com/index.php/archive/how-to-bulk-export-thunderbird-email-attachments/\n"
] | [
0,
0
] | [] | [] | [
"java",
"python",
"ruby",
"scripting",
"thunderbird"
] | stackoverflow_0003385209_java_python_ruby_scripting_thunderbird.txt |
Q:
IDLE processes numerical input in a weird way (python 2.6)
If you simply type an integer after the >>> prompt they give you in the IDLE interpreter, most of the time it'll simply bounce the number back at you.
>>> 3
3
>>> 8
8
>>> 10
10
Start the nubmer off with a 0 however, and some interesting errors happen.
>>> 010
8
>>> 020
16
A:
In Python 2, an integer literal starting with 0 is considered octal, i.e. in base 8. And obviously, 10 oct == 8 dec (or generally, 10 in base b == b base 10). Likewise, 12 oct == 10 dec, and so on.
| IDLE processes numerical input in a weird way (python 2.6) | If you simply type an integer after the >>> prompt they give you in the IDLE interpreter, most of the time it'll simply bounce the number back at you.
>>> 3
3
>>> 8
8
>>> 10
10
Start the nubmer off with a 0 however, and some interesting errors happen.
>>> 010
8
>>> 020
16
| [
"In Python 2, an integer literal starting with 0 is considered octal, i.e. in base 8. And obviously, 10 oct == 8 dec (or generally, 10 in base b == b base 10). Likewise, 12 oct == 10 dec, and so on.\n"
] | [
11
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0003385646_python_syntax.txt |
Q:
how to access the list in different function
I have made a class in which there are 3 functions.
def maxvalue
def min value
def getAction
In the def maxvalue function, I have made a list of actions. I want that list to be accessed in def getaction function so that I can reverse the list and then take out the first entry from it. How can do i that??
def getAction(self,gamestate):
bestaction.reverse()
return bestaction[0]
def maxvalue(gameState, depth):
actions = gameState.getLegalActions(0);
v = -9999
bestaction = []
for action in actions:
marks = minvalue(gameState.generateSuccessor(0, action), depth, 1)
if(v < marks):
v = marks
bestaction.append(action)
return v
It is giving me an error....."global name bestaction is not defined"
A:
Either define the list as a class attribute or as an instance attribute, then all the methods will be able to access it
If you'd like to post your class, it'll be easier to show you what I mean
Here is an example making it a class attribute
class Foo(object):
list_of_actions = ['action1', 'action2']
def max_value(self):
print self.list_of_actions
def min_value(self):
print self.list_of_actions
def get_action(self):
list_of_actions = self.list_of_actions[-2::-1]
print list_of_actions
And here as an instance attribute
class Foo(object):
def __init__(self):
self.list_of_actions = ['action1', 'action2']
def max_value(self):
print self.list_of_actions
def min_value(self):
print self.list_of_actions
def get_action(self):
list_of_actions = self.list_of_actions[-2::-1]
print list_of_actions
Edit since you posted code, here is how to fix your problem
def getAction(self,gamestate):
self.bestaction.reverse()
return bestaction[0]
def maxvalue(gameState, depth):
actions = gameState.getLegalActions(0);
v = -9999
self.bestaction = []
for action in actions:
marks = minvalue(gameState.generateSuccessor(0, action), depth, 1)
if v < marks:
v = marks
self.bestaction.append(action)
return
A:
It's a good idea to post actual code - it makes it easier to see what's happening.
With that said, you probably want something like this:
class MyClass(object):
def max_value(self):
# assigning your list like this will make it accessible
# from other methods in the class
self.list_in_max_value = ["A", "B", "C"]
def get_action(self):
# here, we're doing something with the list
self.list_in_max_value.reverse()
return self.list_in_max_value[0]
>>> my_class = MyClass()
>>> my_class.max_value()
>>> my_class.get_action()
"C"
You might want to read through the python class tutorial.
A:
You could use a side effect to create an attribute of the class..
class Example(object):
def maxvalue(self, items)
self.items = items
return max(item for item in items)
| how to access the list in different function | I have made a class in which there are 3 functions.
def maxvalue
def min value
def getAction
In the def maxvalue function, I have made a list of actions. I want that list to be accessed in def getaction function so that I can reverse the list and then take out the first entry from it. How can do i that??
def getAction(self,gamestate):
bestaction.reverse()
return bestaction[0]
def maxvalue(gameState, depth):
actions = gameState.getLegalActions(0);
v = -9999
bestaction = []
for action in actions:
marks = minvalue(gameState.generateSuccessor(0, action), depth, 1)
if(v < marks):
v = marks
bestaction.append(action)
return v
It is giving me an error....."global name bestaction is not defined"
| [
"Either define the list as a class attribute or as an instance attribute, then all the methods will be able to access it\nIf you'd like to post your class, it'll be easier to show you what I mean\nHere is an example making it a class attribute\nclass Foo(object):\n list_of_actions = ['action1', 'action2']\n d... | [
1,
1,
0
] | [] | [] | [
"function",
"list",
"python"
] | stackoverflow_0003385796_function_list_python.txt |
Q:
Reading RSS Feeds: What Aggregators Do That I'm Not
I drop the following feed into Google Reader, and it update normally.
http://www.indeed.ca/rss?q=&l=Hamilton%2C+ON
However, when I use any of a number of approaches suggested thither and yon on the 'net that simply involve reading from this source and parsing the XML I receive the same 20 items.
What is Google Reader doing that I should be in my code so that I receive new items?
Thanks for your advice. Incidentally, I'm coding in Python.
A:
RSS aggregators "poll" the sources, i.e., they repeat the HTTP query periodically on each source, and check if anything new appears in the results. That's unfortunate, as polling always is, as it wastes resources in an unending series of "are we there yet?" questions (kind of like taking a toddler along in a long car drive;-), and nevertheless implies delays (if you poll a given source every hour, say, you'll wait up to an hour to see some results).
Unfortunately, in the RSS architecture itself, there are no alternatives, no way to ask for a "callback" when new stuff appears or opt for a saner "publish-subscribe architecture".
A good effort to remedy that is pubsubhubbub, but it inevitably requires cooperation (above and beyond the RSS standards) from RSS sources and aggregators -- so it needs very wide takeup before it can be called "a solution" to the problem, though, technically, it already is (for cooperating sites;-).
So back to your question, you're doing nothing wrong: you just need to poll periodically, like RSS aggregators do, in order to get to see new results eventually.
A:
1) Have you tried with other RSS feeds?
2) If so, it sounds like some kind of cache... Are you behind some proxy?
| Reading RSS Feeds: What Aggregators Do That I'm Not | I drop the following feed into Google Reader, and it update normally.
http://www.indeed.ca/rss?q=&l=Hamilton%2C+ON
However, when I use any of a number of approaches suggested thither and yon on the 'net that simply involve reading from this source and parsing the XML I receive the same 20 items.
What is Google Reader doing that I should be in my code so that I receive new items?
Thanks for your advice. Incidentally, I'm coding in Python.
| [
"RSS aggregators \"poll\" the sources, i.e., they repeat the HTTP query periodically on each source, and check if anything new appears in the results. That's unfortunate, as polling always is, as it wastes resources in an unending series of \"are we there yet?\" questions (kind of like taking a toddler along in a ... | [
3,
0
] | [] | [] | [
"aggregator",
"python",
"rss"
] | stackoverflow_0003382942_aggregator_python_rss.txt |
Q:
Including Flash content inline in a custom Weblog?
I'm trying to think of a way to place Flash content into a blog post so that it appears inline between paragraphs. I'm writing a custom weblog application in Django (still learning) and I'll be using SWFObject for the embedding.
The blog is for me only so the back-end isn't too fancy. I'm simply using Django's built in admin interface. No TinyMCE rich text editor (like Wordpress), rather I've implemented Markdown.
I'd like to add Flash content into the body of a post, between paragraphs, in a way that is not coupled to any third party script. Meaning, I would prefer not to include javascript within the body of the blog post as it introduces a dependency on SWFObject. For example, I could quite easily add the following to an entry via the back-end to embed a SWF inline:
Paragraph one...
<script type="text/javascript">
swfobject.embedSWF("/path/to/flash.swf", "myContent", "200", "200", "9.0.0");
</script>
<div id="myContent"></div>
Paragraph two...
As you can see this is quite wordy and a lot to remember but it also refers to SWFObject directly. This WILL work, however I would prefer to write it in a "cleaner" more abstract way. What I was thinking of doing is creating my own parser which would translate a custom string into the above just before rendering a template.
[#SWF swf="/path/to/flash.swf" w="200" h="200" ver="9.0.0"]
I'm wondering if anyone has encountered this issue. I'd love to know how you solved it.
A:
You might want to look into OEmbed, specifically the django-oembed project.
| Including Flash content inline in a custom Weblog? | I'm trying to think of a way to place Flash content into a blog post so that it appears inline between paragraphs. I'm writing a custom weblog application in Django (still learning) and I'll be using SWFObject for the embedding.
The blog is for me only so the back-end isn't too fancy. I'm simply using Django's built in admin interface. No TinyMCE rich text editor (like Wordpress), rather I've implemented Markdown.
I'd like to add Flash content into the body of a post, between paragraphs, in a way that is not coupled to any third party script. Meaning, I would prefer not to include javascript within the body of the blog post as it introduces a dependency on SWFObject. For example, I could quite easily add the following to an entry via the back-end to embed a SWF inline:
Paragraph one...
<script type="text/javascript">
swfobject.embedSWF("/path/to/flash.swf", "myContent", "200", "200", "9.0.0");
</script>
<div id="myContent"></div>
Paragraph two...
As you can see this is quite wordy and a lot to remember but it also refers to SWFObject directly. This WILL work, however I would prefer to write it in a "cleaner" more abstract way. What I was thinking of doing is creating my own parser which would translate a custom string into the above just before rendering a template.
[#SWF swf="/path/to/flash.swf" w="200" h="200" ver="9.0.0"]
I'm wondering if anyone has encountered this issue. I'd love to know how you solved it.
| [
"You might want to look into OEmbed, specifically the django-oembed project.\n"
] | [
1
] | [] | [] | [
"blogs",
"django",
"flash",
"python"
] | stackoverflow_0003382170_blogs_django_flash_python.txt |
Q:
List of lists and "Too many values to unpack"
I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code:
for index, item in outputList1:
outputList2 = outputList2.append(item[6:].extend(outputList1[index+1][6:]))
However, I get a "Too many values to unpack" error. I seem to even get the error with the following code:
for index, item in outputList1:
pass
What could I be doing wrong?
A:
the for statement iterates over an iterable -- in the case of a list, it iterates over the contents, one by one, so in each iteration, one value is available.
When using for index, item in list: you are trying to unpack one value into two variables. This would work with for key, value in dict.items(): which iterates over the dicts keys/values in arbitrary order. Since you seem to want a numerical index, there exists a function enumerate() which gets the value of an iterable, as well as an index for it:
for index, item in enumerate(outputList1):
pass
edit: since the title of your question mentions 'list of lists', I should point out that, when iterating over a list, unpacking into more than one variable will work if each list item is itself an iterable. For example:
list = [ ['a', 'b'], ['c', 'd'] ]
for item1, item2 in list:
print item1, item2
This will output:
a b
c d
as expected. This works in a similar way that dicts do, only you can have two, three, or however many items in the contained lists.
A:
You've forgotten to use enumerate, you mean to do this:
for index,item in enumerate(outputList1) :
pass
| List of lists and "Too many values to unpack" | I'm trying to use the following code on a list of lists to create a new list of lists, whose new elements are a certain combination of elements from the lists inside the old list...if that makes any sense! Here is the code:
for index, item in outputList1:
outputList2 = outputList2.append(item[6:].extend(outputList1[index+1][6:]))
However, I get a "Too many values to unpack" error. I seem to even get the error with the following code:
for index, item in outputList1:
pass
What could I be doing wrong?
| [
"the for statement iterates over an iterable -- in the case of a list, it iterates over the contents, one by one, so in each iteration, one value is available.\nWhen using for index, item in list: you are trying to unpack one value into two variables. This would work with for key, value in dict.items(): which itera... | [
25,
11
] | [] | [] | [
"python"
] | stackoverflow_0003386107_python.txt |
Q:
Python if statement "SyntaxError: invalid syntax"
Trying to execute someone's code, getting a syntax error. No idea why :(
def GetParsers( self, systags ):
childparsers = reduce( lambda a,b : a+b, [[]] + [ plugin.GetParsers( systags ) for plugin in self.plugins ] )
parsers = [ p for plist in [ self.parsers[t] for t in systags if self.parsers.has_key(t) ] for p in plist ]
return reduce( lambda a,b : ( a+[b] if not b in a else a ), [[]] + parsers + childparsers )
And the error is
File "base.py", line 100
return reduce( lambda a,b : ( a+[b] if not b in a else a ), [[]] + parsers + childparsers )
Python Version
Python 2.2.3 (#1, May 1 2006, 12:33:49)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] on linux2
^
A:
Conditional expressions were added in 2.5 (source) - you have 2.2. So no conditional expressions for you, I fear. They just don't exist yet in that version. Definitively update (not only for this little change, there are literally thousands of them since '06) if you can.
A:
You need to upgrade your Python installation to at least 2.5. More Information
A:
Upgrading to a newer version of Python will be the best solution, but if for some reason you can't upgrade you could update the code to use the and-or trick.
So this:
>>> 'a' if 1 == 2 else 'b'
'b'
Becomes:
>>> (1 == 2) and 'a' or 'b'
'b'
There is a slight problem here in that if the value you're return for True itself evaluates to False this statement won't work as you want. You can work around this as follows:
>>> ((1 == 2) and ['a'] or ['b'])[0]
'b'
In this case because the value is a non-empty list it will never evaluate to False so the trick will always work.
| Python if statement "SyntaxError: invalid syntax" | Trying to execute someone's code, getting a syntax error. No idea why :(
def GetParsers( self, systags ):
childparsers = reduce( lambda a,b : a+b, [[]] + [ plugin.GetParsers( systags ) for plugin in self.plugins ] )
parsers = [ p for plist in [ self.parsers[t] for t in systags if self.parsers.has_key(t) ] for p in plist ]
return reduce( lambda a,b : ( a+[b] if not b in a else a ), [[]] + parsers + childparsers )
And the error is
File "base.py", line 100
return reduce( lambda a,b : ( a+[b] if not b in a else a ), [[]] + parsers + childparsers )
Python Version
Python 2.2.3 (#1, May 1 2006, 12:33:49)
[GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] on linux2
^
| [
"Conditional expressions were added in 2.5 (source) - you have 2.2. So no conditional expressions for you, I fear. They just don't exist yet in that version. Definitively update (not only for this little change, there are literally thousands of them since '06) if you can.\n",
"You need to upgrade your Python inst... | [
5,
4,
1
] | [] | [] | [
"python",
"syntax_error"
] | stackoverflow_0003385539_python_syntax_error.txt |
Q:
A scalable solution for server side push?
I would like to implement a mechanism which will provide a RESTful API that allows a client to register interest in a subject with a sever, and receive asynchronous notifications from the server after the interest is registered. In enterprise (messaging) architecture, this is known as publish/subscribe 'pattern'.
With desktop applications, this is readily acheivable - however with web applications, it is proving to be more difficult.
is there a (preferably open source) framework or library out there that allows the publish/subscribe pattern to be applied to web applications?.
Server side technology may be in any of the following languages: C, C++, PHP, Python, Ruby.
I am running on Linux Ubuntu 10.0.4
A:
Have a look at the pubsubhubbub protocol: http://en.wikipedia.org/wiki/PubSubHubbub
Here is the source of the project: http://code.google.com/p/pubsubhubbub/
A:
If you know in advance you'll have a lot of subscribers (people/applications) that want notifications on a certain subject while on other hand you'll have few different subjects consider a pull technology anyway.
RSS, Atom are quite successful even though they use pull. The reason: no need to have an administration on the server of people who are subscribed, to detect who is no longer interested (client offline for a long time) or having a mechanism to get all the data out to the subscribers.
Using push, you need to do very little on the server, while the clients will only pull a small amount of data everytime.
Pull costs slightly more bandwidth that's cheap anyway while it saves you a lot on CPU and software maintanance which is quite expensive.
A:
I suggest you take a look at STOMP protocol, and its python clients (I use stomp.py). That should suit all your needs.
| A scalable solution for server side push? | I would like to implement a mechanism which will provide a RESTful API that allows a client to register interest in a subject with a sever, and receive asynchronous notifications from the server after the interest is registered. In enterprise (messaging) architecture, this is known as publish/subscribe 'pattern'.
With desktop applications, this is readily acheivable - however with web applications, it is proving to be more difficult.
is there a (preferably open source) framework or library out there that allows the publish/subscribe pattern to be applied to web applications?.
Server side technology may be in any of the following languages: C, C++, PHP, Python, Ruby.
I am running on Linux Ubuntu 10.0.4
| [
"Have a look at the pubsubhubbub protocol: http://en.wikipedia.org/wiki/PubSubHubbub\nHere is the source of the project: http://code.google.com/p/pubsubhubbub/\n",
"If you know in advance you'll have a lot of subscribers (people/applications) that want notifications on a certain subject while on other hand you'll... | [
3,
2,
0
] | [] | [] | [
"linux",
"php",
"publish_subscribe",
"python",
"server_push"
] | stackoverflow_0003377951_linux_php_publish_subscribe_python_server_push.txt |
Q:
list query, functions in function
i have a function:
I need to first reverse the list and then take an entry from it.
Earlier, I was making the 3 functions but now I am defining the main function and the other 2 functions in it.
A:
Your code is very unpythonic. Remember Python is not C.
The semicolon is optional.
The parenthesis in an if is optional.
To get the last element of list a, use a[-1], not reversing a then get its first element.
Use the built-in functions! Your modified maxagent can be written simply using the max function:
def maxagent(gamestate, depth):
actions = gamestate.getLegalActions(0)
filteredactions = filter(lambda action: action != Directions.STOP, actions)
# alternatives:
# filteredactions = filter(Directions.STOP.__ne__, actions)
# filteredactions = (a for a in actions if a != Directions.STOP)
bestaction = max(filteredactions,
key=lambda action: self.minvalue(
gamestate.generateSuccessor(0, action),
depth, 1
))
return bestaction
If you need the score too, consider returning a tuple.
def maxagent(gamestate, depth)
actions = gamestate.getLegalActions(0)
scores = ( (self.minvalue(gamestate.generateSuccessor(0, a), depth, 1), a)
for a in actions if a != Directions.STOP
)
return max(scores)
...
score, action = maxagent(gamestate, depth)
| list query, functions in function | i have a function:
I need to first reverse the list and then take an entry from it.
Earlier, I was making the 3 functions but now I am defining the main function and the other 2 functions in it.
| [
"Your code is very unpythonic. Remember Python is not C. \n\nThe semicolon is optional.\nThe parenthesis in an if is optional. \nTo get the last element of list a, use a[-1], not reversing a then get its first element.\nUse the built-in functions! Your modified maxagent can be written simply using the max function:... | [
4
] | [] | [] | [
"function",
"list",
"python"
] | stackoverflow_0003386211_function_list_python.txt |
Q:
A django problem that doesn't show up in runserver
In runserver, I can view my website no problems. (viewing it through lynx on the same machine)
But when I view the same thing through apache, (passenger) I get an error like the following:
Could not import PROJ.APP.views Error was: No module named PROJ.views
It looks like a problem with the urlconf, but again that is the same between both runserver and not.
I have disabled admin & admin autodiscovery.
I have killed all running python instances & deleted all .pyc files. I don't use any {% url %} tags in any templates.
The question is in general, what type of things could be causing this?
solved it was a problem of relative imports. In some files I was importing APP.models instead of PROJ.APP.models.
A:
SOLVED
It was a problem of relative imports. In some files I was importing APP.models instead of PROJ.APP.models.
The error wasn't giving any indication of which file was causing the problem. Once I changed all of them it was fine. Thanks, guys.
| A django problem that doesn't show up in runserver | In runserver, I can view my website no problems. (viewing it through lynx on the same machine)
But when I view the same thing through apache, (passenger) I get an error like the following:
Could not import PROJ.APP.views Error was: No module named PROJ.views
It looks like a problem with the urlconf, but again that is the same between both runserver and not.
I have disabled admin & admin autodiscovery.
I have killed all running python instances & deleted all .pyc files. I don't use any {% url %} tags in any templates.
The question is in general, what type of things could be causing this?
solved it was a problem of relative imports. In some files I was importing APP.models instead of PROJ.APP.models.
| [
"SOLVED\nIt was a problem of relative imports. In some files I was importing APP.models instead of PROJ.APP.models.\nThe error wasn't giving any indication of which file was causing the problem. Once I changed all of them it was fine. Thanks, guys.\n"
] | [
0
] | [] | [] | [
"django",
"django_urls",
"python"
] | stackoverflow_0003386654_django_django_urls_python.txt |
Q:
How to mimic Python set with django ORM?
I am working on a membership application. I would like to make a membership reminder. (member during a period of time which is not member for another period of time).
Currently, I am using set for making this calculation. See the code below.
class Member(models.Model):
...
class Membership(models.Model):
member = models.ForeignKey(Member, verbose_name=_("Member"))
start_date = models.DateField(_("Start date"))
end_date = models.DateField(_("End date"))
x = Member.objects.filter(Q(membership__start_date__lte=dt1) & Q(membership__end_date__gte=dt1))
y = Member.objects.filter(Q(membership__start_date__lte=dt2) & Q(membership__end_date__gte=dt2))
result = set(x) - set(y)
I would like to know of I can do it only by using the django ORM (filter, exclude, annotate, distinct ...)?
Thanks in advance for your help
UPDATE
In fact, my model is a bit more complex. I also have newspaper foreign key.
class Member(models.Model):
...
class Newspaper(models.Model):
...
class Membership(models.Model):
member = models.ForeignKey(Member, verbose_name=_("Member"))
start_date = models.DateField(_("Start date"))
end_date = models.DateField(_("End date"))
newspaper = models.ForeignKey(Newspaper)
I want to have the reminder for a given newspaper. In this case, the working query is
sin = models.Membership.objects.filter(start_date__lte=dt1,
end_date__gte=dt1,
newspaper__id=2)
sout = models.Membership.objects.filter(start_date__lte=dt2,
end_date__gte=dt2,
newspaper__id=2)
result = models.Member.objects.filter(membership__in=sin).exclude(membership__in=sout)
I think that this a more verbose version of the answer given Ghislain Leveque which is also working well for me.
Thanks to S.Lott and KillianDS for very valuable answers and sorry for not so clear question :)
A:
Isn't it simply negating the second expression and putting it in the same filter? So you have something like !(a&b), which equals to (!a)|(!b), in this case:
result = Member.objects.filter(membership__start_date__lte=dt1, membership__end_date__gte=dt1, ~Q(membership__start_date__lte=dt2) | ~Q(membership__end_date__gte=dt2))
note by the way that for simple anding and basic lookups you need no Q objects, like I showed with the first two lookup parameters. Anding happens just by passing multiple arguments, Q objects are needed for negating and OR'ing lookups.
A:
A relational database table is a set -- by definition. Set - is where not exists in SQL, which is exclude in Django's ORM.
It seems (without testing) that you're doing this.
result = Member.objects.filter(
Q(membership__start_date__lte=dt1) & Q(membership__end_date__gte=dt1)
).exclude(
Q(membership__start_date__lte=dt2) & Q(membership__end_date__gte=dt2)
)
A:
You should try :
result = Member.objects.\
filter(
membership__start_date__lte = dt1,
membership__end_date__gte=dt1).\
exclude(
pk__in = \
Member.objects.filter(
membership__start_date__lte = dt2,
membership__end_date__gte = dt2).\
values_list('pk')
| How to mimic Python set with django ORM? | I am working on a membership application. I would like to make a membership reminder. (member during a period of time which is not member for another period of time).
Currently, I am using set for making this calculation. See the code below.
class Member(models.Model):
...
class Membership(models.Model):
member = models.ForeignKey(Member, verbose_name=_("Member"))
start_date = models.DateField(_("Start date"))
end_date = models.DateField(_("End date"))
x = Member.objects.filter(Q(membership__start_date__lte=dt1) & Q(membership__end_date__gte=dt1))
y = Member.objects.filter(Q(membership__start_date__lte=dt2) & Q(membership__end_date__gte=dt2))
result = set(x) - set(y)
I would like to know of I can do it only by using the django ORM (filter, exclude, annotate, distinct ...)?
Thanks in advance for your help
UPDATE
In fact, my model is a bit more complex. I also have newspaper foreign key.
class Member(models.Model):
...
class Newspaper(models.Model):
...
class Membership(models.Model):
member = models.ForeignKey(Member, verbose_name=_("Member"))
start_date = models.DateField(_("Start date"))
end_date = models.DateField(_("End date"))
newspaper = models.ForeignKey(Newspaper)
I want to have the reminder for a given newspaper. In this case, the working query is
sin = models.Membership.objects.filter(start_date__lte=dt1,
end_date__gte=dt1,
newspaper__id=2)
sout = models.Membership.objects.filter(start_date__lte=dt2,
end_date__gte=dt2,
newspaper__id=2)
result = models.Member.objects.filter(membership__in=sin).exclude(membership__in=sout)
I think that this a more verbose version of the answer given Ghislain Leveque which is also working well for me.
Thanks to S.Lott and KillianDS for very valuable answers and sorry for not so clear question :)
| [
"Isn't it simply negating the second expression and putting it in the same filter? So you have something like !(a&b), which equals to (!a)|(!b), in this case:\nresult = Member.objects.filter(membership__start_date__lte=dt1, membership__end_date__gte=dt1, ~Q(membership__start_date__lte=dt2) | ~Q(membership__end_date... | [
6,
3,
1
] | [] | [] | [
"django",
"django_orm",
"python"
] | stackoverflow_0003386599_django_django_orm_python.txt |
Q:
In Sqlalchemy, if i add an object using session.add() and flush it, session.query() does not give that object, why?
While using SQLAlchemy, i add a object to a session using session.add(objname), then either explicitly flush it using session.flush or enable autoflush=True while creating the engine itself.
Now in the session, if want to return that object via session.query(classname).all(), i cannot retrieve it.
Why is that so? or is there a way in which query() can also retrieve flushed objects.
A:
I can't reproduce your issue. Please provide sample code that I can run to reproduce it.
Here's code that does what you describe, but behaves as one would expect:
from sqlalchemy import Column, Integer, Unicode, create_engine
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite://')
Base = declarative_base(bind=engine)
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(Unicode(60))
Base.metadata.create_all()
After that setup, Add a new user:
s = create_session(autocommit=False, autoflush=False)
u = User()
u.name = u'Cheezo'
s.add(u)
s.flush()
Then query it back:
>>> u2 = s.query(User).first()
>>> print u2.name
Cheezo
>>> u2 is u
True
| In Sqlalchemy, if i add an object using session.add() and flush it, session.query() does not give that object, why? | While using SQLAlchemy, i add a object to a session using session.add(objname), then either explicitly flush it using session.flush or enable autoflush=True while creating the engine itself.
Now in the session, if want to return that object via session.query(classname).all(), i cannot retrieve it.
Why is that so? or is there a way in which query() can also retrieve flushed objects.
| [
"I can't reproduce your issue. Please provide sample code that I can run to reproduce it.\nHere's code that does what you describe, but behaves as one would expect:\nfrom sqlalchemy import Column, Integer, Unicode, create_engine\nfrom sqlalchemy.orm import create_session\nfrom sqlalchemy.ext.declarative import decl... | [
7
] | [] | [] | [
"orm",
"python",
"sql",
"sqlalchemy"
] | stackoverflow_0003386572_orm_python_sql_sqlalchemy.txt |
Q:
Made Django's auth track on emails, how to relate username field to email?
My original though was to simply put the email address into both username and email fields when creating accounts, this doesn't work as Django limits the username field to 30 characters which may not be enough for email addresses.
My second thought was to md5 the email address, put the hash into username, and that would make it always unique (and technically, identical to the email field as well). md5 is 32 characters, again I only have 30 characters to work with.
My third thought was to chop the last two characters off the end of the md5 hash, making it 30 and then using it as I had planned to use it with the full hash. But I don't know what the chances are of ending up with two hashes that are identical up to the 30th character and only differing at 31 and 32, which I've chopped off.
Is there a better way to relate the contents of the username field to the email address, in a way that will make it always unique?
A:
We developed a django application, which stores emails as usernames. Django builtin username model is restricted to 30 chars, which was good for 90%.
To support longer usernames, without altering the django source, we used a tiny additional application, called longer_username:
from django.db.models.signals import class_prepared
def longer_username(sender, *args, **kwargs):
# You can't just do `if sender == django.contrib.auth.models.User`
# because you would have to import the model
# You have to test using __name__ and __module__
if sender.__name__ == "User" and sender.__module__ == \
"django.contrib.auth.models":
sender._meta.get_field("username").max_length = 75
class_prepared.connect(longer_username)
We added this as the first application into INSTALLED_APPS:
INSTALLED_APPS = (
'longer_username',
...
)
That's it. More information can be found here:
Can django's auth_user.username be varchar(75)? How could that be done?
| Made Django's auth track on emails, how to relate username field to email? | My original though was to simply put the email address into both username and email fields when creating accounts, this doesn't work as Django limits the username field to 30 characters which may not be enough for email addresses.
My second thought was to md5 the email address, put the hash into username, and that would make it always unique (and technically, identical to the email field as well). md5 is 32 characters, again I only have 30 characters to work with.
My third thought was to chop the last two characters off the end of the md5 hash, making it 30 and then using it as I had planned to use it with the full hash. But I don't know what the chances are of ending up with two hashes that are identical up to the 30th character and only differing at 31 and 32, which I've chopped off.
Is there a better way to relate the contents of the username field to the email address, in a way that will make it always unique?
| [
"We developed a django application, which stores emails as usernames. Django builtin username model is restricted to 30 chars, which was good for 90%. \nTo support longer usernames, without altering the django source, we used a tiny additional application, called longer_username:\nfrom django.db.models.signals impo... | [
4
] | [] | [] | [
"authentication",
"database",
"django",
"python"
] | stackoverflow_0003385944_authentication_database_django_python.txt |
Q:
How to bundle a Gnome applet with distutils?
I'm trying to write a Gnome applet in Python. In fact, I've written the app and I'm stuck when it comes to packaging it.
I started by looking into distutils. The problem I ran into right away was that when specifying py_modules, an extension of .py is expected. However, Gnome applets are basically shell scripts. (That use the Python interpreter, of course.)
Here is what I tried... but it isn't working.
from distutils.core import setup
setup(name='myapp',
version='1.2',
py_modules=['myapp'],
)
Also, the myapp file has to get put in /usr/lib/myapp/. As far as I know, distutils puts the files in with the other modules.
How should I go about doing this?
A:
Scripts should be installed with the script option to distutils.core.setup() as described in distutils documentation. On the other hand, py_modules is used to list individual modules, and they must have .py extension as you described.
Also, if you want to add additional files, the data_files option lets you specify both source and destination of the files.
Answer summary: Read whole distutils documentation.
| How to bundle a Gnome applet with distutils? | I'm trying to write a Gnome applet in Python. In fact, I've written the app and I'm stuck when it comes to packaging it.
I started by looking into distutils. The problem I ran into right away was that when specifying py_modules, an extension of .py is expected. However, Gnome applets are basically shell scripts. (That use the Python interpreter, of course.)
Here is what I tried... but it isn't working.
from distutils.core import setup
setup(name='myapp',
version='1.2',
py_modules=['myapp'],
)
Also, the myapp file has to get put in /usr/lib/myapp/. As far as I know, distutils puts the files in with the other modules.
How should I go about doing this?
| [
"Scripts should be installed with the script option to distutils.core.setup() as described in distutils documentation. On the other hand, py_modules is used to list individual modules, and they must have .py extension as you described.\nAlso, if you want to add additional files, the data_files option lets you speci... | [
0
] | [] | [] | [
"applet",
"distutils",
"gnome",
"python"
] | stackoverflow_0003384012_applet_distutils_gnome_python.txt |
Q:
Using Python to send/receive text from GUI program
I'm using PyWin32's win32process.CreateProcess to start up a GUI program that has functionality I want to use in a Python class.
I want to do the following from Python with this GUI:
sent text to individual windows within the GUI (which seem to change identifiers every time I create the process if WinSpy++ is to be believed),
click buttons on the GUI to configure and initiate the calculation, and
retrieve calculation output from the GUI (which allows for either in-GUI text output or save-file output).
Quick question: what Python/PyWin32 functionality should I be researching to accomplish these tasks? I'm not looking for actual code, just the area I should research to learn how to do these things myself. I've scanned most of Learning Python, Programming Python, and Python Programming on Win32 and don't recognize the answer if it's there.
Thanks,
Mike
A:
What you want to do is complicated and I'm not sure you can accomplish that with Python. I can only post some pointers, but can't guarantee that it's right direction.
As for sending text to individual windows - there is SendMessage function - you'd probably need to send your data as keystroke messages to desired window. As for hWnd argument that SendMessage takes - you should be able to obtain it by calling EnumChildWindows function or similar.
Retrieving output is even harder - I think you need to replace WndProc of target window with one that will save output for you while it's being printed. You can substitute WndProc with SetWindowLong (probably).
It should be possible that way, but personally I'd do anything to avoid coding something like that.
One more thing - it's not exactly python related question. Try to find C/C++ code accomplishing something similar with Win32API and try to translate it to Python. Search SO for WinAPI resources. If you're desperate enough, that is...
| Using Python to send/receive text from GUI program | I'm using PyWin32's win32process.CreateProcess to start up a GUI program that has functionality I want to use in a Python class.
I want to do the following from Python with this GUI:
sent text to individual windows within the GUI (which seem to change identifiers every time I create the process if WinSpy++ is to be believed),
click buttons on the GUI to configure and initiate the calculation, and
retrieve calculation output from the GUI (which allows for either in-GUI text output or save-file output).
Quick question: what Python/PyWin32 functionality should I be researching to accomplish these tasks? I'm not looking for actual code, just the area I should research to learn how to do these things myself. I've scanned most of Learning Python, Programming Python, and Python Programming on Win32 and don't recognize the answer if it's there.
Thanks,
Mike
| [
"What you want to do is complicated and I'm not sure you can accomplish that with Python. I can only post some pointers, but can't guarantee that it's right direction.\nAs for sending text to individual windows - there is SendMessage function - you'd probably need to send your data as keystroke messages to desired ... | [
1
] | [] | [] | [
"python",
"pywin32",
"windows"
] | stackoverflow_0003387263_python_pywin32_windows.txt |
Q:
Writing blob from SQLite to file using Python
A clueless Python newbie needs help. I muddled through creating a simple script that inserts a binary file into a blog field in a SQLite database:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
input_note = raw_input(_(u'Note: '))
input_type = 'A'
input_file = raw_input(_(u'Enter path to file: '))
with open(input_file, 'rb') as f:
ablob = f.read()
f.close()
cursor.execute("INSERT INTO notes (note, file) VALUES('"+input_note+"', ?)", [buffer(ablob)])
conn.commit()
conn.close()
Now I need to write a script that grabs the contents of the blob field of a specific record and writes the binary blob to a file. In my case, I use the SQLite database to store .odt documents, so I want to grab and save them as .odt files. How do I go about that? Thanks!
A:
Here's a script that does read a file, put it in the database, read it from database and then write it to another file:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
with open("...", "rb") as input_file:
ablob = input_file.read()
cursor.execute("INSERT INTO notes (id, file) VALUES(0, ?)", [sqlite3.Binary(ablob)])
conn.commit()
with open("Output.bin", "wb") as output_file:
cursor.execute("SELECT file FROM notes WHERE id = 0")
ablob = cursor.fetchone()
output_file.write(ablob[0])
cursor.close()
conn.close()
I tested it with an xml and a pdf and it worked perfectly. Try it with your odt file and see if it works.
| Writing blob from SQLite to file using Python | A clueless Python newbie needs help. I muddled through creating a simple script that inserts a binary file into a blog field in a SQLite database:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
input_note = raw_input(_(u'Note: '))
input_type = 'A'
input_file = raw_input(_(u'Enter path to file: '))
with open(input_file, 'rb') as f:
ablob = f.read()
f.close()
cursor.execute("INSERT INTO notes (note, file) VALUES('"+input_note+"', ?)", [buffer(ablob)])
conn.commit()
conn.close()
Now I need to write a script that grabs the contents of the blob field of a specific record and writes the binary blob to a file. In my case, I use the SQLite database to store .odt documents, so I want to grab and save them as .odt files. How do I go about that? Thanks!
| [
"Here's a script that does read a file, put it in the database, read it from database and then write it to another file:\nimport sqlite3\nconn = sqlite3.connect('database.db')\ncursor = conn.cursor()\n\nwith open(\"...\", \"rb\") as input_file:\n ablob = input_file.read()\n cursor.execute(\"INSERT INTO notes ... | [
37
] | [] | [] | [
"binary",
"blob",
"python",
"sql",
"sqlite"
] | stackoverflow_0003379166_binary_blob_python_sql_sqlite.txt |
Q:
How do I use context_instance in my template
Django newbie here, I'm using
render_to_response('example.html', {
'error_message': error_message,
}, context_instance=RequestContext(request))
How do I use the request in the template? (e.g. the request.host etc.)
A:
The whole point of the context processors is that they automatically add the elements to the context. So you can just use {{ request.host }} or whatever directly in the template.
Edit after comment No, this has nothing to do with generic views. Generic views act in exactly the same way as your own views that use RequestContext as you show above. If you want to make the request object available automatically in your views all you need to do is to add the code below to your settings.py - hard to see how this could be any quicker.
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.contrib.messages.context_processors.messages",
"django.core.context_processors.request"
)
(This is just the default list of context processors as described in the docs, with the request one added.)
| How do I use context_instance in my template | Django newbie here, I'm using
render_to_response('example.html', {
'error_message': error_message,
}, context_instance=RequestContext(request))
How do I use the request in the template? (e.g. the request.host etc.)
| [
"The whole point of the context processors is that they automatically add the elements to the context. So you can just use {{ request.host }} or whatever directly in the template.\nEdit after comment No, this has nothing to do with generic views. Generic views act in exactly the same way as your own views that use ... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003387636_django_python.txt |
Q:
How to convince boss to substitute Java/Netbeans Platform for Python/PyQt?
I'm working for small company, which operates in the automation industry.
The boss hired me because he wants to sell/give some desktop applications to his
current costumers.
He imposes me to use the Netbeans Platform (a generic desktop application framework).
A software engineer friend of his advised him to choose this framework.
At the moment I created 3 desktop applications with Netbeans Platform.
I like Netbeans Platfom. I really take advantage of modularity, Window System and Lookup.
Unfortunately I'm frustrated to known that I can do the same works with Python and PyQt in a fraction of time.
I've already illustrated to my boss the main advantages of Python, but he doesn't like the
idea to use a language that he never heared of it.
I'm the only programmer who codes desktop applications. And except the framework imposition, I'm free to use whatever I want.
I'm looking for good motivations to convince him to leave Netbeans Platform for Python/PyQt.
P.S: My english is bad, sorry.
A:
If your selling skills are not working in discussion format I highly suggest that you document it. Some managers/bosses really respond well to this.
Make a matrix of all the metrics that you yourself use to grade the two frameworks (I leave the level of objectivity to you there: for example if objective it should analyze the cost of transition and the loss of institutional experience; but it might not be high).
Finally, send it by e-mail and viola you have:
made a report/analysis of the situation providing options for improvement
this shows that you are thinking towards future and that you show initiative
EDIT:
You can also ask your boss to show your analysis to his friend if he trust his friend that much, but ask for a written counter-analysis so that you can address the critique.
It is a good thing to do it openly and document the decision process well, since ultimately, if your suggestion is accepted, you will share responsibility for the decision.
A:
The problem is that development time is usually nothing compared to maintenance. Who cares if it takes two days instead of four if the app has a 1-5 year lifetime?
You'll have to convince him that if you get hit by a truck or leave the company (perhaps to work for somebody who uses Python exclusively) that he won't be left in the lurch with a bunch of applications that nobody else knows and can't maintain or upgrade.
A:
The basic problem here is that your non-technical boss is getting conflicting advice from you and from the friend who advised him in the first place. If you want him to take your advice seriously you need to prove that your advice is likely to be trustworthy. And that will only come with taking the lead and being successful with significant projects in the company. Right now, you haven't earned his confidence.
The other thing to consider is how your preferences mesh with the company's objectives. For instance, you want to be able to write code fast. But the boss / the company needs code that is going to be reliable and maintainable ... if you decide to take another position. He doesn't want to be left in the awkward situation where the company is contractually committed to deliver code that doesn't really work properly, and the only person who understands it has left.
A:
First, results speak for themselves: if you can piece together another version of one of your applications in pyqt, and tell him how long it took, it might be motivation enough.
Or, next time you're starting a project, you could prototype four or five different versions of the interface in pyqt in the morning, ask his feedback after lunch, and then say, "if I keep going on these, it'll be done in two days; if I redo this in netbeans, it'll be done in four."
And as for the "never heard of it", feel free to point out that Google uses python extensively, and even hired many of the python developers.
A:
Some people will tell you to try to convince your boss verbally. Others will tell you to document the time savings you think you can make. My opinion is that you just go ahead and do it. Do it in your own time if you strongly believe its in your best interests.
I'm yet to meet a software manager who turned down a working piece of software when it comes in on time and under budget. This is by far the best method of persuasion I've used in my career. Its also a great way to show you have initiative. Just be prepared to work for free if it doesnt work out.
A:
Have you emphasised the point of the lower development time. Any person that doesn't want a shorter turn around time is an idiot. This is the only main issue i can think for the change. Or what you could do is develop it on the side and when you have errors say this is what i have been doing in my spare time(have a working copy written in python).
A:
Perhaphs showing him
a)Time spent in developing in Python and Java
b)lines of code in Python and Java
with these two metrics maybe you can make your case stronger
A:
I would guess a lot, in terms of risk management, would depend on the separation/isolation of the various softwares you develop, and their life cycle.
If you don't need to further a central set of libraries, or have (or can develop) Python bindings for those, and the projects are relatively self contained, say a turn around of two to six months, you could give him a quote for a project in Java that is reasonable and he's familiar with (to make sure it doesn't appear artificially inflated). Then give a much reduced quote for the same in py+pyQt, and see if you can get him to invest on your advice.
Without tangible evidence coming from inside that a change in route will bring benefit the more management and economics savvy people who are technically ignorant will not buy into a new platform when the old one never prevented from realizing and selling.
Without a decent assessment of why he doesn't want to switch platform and what he considers risks it's kinda hard to give more pertinent advice.
A:
Just use Netbeans as an IDE and he'll never notice :P
Speaking more seriously: a side by side comparison of strong and weak points behind each of technologies will certianly be more convincing. Just don't cheat too much in favor of Python ;)
| How to convince boss to substitute Java/Netbeans Platform for Python/PyQt? | I'm working for small company, which operates in the automation industry.
The boss hired me because he wants to sell/give some desktop applications to his
current costumers.
He imposes me to use the Netbeans Platform (a generic desktop application framework).
A software engineer friend of his advised him to choose this framework.
At the moment I created 3 desktop applications with Netbeans Platform.
I like Netbeans Platfom. I really take advantage of modularity, Window System and Lookup.
Unfortunately I'm frustrated to known that I can do the same works with Python and PyQt in a fraction of time.
I've already illustrated to my boss the main advantages of Python, but he doesn't like the
idea to use a language that he never heared of it.
I'm the only programmer who codes desktop applications. And except the framework imposition, I'm free to use whatever I want.
I'm looking for good motivations to convince him to leave Netbeans Platform for Python/PyQt.
P.S: My english is bad, sorry.
| [
"If your selling skills are not working in discussion format I highly suggest that you document it. Some managers/bosses really respond well to this.\nMake a matrix of all the metrics that you yourself use to grade the two frameworks (I leave the level of objectivity to you there: for example if objective it should... | [
12,
8,
5,
3,
2,
1,
1,
1,
0
] | [] | [] | [
"java",
"netbeans",
"pyqt",
"python"
] | stackoverflow_0003386377_java_netbeans_pyqt_python.txt |
Q:
How can I fetch emails via POP or IMAP through a proxy?
Neither poplib or imaplib seem to offer proxy support and I couldn't find much info about it despite my google-fu attempts.
I'm using python to fetch emails from various imap/pop enabled servers and need to be able to do it through proxies.
Ideally, I'd like to be able to do it in python directly but using a wrapper (external program/script, OSX based) to force all traffic to go through the proxy might be enough if I can't find anything better.
Could anyone give me a hand? I can't imagine I'm the only one who ever needed to fetch emails through a proxy in python...
** EDIT Title edit to remove HTTP, because I shouldn't type so fast when I'm tired, sorry for that guys **
The proxies I'm planning to use allow socks in addition to http.
Pop or Imap work through http wouldn't make much sense (stateful vs stateless) but my understanding is that socks would allow me to do what I want.
So far the only way to achieve what I want seems to be dirty hacking of imaplib... would rather avoid it if I can.
A:
You don't need to dirtily hack imaplib. You could try using the SocksiPy package, which supports socks4, socks5 and http proxy (connect):
Something like this, obviously you'd want to handle the setproxy options better, via extra arguments to a custom __init__ method, etc.
from imaplib import IMAP4, IMAP4_SSL, IMAP4_PORT, IMAP4_SSL_PORT
from socks import sockssocket, PROXY_TYPE_SOCKS4, PROXY_TYPE_SOCKS5, PROXY_TYPE_HTTP
class SocksIMAP4(IMAP4):
def open(self,host,port=IMAP4_PORT):
self.host = host
self.port = port
self.sock = sockssocket()
self.sock.setproxy(PROXY_TYPE_SOCKS5,'socks.example.com')
self.sock.connect((host,port))
self.file = self.sock.makefile('rb')
You could do similar with IMAP4_SSL. Just take care to wrap it into an ssl socket
import ssl
class SocksIMAP4SSL(IMAP4_SSL):
def open(self, host, port=IMAP4_SSL_PORT):
self.host = host
self.port = port
#actual privoxy default setting, but as said, you may want to parameterize it
self.sock = create_connection((host, port), PROXY_TYPE_HTTP, "127.0.0.1", 8118)
self.sslobj = ssl.wrap_socket(self.sock, self.keyfile, self.certfile)
self.file = self.sslobj.makefile('rb')
A:
Answer to my own question...
There's a quick and dirty way to force trafic from a python script to go through a proxy without hassle using Socksipy (thanks MattH for pointing me that way)
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS4,proxy_ip,port,True)
socket.socket = socks.socksocket
That global socket override is obviously a bit brutal, but works as a quick fix till I find the time to properly subclass IMAP4 and IMAP4_SSL.
A:
If I understand you correctly you're trying to put a square peg in a round hole.
An HTTP Proxy only knows how to "talk" HTTP so can't connect to a POP or IMAP server directly.
If you want to do this you'll need to implement your own server somewhere to talk to the mail servers. It would receive HTTP Requests and then make the appropriate calls to the Mail Server. E.g.:
How practical this would be I don't know since you'd have to convert a stateful protocol into a stateless one.
| How can I fetch emails via POP or IMAP through a proxy? | Neither poplib or imaplib seem to offer proxy support and I couldn't find much info about it despite my google-fu attempts.
I'm using python to fetch emails from various imap/pop enabled servers and need to be able to do it through proxies.
Ideally, I'd like to be able to do it in python directly but using a wrapper (external program/script, OSX based) to force all traffic to go through the proxy might be enough if I can't find anything better.
Could anyone give me a hand? I can't imagine I'm the only one who ever needed to fetch emails through a proxy in python...
** EDIT Title edit to remove HTTP, because I shouldn't type so fast when I'm tired, sorry for that guys **
The proxies I'm planning to use allow socks in addition to http.
Pop or Imap work through http wouldn't make much sense (stateful vs stateless) but my understanding is that socks would allow me to do what I want.
So far the only way to achieve what I want seems to be dirty hacking of imaplib... would rather avoid it if I can.
| [
"You don't need to dirtily hack imaplib. You could try using the SocksiPy package, which supports socks4, socks5 and http proxy (connect):\nSomething like this, obviously you'd want to handle the setproxy options better, via extra arguments to a custom __init__ method, etc. \nfrom imaplib import IMAP4, IMAP4_SSL, I... | [
14,
7,
2
] | [] | [] | [
"imap",
"pop3",
"proxy",
"python"
] | stackoverflow_0003386724_imap_pop3_proxy_python.txt |
Q:
Library for electrical network simulation
I'm searching for a free and open source library for electrical network simulation.
In (Per preference order) : Python, Ruby, Javascript, PHP, C++ (with Qt if it exist) or bash (ahah).
Do you know one ?
A:
http://www.thedigitalmachine.net/eispice.html
| Library for electrical network simulation | I'm searching for a free and open source library for electrical network simulation.
In (Per preference order) : Python, Ruby, Javascript, PHP, C++ (with Qt if it exist) or bash (ahah).
Do you know one ?
| [
"http://www.thedigitalmachine.net/eispice.html\n"
] | [
3
] | [] | [] | [
"c++",
"python",
"ruby",
"simulation"
] | stackoverflow_0003387913_c++_python_ruby_simulation.txt |
Q:
How to do a group by/count(*) pr year, month and day in django based on a datetime database field?
I have a table describing files with a datetime field. I want to somehow create a report that gives me the number of files grouped by each year, number of files grouped by each year and month and number of files grouped by each year, month and day. I just want records where count(*) > 0. Preferably using the ORM in django or if that`s not possible, using some SQL that runs on both PostgreSQL and SQLite.
The number of records in this database can be huge so my attempts to do this in code, not in SQL ( or indirectly in SQL thru ORM ) don't work and if I get it to work I don`t think it will scale at all.
Grateful for any hints or solutions.
A:
Normally I work on Oracle but a quick google search showed that this should also work for Postgres. For the minutes you could do like this
select to_char(yourtimestamp,'yyyymmdd hh24:mi'), count(*)
from yourtable
group by to_char(yourtimestamp,'yyyymmdd hh24:mi')
order by to_char(yourtimestamp,'yyyymmdd hh24:mi') DESC;
That works then all the way down to years:
select to_char(yourtimestamp,'yyyy'), count(*)
from yourtable
group by to_char(yourtimestamp,'yyyy')
order by to_char(yourtimestamp,'yyyy') DESC;
You are only getting the years where you got something. I think that is what you wanted.
Edit: You need to build an index on "yourtimestamp" otherwise the performance is ugly if you do have a lot of rows.
A:
My mistake - the date() function only works for MySql:
Maybe try this (SQLite):
tbl = MyTable.objects.filter()
tbl = tbl.extra(select={'count':'count(strftime('%Y-%m-%d', timestamp))', 'my_date':'strftime('%Y-%m-%d', timestamp))'}
tbl = tbl.values('count', 'my_date')
tbl.query.group_by = ['strftime('%Y-%m-%d', timestamp)']
For day and month, you could replace '%Y-%m-%d' with variations of the date format strings.
This was for MySQL (just in case someone needs it)
tbl = MyTable.objects.filter()
tbl = tbl.extra(select={'count':'count(date(timestamp))', 'my_date':'date(timestamp)'}
tbl = tbl.values('count', 'my_date')
tbl.query.group_by = ['date(timestamp)']
That works for year.
| How to do a group by/count(*) pr year, month and day in django based on a datetime database field? | I have a table describing files with a datetime field. I want to somehow create a report that gives me the number of files grouped by each year, number of files grouped by each year and month and number of files grouped by each year, month and day. I just want records where count(*) > 0. Preferably using the ORM in django or if that`s not possible, using some SQL that runs on both PostgreSQL and SQLite.
The number of records in this database can be huge so my attempts to do this in code, not in SQL ( or indirectly in SQL thru ORM ) don't work and if I get it to work I don`t think it will scale at all.
Grateful for any hints or solutions.
| [
"Normally I work on Oracle but a quick google search showed that this should also work for Postgres. For the minutes you could do like this\nselect to_char(yourtimestamp,'yyyymmdd hh24:mi'), count(*)\nfrom yourtable\ngroup by to_char(yourtimestamp,'yyyymmdd hh24:mi') \norder by to_char(yourtimestamp,'yyyymmdd hh24:... | [
0,
0
] | [] | [] | [
"aggregate",
"datetime",
"django",
"python",
"sql"
] | stackoverflow_0003387680_aggregate_datetime_django_python_sql.txt |
Q:
Django, Python, Mysql
This is the settings.py file for python. I set mysql up via macports (mysql5 & mysqldb) The problem is that I am unsure if I have settings.py configuration correct before I sync the db. Should the PORT be left blank? I believe it should. I know on my Mamp install I have it set to 3306. Thanks....
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql'
'NAME': 'jenniwren' # Or path to database file if using sqlite3.
'USER': '***' # Not used with sqlite3.
'PASSWORD': '****' # Not used with sqlite3.
'HOST': '/var/run/mysql5/mysqld.sock' # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
update: this is what I am getting when I test the db in the shell..
demetrius-fords-macbook-pro-17:jenniwren demet8$ python manage.py dbshell
Traceback (most recent call last):
File "manage.py", line 4, in
import settings # Assumed to be in the same directory.
File "/Users/demet8/python_projects/jenniwren/settings.py", line 15
'NAME': 'jenniwren' # Or path to database file if using sqlite3.
^
SyntaxError: invalid syntax
A:
3306 is the default, so that should be fine.
Why do you have the host set to that? I haven't used MySQL on a Mac, but on Linux the host is 'localhost'.
The 'invalid syntax' is because you do't have a comma after the host string - wait, after any of the strings but the last one - and that is invalid syntax for Python dictionary.
| Django, Python, Mysql | This is the settings.py file for python. I set mysql up via macports (mysql5 & mysqldb) The problem is that I am unsure if I have settings.py configuration correct before I sync the db. Should the PORT be left blank? I believe it should. I know on my Mamp install I have it set to 3306. Thanks....
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql'
'NAME': 'jenniwren' # Or path to database file if using sqlite3.
'USER': '***' # Not used with sqlite3.
'PASSWORD': '****' # Not used with sqlite3.
'HOST': '/var/run/mysql5/mysqld.sock' # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
update: this is what I am getting when I test the db in the shell..
demetrius-fords-macbook-pro-17:jenniwren demet8$ python manage.py dbshell
Traceback (most recent call last):
File "manage.py", line 4, in
import settings # Assumed to be in the same directory.
File "/Users/demet8/python_projects/jenniwren/settings.py", line 15
'NAME': 'jenniwren' # Or path to database file if using sqlite3.
^
SyntaxError: invalid syntax
| [
"3306 is the default, so that should be fine.\nWhy do you have the host set to that? I haven't used MySQL on a Mac, but on Linux the host is 'localhost'.\nThe 'invalid syntax' is because you do't have a comma after the host string - wait, after any of the strings but the last one - and that is invalid syntax for P... | [
1
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003388071_django_mysql_python.txt |
Q:
ModelAdmin thread-safety/caching issues
Ultimately, my goal is to extend Django's ModelAdmin to provide field-level permissions—that is, given properties of the request object and values of the fields of the object being edited, I would like to control whether or not the fields/inlines are visible to the user. I ultimately accomplished this by adding a can_view_field() method to the ModelAdmin and modifying the built-in get_form() and get_fieldset() methods to remove/exclude fields+inlines that the user does not have permissions (as determined by can_view_field()) to see. If you'd like to see the code, I placed it in a pastebin, since it's long and only somewhat relevant.
It works great...almost. I appear to have run into some sort of thread-safety or caching issue, where the state of the ModelAdmin object is being leaked from one request to another in a reproducible manner.
I'll illustrate the problem with a simple example. Suppose that I have a model whose ModelAdmin I have extended with the field-level permissions code. This model has two fields:
- public_field, which can be seen/edited by any staff member
- secret_field, which can only be seen/edited by superusers
In this case, the can_view_field() method would look like this:
def can_view_field(self, request, obj, field_name):
"""
Returns boolean indicating whether the user has necessary permissions to
view the passed field.
"""
if obj is None:
return request.user.has_perm('%s.%s_%s' % (
self.opts.app_label,
action,
obj.__class__.__name__.lower()
))
else:
if field_name == "public_field":
return True
if field_name == "secret_field" and request.is_superuser:
return True
return False
Test case 1: with a fresh server restart, if you first view the changelist form as a superuser, you see the form as should happen, with both public_field and secret_field visible. If you log out and view it as a staff member (but not superuser), you only see public_field.
Test case 2: with a fresh server restart, if you log in as a staff member first, you still only see public_field. However, if you then log out and view as a superuser, you do not see secret_field. This is 100% reproducible.
I've done some basic thread-safety diagnostics:
At the end of get_form(), I've printed out the memory address of the ModelForm object. As it should be, it is unique with each request. Therefore, the ModelForm object is not the problem.
Immediately before the admin registration, I tried printing the memory address of the ModelAdmin object. In test case 1, it is unique with both requests. However with test case 2, it does not print at all on the second request.
At this point, I'm clueless. My next point of research will be the admin registration system (which I admittedly know nothing about). The state resets with a server restart, so it seems that the ModelAdmin must be cached? Or is it a thread-safety issue? If I turn it into a factory and return a deepcopy() of the ModelAdmin, would it serve a fresh ModelAdmin with each request? I'm clueless and would appreciate any thoughts. Thanks!
A:
I'm confused about why you think ModelAdmin should be a new instance on each request. The admin objects are instantiated by the admin.site.register(Model) calls in each admin.py, which in turn is called from admin.autodiscover() in urls.py. In other words, this happens on process startup. Given the dynamic multi-process nature of most web serving environments, you may or may not get a new process with any particular request - certainly you won't get one every single time.
Because of this, it's not wise to store or alter state on a global object like ModelAdmin. I haven't looked through your linked code properly, but there was at least one case where you were altering an attribute on self as a result of a method call. Don't do that - you'll need to find some other way of passing dynamic values between methods.
| ModelAdmin thread-safety/caching issues | Ultimately, my goal is to extend Django's ModelAdmin to provide field-level permissions—that is, given properties of the request object and values of the fields of the object being edited, I would like to control whether or not the fields/inlines are visible to the user. I ultimately accomplished this by adding a can_view_field() method to the ModelAdmin and modifying the built-in get_form() and get_fieldset() methods to remove/exclude fields+inlines that the user does not have permissions (as determined by can_view_field()) to see. If you'd like to see the code, I placed it in a pastebin, since it's long and only somewhat relevant.
It works great...almost. I appear to have run into some sort of thread-safety or caching issue, where the state of the ModelAdmin object is being leaked from one request to another in a reproducible manner.
I'll illustrate the problem with a simple example. Suppose that I have a model whose ModelAdmin I have extended with the field-level permissions code. This model has two fields:
- public_field, which can be seen/edited by any staff member
- secret_field, which can only be seen/edited by superusers
In this case, the can_view_field() method would look like this:
def can_view_field(self, request, obj, field_name):
"""
Returns boolean indicating whether the user has necessary permissions to
view the passed field.
"""
if obj is None:
return request.user.has_perm('%s.%s_%s' % (
self.opts.app_label,
action,
obj.__class__.__name__.lower()
))
else:
if field_name == "public_field":
return True
if field_name == "secret_field" and request.is_superuser:
return True
return False
Test case 1: with a fresh server restart, if you first view the changelist form as a superuser, you see the form as should happen, with both public_field and secret_field visible. If you log out and view it as a staff member (but not superuser), you only see public_field.
Test case 2: with a fresh server restart, if you log in as a staff member first, you still only see public_field. However, if you then log out and view as a superuser, you do not see secret_field. This is 100% reproducible.
I've done some basic thread-safety diagnostics:
At the end of get_form(), I've printed out the memory address of the ModelForm object. As it should be, it is unique with each request. Therefore, the ModelForm object is not the problem.
Immediately before the admin registration, I tried printing the memory address of the ModelAdmin object. In test case 1, it is unique with both requests. However with test case 2, it does not print at all on the second request.
At this point, I'm clueless. My next point of research will be the admin registration system (which I admittedly know nothing about). The state resets with a server restart, so it seems that the ModelAdmin must be cached? Or is it a thread-safety issue? If I turn it into a factory and return a deepcopy() of the ModelAdmin, would it serve a fresh ModelAdmin with each request? I'm clueless and would appreciate any thoughts. Thanks!
| [
"I'm confused about why you think ModelAdmin should be a new instance on each request. The admin objects are instantiated by the admin.site.register(Model) calls in each admin.py, which in turn is called from admin.autodiscover() in urls.py. In other words, this happens on process startup. Given the dynamic multi-p... | [
3
] | [] | [] | [
"django",
"django_admin",
"django_permissions",
"python"
] | stackoverflow_0003388111_django_django_admin_django_permissions_python.txt |
Q:
Python - difference between os.access and os.path.exists?
def CreateDirectory(pathName):
if not os.access(pathName, os.F_OK):
os.makedirs(pathName)
versus:
def CreateDirectory(pathName):
if not os.path.exists(pathName):
os.makedirs(pathName)
I understand that os.access is a bit more flexible since you can check for RWE attributes as well as path existence, but is there some subtle difference I'm missing here between these two implementations?
A:
Better to just catch the exception rather than try to prevent it. There are a zillion reasons that makedirs can fail
def CreateDirectory(pathName):
try:
os.makedirs(pathName)
except OSError, e:
# could be that the directory already exists
# could be permission error
# could be file system is full
# look at e.errno to determine what went wrong
To answer your question, os.access can test for permission to read or write the file (as the logged in user). os.path.exists simply tells you whether there is something there or not. I expect most people would use os.path.exists to test for the existence of a file as it is easier to remember.
A:
os.access tests if the path can be accessed by the current user
os.path.exists checks if the path does exist. os.access could return False even if the path exists.
| Python - difference between os.access and os.path.exists? | def CreateDirectory(pathName):
if not os.access(pathName, os.F_OK):
os.makedirs(pathName)
versus:
def CreateDirectory(pathName):
if not os.path.exists(pathName):
os.makedirs(pathName)
I understand that os.access is a bit more flexible since you can check for RWE attributes as well as path existence, but is there some subtle difference I'm missing here between these two implementations?
| [
"Better to just catch the exception rather than try to prevent it. There are a zillion reasons that makedirs can fail\ndef CreateDirectory(pathName):\n try:\n os.makedirs(pathName)\n except OSError, e:\n # could be that the directory already exists\n # could be permission error\n #... | [
13,
4
] | [] | [] | [
"module",
"operating_system",
"python"
] | stackoverflow_0003388223_module_operating_system_python.txt |
Q:
logout from command prompt to uploading application on google app
I am uploading google app engine application with the help of appcfg.py command from command prompt in windows.
But after one login I want to upload another application from the same command prompt but i cannot because this second application has no rights with the current login so i want to logout from this session on command prompt so for that what to do? It is a python application
Is there any command to logout from command prompt?
A:
You can run appcfg.py with --no_cookies to tell it not to store authentication cookies, or -e EMAIL to specify an email address that differs from the one in the current cookie.
| logout from command prompt to uploading application on google app | I am uploading google app engine application with the help of appcfg.py command from command prompt in windows.
But after one login I want to upload another application from the same command prompt but i cannot because this second application has no rights with the current login so i want to logout from this session on command prompt so for that what to do? It is a python application
Is there any command to logout from command prompt?
| [
"You can run appcfg.py with --no_cookies to tell it not to store authentication cookies, or -e EMAIL to specify an email address that differs from the one in the current cookie.\n"
] | [
3
] | [] | [] | [
"command_prompt",
"google_app_engine",
"python"
] | stackoverflow_0003387605_command_prompt_google_app_engine_python.txt |
Q:
twitter connection needs to be closed?
i developed an aplication built on twitter api , but i get erorrs like a mesage that i've parsed and deleted to be parsed again at the next execution , could that be because i left the twitter connection opened or is just a fault of the twitter API. I also tried to delete all direct messages because it seemed too full for me but instead the Api has just reset the count of my messages , the messages haven't been deleted:((
A:
Twitter's API is over HTTP, which is a stateless protocol. you don't really need to close the connection, since connections made and closed for each request
| twitter connection needs to be closed? | i developed an aplication built on twitter api , but i get erorrs like a mesage that i've parsed and deleted to be parsed again at the next execution , could that be because i left the twitter connection opened or is just a fault of the twitter API. I also tried to delete all direct messages because it seemed too full for me but instead the Api has just reset the count of my messages , the messages haven't been deleted:((
| [
"Twitter's API is over HTTP, which is a stateless protocol. you don't really need to close the connection, since connections made and closed for each request\n"
] | [
2
] | [] | [] | [
"python",
"twitter"
] | stackoverflow_0003385990_python_twitter.txt |
Q:
Does gzip work on the development server?
Does gzip work on the python development server for appengine? How can I test this in the future?
Note: I've used Firebug to look at my HTTP requests from the browser, and I see that Accept-Encoding is set to "gzip,deflate".
A:
to see if the server responds with gzip encoded headers look for
Content-Encoding:gzip
in the response headers
€: found this in their faq
Google App Engine does its best to serve gzipped content to browsers that support it. Taking advantage of this scheme is automatic and requires no modifications to applications.
We use a combination of request
headers (Accept-Encoding, User-Agent)
and response headers (Content-Type) to
determine whether or not the end-user
can take advantage of gzipped content.
This approach avoids some well-known
bugs with gzipped content in popular
browsers. To force gzipped content to
be served, clients may supply 'gzip'
as the value of both the
Accept-Encoding and User-Agent request
headers. Content will never be gzipped
if no Accept-Encoding header is
present.
| Does gzip work on the development server? | Does gzip work on the python development server for appengine? How can I test this in the future?
Note: I've used Firebug to look at my HTTP requests from the browser, and I see that Accept-Encoding is set to "gzip,deflate".
| [
"to see if the server responds with gzip encoded headers look for \n\nContent-Encoding:gzip\n\nin the response headers\n€: found this in their faq\n\nGoogle App Engine does its best to serve gzipped content to browsers that support it. Taking advantage of this scheme is automatic and requires no modifications to ap... | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003388458_google_app_engine_python.txt |
Q:
Extended call-syntax: Passing parameters
I have a function that looks like this:
def getColumn(self, name, type, **args):
Now I would like to have a function
def getColumns(self, columns)
where I can pass a tuple that contains a tuple, where each entry in that tuple represents the
arguments to be passed go getColumn. However, I'd like not to have to use named parameters for the name and type.
So I'd like not to have to use it like this:
def getColumns(self, columns):
columns = [self.getColumn(**data) for data in columns]
column_data = ( {'name' : 'myName', 'type' : 'myType', 'other' : 'myOther'},
{'name' : 'myName2', 'type' : 'myType2', 'other' : 'myOther2'})
How do I get rid of the 'name': and 'type':?
A:
Something like this?
column_data = (('myName', 'myType', {'other': 'myOther'}),
('myName2', 'myType2', {'other2': 'myOther2'}))
def getColumn(self,name,type,**rest):
pass
def getColumns(self,columns):
return [self.getColumn(name, type, **rest) for name, type, rest in columns]
You don't have to unpack - if you remove ** before restin both places the function will take a dictionary.
If you simply don't want to give names to arguments, use *args instead of **kwargs as gnibbler suggested.
A:
def getColumns(self, columns):
columns = [self.getColumn(*data) for data in columns]
column_data = (('myName', 'myType', 'myOther'),
('myName2', 'myType2', 'myOther2'))
| Extended call-syntax: Passing parameters | I have a function that looks like this:
def getColumn(self, name, type, **args):
Now I would like to have a function
def getColumns(self, columns)
where I can pass a tuple that contains a tuple, where each entry in that tuple represents the
arguments to be passed go getColumn. However, I'd like not to have to use named parameters for the name and type.
So I'd like not to have to use it like this:
def getColumns(self, columns):
columns = [self.getColumn(**data) for data in columns]
column_data = ( {'name' : 'myName', 'type' : 'myType', 'other' : 'myOther'},
{'name' : 'myName2', 'type' : 'myType2', 'other' : 'myOther2'})
How do I get rid of the 'name': and 'type':?
| [
"Something like this?\ncolumn_data = (('myName', 'myType', {'other': 'myOther'}),\n ('myName2', 'myType2', {'other2': 'myOther2'}))\n\ndef getColumn(self,name,type,**rest):\n pass\n\ndef getColumns(self,columns):\n return [self.getColumn(name, type, **rest) for name, type, rest in columns]\n\nYo... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0003388592_python.txt |
Q:
What purpose does a python backend serve?
I am primarily a PHP developer, and I have been browsing the source code of a few open-source applications recently(Mozilla Bespin in particular), to find that some of them use a Python "back-end." I was just wondering what the purpose of this back-end is. I am assuming it is the same thing as the model in an MVC framework and is used to interface with the database, but I'm unsure. If I'm right and the back-end is used to simply interface with the database, is the sqlite/mysql server included in the backend, because I didn't see any database config information in the install directions?
A:
A "Python backend" is simply server-side software written in Python, no different in general terms than server-side software written in PHP. It does all the same things, just with a different programming language.
A:
It looks like Bespin uses Python in the same way it would use PHP, if the autors chose PHP and not Python.
If you are a PHP developer, you already are a "back-end" programmer and you already know what it does, the only difference is the programming language that was used to do that.
Some web sites, mostly the huge ones like Facebook or Twitter, consist of more layers than the usual MVC ones. If you look at Facebook, you can see PHP scripts that generate HTML and AJAX responses as the "front-end" and high-performance databases, storage, computation cluster, application servers etc. as the "back-end" (where PHP is rarely used). So what is considered "front-end" and what "back-end" may also depend on how you look at it.
| What purpose does a python backend serve? | I am primarily a PHP developer, and I have been browsing the source code of a few open-source applications recently(Mozilla Bespin in particular), to find that some of them use a Python "back-end." I was just wondering what the purpose of this back-end is. I am assuming it is the same thing as the model in an MVC framework and is used to interface with the database, but I'm unsure. If I'm right and the back-end is used to simply interface with the database, is the sqlite/mysql server included in the backend, because I didn't see any database config information in the install directions?
| [
"A \"Python backend\" is simply server-side software written in Python, no different in general terms than server-side software written in PHP. It does all the same things, just with a different programming language.\n",
"It looks like Bespin uses Python in the same way it would use PHP, if the autors chose PHP ... | [
2,
1
] | [] | [] | [
"backend",
"php",
"python"
] | stackoverflow_0003388829_backend_php_python.txt |
Q:
pyAA with py2exe
Is anyone able to get pyAA working with py2exe? pyAA can be downloaded here.
I have trying to do this for the last 2 days and I am unable to reach a solution till now. The example files are like given below:
hello.py
import pyAA
print "Hello, World"
setup.py
from distutils.core import setup
import py2exe
setup(console=['hello.py'],
options = {"py2exe": {"bundle_files": 1}})
Now, if we run:
python setup.py py2exe
the executable is created. But running it gives the following error:
Traceback (most recent call last):
File "hello.py", line 1, in ?
File "zipextimporter.pyc", line 82, in load_module
File "pyAA\__init__.pyc", line 1, in ?
File "zipextimporter.pyc", line 82, in load_module
File "pyAA\AA.pyc", line 8, in ?
File "zipextimporter.pyc", line 82, in load_module
File "pyAA\pyAAc.pyc", line 5, in ?
File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd
I tried using dependency walker but I was unable to make too much sense of the same. I tried to add/delete some DLLs but to no avail.
p.s -> Please note that without bundle_files, it is working perfectly. But one of the requirements of the projects mean that bundle_file is required.
A:
This king of thing seems to be a common problem with py2exe. Maybe try using another installer such as PyInstaller.
A:
When I install pyAA and run depends on _pyAAc.pyd, it tells me I'm missing IESHIMS.DLL, though that might be because I'm on Windows 7.
A:
_pyAAc.pyd is a DLL, I think those have to be loaded directly from the file system (not from memory buffers or archives).
If a one-file-solution is needed you could do your own bundling of the working unbundled py2exe result that unpacks itself to TEMP and runs from there. I suspect some self extracting archive maker could do this trick for you without the need for any coding on your part.
A:
Having fought with Py2Exe a few times myself, bundling DLLs with dependencies usually causes headaches. If my memory serves me correctly, try adding sys.exec_prefix to PATH environment variable. This should allow the program to find the IESHIMS.DLL
os.environ['PATH'] = os.sep.join([sys.exec_prefix, os.environ['PATH']])
| pyAA with py2exe | Is anyone able to get pyAA working with py2exe? pyAA can be downloaded here.
I have trying to do this for the last 2 days and I am unable to reach a solution till now. The example files are like given below:
hello.py
import pyAA
print "Hello, World"
setup.py
from distutils.core import setup
import py2exe
setup(console=['hello.py'],
options = {"py2exe": {"bundle_files": 1}})
Now, if we run:
python setup.py py2exe
the executable is created. But running it gives the following error:
Traceback (most recent call last):
File "hello.py", line 1, in ?
File "zipextimporter.pyc", line 82, in load_module
File "pyAA\__init__.pyc", line 1, in ?
File "zipextimporter.pyc", line 82, in load_module
File "pyAA\AA.pyc", line 8, in ?
File "zipextimporter.pyc", line 82, in load_module
File "pyAA\pyAAc.pyc", line 5, in ?
File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pyAA\_pyAAc.pyd
I tried using dependency walker but I was unable to make too much sense of the same. I tried to add/delete some DLLs but to no avail.
p.s -> Please note that without bundle_files, it is working perfectly. But one of the requirements of the projects mean that bundle_file is required.
| [
"This king of thing seems to be a common problem with py2exe. Maybe try using another installer such as PyInstaller.\n",
"When I install pyAA and run depends on _pyAAc.pyd, it tells me I'm missing IESHIMS.DLL, though that might be because I'm on Windows 7.\n",
"_pyAAc.pyd is a DLL, I think those have to be loa... | [
2,
0,
0,
0
] | [] | [] | [
"automation",
"py2exe",
"python"
] | stackoverflow_0003362698_automation_py2exe_python.txt |
Q:
Python class variables or class variables in general
From Dive into Python:
Class attributes are available both through direct reference to the
class and through any instance of the class.
Class attributes can be used as class-level constants, but they are
not really constants. You can also change them.
So I type this into IDLE:
IDLE 2.6.5
>>> class c:
counter=0
>>> c
<class __main__.c at 0xb64cb1dc>
>>> v=c()
>>> v.__class__
<class __main__.c at 0xb64cb1dc>
>>> v.counter += 1
>>> v.counter
1
>>> c.counter
0
>>>
So what am I doing wrong? Why is the class variable not maintaining its value both through direct reference to the class and through any instance of the class.
A:
Because ints are immutable in python
v.counter += 1
rebinds v.counter to a new int object. The rebinding creates an instance attribute that masks the class attribute
You can see this happening if you look at the id() of v.counter
>>> id(v.counter)
149265780
>>> v.counter+=1
>>> id(v.counter)
149265768
Here you can see that v now has a new attribute in its __dict__
>>> v=c()
>>> v.__dict__
{}
>>> v.counter+=1
>>> v.__dict__
{'counter': 1}
Contrast the case where counter is mutable, eg a list
>>> class c:
... counter=[]
...
>>> v=c()
>>> v.counter+=[1]
>>> c.counter
[1]
>>>
A:
Your are confused between declaration and instantiation.
C is the name of a class you declared.
v is an object, instantiated from c.
A:
Before:
c.counter = 0
v.counter -> c.counter
During:
c.counter = 0
v.counter = c.counter + 1
After:
c.counter = 0
v.counter = 1
A:
Note that you can still get at the class value:
v.__class__.__dict__['counter']
will allow you to read or set to your class, even if you have obscured the symbol by adding a symbol to your instance's __dict__.
| Python class variables or class variables in general | From Dive into Python:
Class attributes are available both through direct reference to the
class and through any instance of the class.
Class attributes can be used as class-level constants, but they are
not really constants. You can also change them.
So I type this into IDLE:
IDLE 2.6.5
>>> class c:
counter=0
>>> c
<class __main__.c at 0xb64cb1dc>
>>> v=c()
>>> v.__class__
<class __main__.c at 0xb64cb1dc>
>>> v.counter += 1
>>> v.counter
1
>>> c.counter
0
>>>
So what am I doing wrong? Why is the class variable not maintaining its value both through direct reference to the class and through any instance of the class.
| [
"Because ints are immutable in python\nv.counter += 1\n\nrebinds v.counter to a new int object. The rebinding creates an instance attribute that masks the class attribute\nYou can see this happening if you look at the id() of v.counter\n>>> id(v.counter)\n149265780\n>>> v.counter+=1\n>>> id(v.counter)\n149265768\n\... | [
8,
0,
0,
0
] | [] | [] | [
"oop",
"python"
] | stackoverflow_0003389148_oop_python.txt |
Q:
Importing from module with the same name as executable file in Python
I have an executable file, named, for example, resource.py. It is disposed in the folder named resource. Renaming file or folder is objectionable - it is old product and users accustomed to use such naming. At old version it was under another project, so imports to it sound like import main_product.resource.<..>.
Now I need to use imports like import resource.<..> and __import__('resource.<..>', ...). Then I try it, I get an expected error, because Python try to import from the file resource.py first.
Suggestion solutions:
remove path of current folder from sys.path:
we need an ugly chunk of code at the begin of the file;
no relative imports will be available in this folder;
put folder path at the end sys.path list:
bigger chunk of ugly code at the begin of the file;
i am not sure that this feature will always work perfect.
Have any usable idea about this?
P.S. Python v2.6, FreeBSD 7.3
A:
Use imp.find_module() and imp.load_module()
find_module lets you specify your own path to search
| Importing from module with the same name as executable file in Python | I have an executable file, named, for example, resource.py. It is disposed in the folder named resource. Renaming file or folder is objectionable - it is old product and users accustomed to use such naming. At old version it was under another project, so imports to it sound like import main_product.resource.<..>.
Now I need to use imports like import resource.<..> and __import__('resource.<..>', ...). Then I try it, I get an expected error, because Python try to import from the file resource.py first.
Suggestion solutions:
remove path of current folder from sys.path:
we need an ugly chunk of code at the begin of the file;
no relative imports will be available in this folder;
put folder path at the end sys.path list:
bigger chunk of ugly code at the begin of the file;
i am not sure that this feature will always work perfect.
Have any usable idea about this?
P.S. Python v2.6, FreeBSD 7.3
| [
"Use imp.find_module() and imp.load_module()\nfind_module lets you specify your own path to search\n"
] | [
1
] | [] | [] | [
"import",
"python"
] | stackoverflow_0003389313_import_python.txt |
Q:
Help removing items from a text file using python
After implementing some of the solutions in my previous question, I've come up with the following solution:
reader = open('C://text.txt')
writer = open('C://nona.txt', 'w')
counter = 1
names, nums = [], []
row = reader.read().split(' ')
x = len(row)/2
for (a, b) in [(c, d) for c, d in zip(row[:x], row[x:]) if d!='na']:
print counter
counter +=1
names.append(a)
nums.append(b)
writer.write(' '.join(names))
writer.write(' ')
writer.write(' '.join(nums))
This program works quite well for a smaller sample data set. However it freezes up when I use the full data set and causes python to crash. Any suggestions on how I can overcome this?
A:
What you should do is break your file up into two separate files. Your logic should do something like this:
Open data file
open name file
read next data
is it name? see 5. Otherwise see 6
write name to name file, see 3
is it number or na? close name file and open number file
read next data
is it number or na? see 7, otherwise write file
once you have your files split into two pieces, you can iterate over them together:
names = open('names.txt')
numbers = open('numbers.txt')
for name, number in zip(names, numbers):
if not numbers == 'na':
output.write(name + " " + number)
or you could write to two different files and then join them together if that's what you need.
A:
Your file is organized in an unfortunate manner for Pythonic processing.
Note that when you call reader.read(), you are reading the entire file into memory. Let's say this takes up X bytes.
Calling split will effectively add another X bytes of memory usage, as it will create a new string for each separate string in the file.
Then you call row[:x] and row[x:], which will add ANOTHER X bytes (because the slice operator makes a copy).
Then you call zip, and make a list comprehension, etc, etc. Strings and tuples are immutable data, which means you are always creating them from scratch.
I would approach this problem at a lower level. Open one file descriptor and point it to the beginning of the file. Open another and have it seek to the beginning of the (na/0/1/2) values (you will know where this is by counting the spaces). Now, read one name and one value at a time, and if the value is not "na" you can write the name to an output file. If you need to write the values to the output file also, hold them in memory and write them all at once when you are done.
Unfortunately this will be more difficult to code than just using the high-level functions that Python provides (you will need to write code that operates at the character level), but as you have seen there is a price to pay for those high-level functions.
| Help removing items from a text file using python | After implementing some of the solutions in my previous question, I've come up with the following solution:
reader = open('C://text.txt')
writer = open('C://nona.txt', 'w')
counter = 1
names, nums = [], []
row = reader.read().split(' ')
x = len(row)/2
for (a, b) in [(c, d) for c, d in zip(row[:x], row[x:]) if d!='na']:
print counter
counter +=1
names.append(a)
nums.append(b)
writer.write(' '.join(names))
writer.write(' ')
writer.write(' '.join(nums))
This program works quite well for a smaller sample data set. However it freezes up when I use the full data set and causes python to crash. Any suggestions on how I can overcome this?
| [
"What you should do is break your file up into two separate files. Your logic should do something like this:\n\nOpen data file\nopen name file\nread next data\nis it name? see 5. Otherwise see 6\nwrite name to name file, see 3\nis it number or na? close name file and open number file\nread next data\nis it number o... | [
1,
0
] | [] | [] | [
"memory",
"python"
] | stackoverflow_0003389260_memory_python.txt |
Q:
How to silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output?
I am writing a simple http server as part of my project. Below is a skeleton of my script:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class MyHanlder(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<html><body><p>OK</p></body></html>')
httpd = HTTPServer(('', 8001), MyHanlder)
httpd.serve_forever()
My question: how do I suppress the stderr log output my script produces every time a client connects to my server?
I have looked at the HTTPServer class up to its parent, but was unable to find any flag or function call to achieve this. I also looked at the BaseHTTPRequestHandler class, but could not find a clue. I am sure there must be a way. If you do, please share with me and others; I appreciate your effort.
A:
This will probably do it:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<html><body><p>OK</p></body></html>')
def log_message(self, format, *args):
return
httpd = HTTPServer(('', 8001), MyHandler)
httpd.serve_forever()
| How to silent/quiet HTTPServer and BasicHTTPRequestHandler's stderr output? | I am writing a simple http server as part of my project. Below is a skeleton of my script:
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
class MyHanlder(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write('<html><body><p>OK</p></body></html>')
httpd = HTTPServer(('', 8001), MyHanlder)
httpd.serve_forever()
My question: how do I suppress the stderr log output my script produces every time a client connects to my server?
I have looked at the HTTPServer class up to its parent, but was unable to find any flag or function call to achieve this. I also looked at the BaseHTTPRequestHandler class, but could not find a clue. I am sure there must be a way. If you do, please share with me and others; I appreciate your effort.
| [
"This will probably do it:\nfrom BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler\n\nclass MyHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header('Content-type', 'text/html')\n self.end_headers()\n self.wfile.write('<html><body><p>O... | [
149
] | [] | [] | [
"basehttpserver",
"httpserver",
"python"
] | stackoverflow_0003389305_basehttpserver_httpserver_python.txt |
Q:
Nose: Capture script output as well as test output
If I put any print statements at the top of my module, not inside any class/function, nothing gets printed while running my test through nose.
import os
print 'hi'
#----------------------------------------------------------------------
def make_shapes(canvas):
"""
Generates shapes. Needs a Canvas instance to add the shapes to
"""
params = [canvas, Colour(0, 0, 0), 1]
placing the print inside the function works though. Any ideas?
A:
Not sure if this is the problem, but you can run nosetests with the -s argument to prevent capturing of stdout.
| Nose: Capture script output as well as test output | If I put any print statements at the top of my module, not inside any class/function, nothing gets printed while running my test through nose.
import os
print 'hi'
#----------------------------------------------------------------------
def make_shapes(canvas):
"""
Generates shapes. Needs a Canvas instance to add the shapes to
"""
params = [canvas, Colour(0, 0, 0), 1]
placing the print inside the function works though. Any ideas?
| [
"Not sure if this is the problem, but you can run nosetests with the -s argument to prevent capturing of stdout.\n"
] | [
6
] | [] | [] | [
"nose",
"nosetests",
"python"
] | stackoverflow_0003388981_nose_nosetests_python.txt |
Q:
What's wrong with the "or" in my "if" statement?
I've tried Google, but I can't find the answer to this simple question.
I hate myself for not being able to figure this out, but here we go.
How do I write an if statement with or in it?
For example:
if raw_input=="dog" or "cat" or "small bird":
print "You can have this animal in your house"
else:
print "I'm afraid you can't have this animal in your house."
A:
You can put the allowed animals into a tuple then use in to search for a match
if raw_input() in ("dog", "cat", "small bird"):
print "You can have this animal in your house"
else:
print "I'm afraid you can't have this animal in your house."
You can also use a set here, but I doubt it would improve performance for such a small number of allowed animals
desired_animal = raw_input()
allowed_animals = set(("dog", "cat", "small bird"))
if desired_animal in allowed_animals:
print "You can have this animal in your house"
else:
print "I'm afraid you can't have this animal in your house."
A:
If you want to use or, you need to repeat the whole expression each time:
if raw_input == "dog" or raw_input == "cat" or raw_input == "small bird":
But a better way to do this particular comparison is with in:
if raw_input in ("dog", "cat", "small bird"):
A:
if (raw_input=="dog") or (raw_input == "cat") or (raw_input == "small bird"):
print You can have this animal in your house
else:
print I'm afraid you can't have this animal in your house.
or
if raw_input in ("dog", "cat", "small bird"):
print You can have this animal in your house
else:
print I'm afraid you can't have this animal in your house.
A:
You can do it this way
if raw_input=="dog" or raw_input=="cat" or raw_input=="small bird":
A:
goodanimals= ("dog" ,"cat","small bird")
print("You can have this animal in your house" if raw_input().strip().lower() in goodanimals
else "I'm afraid you can't have this animal in your house.")
| What's wrong with the "or" in my "if" statement? | I've tried Google, but I can't find the answer to this simple question.
I hate myself for not being able to figure this out, but here we go.
How do I write an if statement with or in it?
For example:
if raw_input=="dog" or "cat" or "small bird":
print "You can have this animal in your house"
else:
print "I'm afraid you can't have this animal in your house."
| [
"You can put the allowed animals into a tuple then use in to search for a match\nif raw_input() in (\"dog\", \"cat\", \"small bird\"):\n print \"You can have this animal in your house\"\nelse:\n print \"I'm afraid you can't have this animal in your house.\"\n\nYou can also use a set here, but I doubt it would... | [
17,
11,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003388788_python.txt |
Q:
advice on storing 3rd party modules on my computer
How do you guys go about storing your python modules locally? And how do you then go about referencing them in your python scripts?
Should I do this?
/home/python/modules
And then create a sub-directory for each module, like say the amazon s3 module:
/home/python/modules/amazon-s3/s3.py
Now I have to somehow tell python to look at these folders for modules, which I think is sys.path somehow?
A:
I usually store my modules in /usr/local/lib/python for the whole system, and /home/user/lib/python for the user. That's if they weren't installed via the system package manager. If they were a .deb or .rpm or whatever, they'll probably be placed in /usr/lib/python, as per the FHS standard, which specifies where different types of files should go on a POSIXish operating system.
Set the PYTHONPATH environment variable to have local packages be found by the interpreter.
A:
Should I do this?
No.
Install them in site-packages, just like it says in the documentation.
http://docs.python.org/install/
http://docs.python.org/library/site.html
A:
If you're particularly concerned about managing python modules you'll probably want to look at virtualenv, which lets you setup separate virtual python environments so you can separate out what modules are installed and used.
| advice on storing 3rd party modules on my computer | How do you guys go about storing your python modules locally? And how do you then go about referencing them in your python scripts?
Should I do this?
/home/python/modules
And then create a sub-directory for each module, like say the amazon s3 module:
/home/python/modules/amazon-s3/s3.py
Now I have to somehow tell python to look at these folders for modules, which I think is sys.path somehow?
| [
"I usually store my modules in /usr/local/lib/python for the whole system, and /home/user/lib/python for the user. That's if they weren't installed via the system package manager. If they were a .deb or .rpm or whatever, they'll probably be placed in /usr/lib/python, as per the FHS standard, which specifies where... | [
2,
1,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0003389817_module_python.txt |
Q:
Stop module loading
I'd like to stop the loading of a module if some modules dependencies arent on machine, how can i do that?
try:
import lxml
except:
print "This module requires lxml"
# WHAT SHOULD I PUT HERE TO STOP MODULE LOADING?
class foo:
pass
A:
Raise the exception, or raise a new one:
try:
import lxml
except:
raise SomeError('This module requires lxml')
If you want to stop the interpreter entirely, use exit() to terminate the program.
A:
To stop the whole python interpreter you can use sys.exit()
| Stop module loading | I'd like to stop the loading of a module if some modules dependencies arent on machine, how can i do that?
try:
import lxml
except:
print "This module requires lxml"
# WHAT SHOULD I PUT HERE TO STOP MODULE LOADING?
class foo:
pass
| [
"Raise the exception, or raise a new one:\ntry:\n import lxml\nexcept:\n raise SomeError('This module requires lxml')\n\nIf you want to stop the interpreter entirely, use exit() to terminate the program.\n",
"To stop the whole python interpreter you can use sys.exit()\n"
] | [
1,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0003390299_module_python.txt |
Q:
Reading from file
I am a beginner and just started learning Python couple days ago (yay!)
so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines)
def output():
xf=open("data.txt", "r")
print xf
print("opened, printing now")
for line in xf:
print(xf.read())
print("and\n")
xf.close()
print("closed, done printing")
A:
You don't use line, try:
with open('data.txt') as f:
for line in f:
print line
A:
This should print out each number on its own line, like you want, in a lot less code, and more readable.
def output():
f = open('data.txt', 'r').read()
print f
A:
When you used for line in xf: you basically already iterated over the file, implicitly reading each line.
All you need to do is print it:
for line in xf:
print(line)
A:
The reason you aren't seeing the line output is because you aren't telling it to output the line. While iterating over values of line, you print xf.read(). The following is your function rewritten with this in mind. Also added is the use of a with statment block to automatically close the file when you're done with it.
(Using xf.close() is not wrong, just less pythonic for this example.)
def output():
with open("data.txt", "r") as xf:
print xf
print("opened, printing now")
for line in xf:
print(line)
print("and\n")
print("closed, done printing")
A:
You have read the line of text into the variable line in the code for line in xf: so you need to show that e.g. print(line)
I would look at tutorials like the python.org one
| Reading from file | I am a beginner and just started learning Python couple days ago (yay!)
so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines)
def output():
xf=open("data.txt", "r")
print xf
print("opened, printing now")
for line in xf:
print(xf.read())
print("and\n")
xf.close()
print("closed, done printing")
| [
"You don't use line, try:\nwith open('data.txt') as f:\n for line in f:\n print line\n\n",
"This should print out each number on its own line, like you want, in a lot less code, and more readable.\ndef output():\n f = open('data.txt', 'r').read()\n print f\n\n",
"When you used for line in xf: yo... | [
6,
2,
1,
1,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0003390334_file_io_python.txt |
Q:
Naming practice for objects of a class in Python
I have this weird problem as to how to name objects of a class.
For example, consider the class:
>>> class DoSomething:
pass
What should I call the object of this class? do_something or what? Since I came out of the learning stage, I used to use x, y or z or whatever came to my mind. But now since I am learning to write proper code and not the language, I always face this problem. Any suggestions?
A:
Name it something representative of what it's actually being used for. For instance:
class Cereal:
def eat(self):
print 'yum'
breakfast = Cereal()
breakfast.eat()
or
class User:
def __init__(self, userid):
# ...
admin_user = User(ADMIN_ID)
A:
You should name it after what it represents. For example if I have a class User in a web application and I want to refer to the currently logged-in user, I name the variable current_user.
And if you have more objects of one class, your approach fails immediately. Giving the variable an index like do_something1, do_something2 is not and will never be an option.
Use something meaningful, so that a reader of your code knows what this variable represents.
Btw. this applies to all programming languages, not just Python.
A:
One good naming practise is to give plural names to collections such as sets and lists.
| Naming practice for objects of a class in Python | I have this weird problem as to how to name objects of a class.
For example, consider the class:
>>> class DoSomething:
pass
What should I call the object of this class? do_something or what? Since I came out of the learning stage, I used to use x, y or z or whatever came to my mind. But now since I am learning to write proper code and not the language, I always face this problem. Any suggestions?
| [
"Name it something representative of what it's actually being used for. For instance:\nclass Cereal:\n def eat(self):\n print 'yum'\n\nbreakfast = Cereal()\nbreakfast.eat()\n\nor\nclass User:\n def __init__(self, userid):\n # ...\n\nadmin_user = User(ADMIN_ID)\n\n",
"You should name it after w... | [
4,
2,
0
] | [] | [] | [
"naming_conventions",
"oop",
"python"
] | stackoverflow_0003390220_naming_conventions_oop_python.txt |
Q:
help sorting a dictionary into another dictionary
I have a dictionary (index2) of 3-item lists, organized by key from 0-150 or so. I need to sort it into another dictionary, with the following constraints:
1.) all items attached to one key must stay together in the second dictionary
2.) length of items in the second dictionary must all be the same. To help with this one, I divided the total number of items in the first dictionary by the number of keys in the second and attached it to a variable so it can be used as a limiting factor.
This is what I have so far, however when I run it, it doesn't actually append anything to the target dictionary.
for key,runs in index2.iteritems():
for a in mCESrange:
if index2[key][0] in mCESdict[a]:
pass
elif len(mCESdict[a]) < mCESlength:
pass
else:
mCESdict[a].extend(index2[key])
A:
Your problem description isn't really clear, and non-working code rarely helps to clarify, but I suspect that this line is your problem: elif len(dict[a]) < length.
| help sorting a dictionary into another dictionary | I have a dictionary (index2) of 3-item lists, organized by key from 0-150 or so. I need to sort it into another dictionary, with the following constraints:
1.) all items attached to one key must stay together in the second dictionary
2.) length of items in the second dictionary must all be the same. To help with this one, I divided the total number of items in the first dictionary by the number of keys in the second and attached it to a variable so it can be used as a limiting factor.
This is what I have so far, however when I run it, it doesn't actually append anything to the target dictionary.
for key,runs in index2.iteritems():
for a in mCESrange:
if index2[key][0] in mCESdict[a]:
pass
elif len(mCESdict[a]) < mCESlength:
pass
else:
mCESdict[a].extend(index2[key])
| [
"Your problem description isn't really clear, and non-working code rarely helps to clarify, but I suspect that this line is your problem: elif len(dict[a]) < length.\n"
] | [
0
] | [] | [] | [
"dictionary",
"iteration",
"python"
] | stackoverflow_0003390469_dictionary_iteration_python.txt |
Q:
Python - Hashlib MD5 differs between linux/windows
I have a python app in which I am creating packages in windows to be used and later compared in a linux python app. I am creating an md5 for a file in windows to be checked later in linux. The problem is that the same code on the same file gives different Md5 hash results in each environment. Below is the method I use to calculate the Md5. (It is the same code on each end, and I am using Python 2.6.5 for both windows/linux environments) When I run this on the same file in different environments, I get md5 hashes that do not match.
def md5_for_file(filePath):
md5 = hashlib.md5()
file = open(filePath)
while True:
data = file.read(8192)
if not data:
break
md5.update(data)
file.close()
return md5.hexdigest()
Any ideas or suggestions are appreciated.
A:
Change open(filePath) to open(filePath, 'rb'), where the b is for binary mode. You're currently opening in text mode, which can cause portability issues.
A:
check if the two files use the same encoding and lineendings
| Python - Hashlib MD5 differs between linux/windows | I have a python app in which I am creating packages in windows to be used and later compared in a linux python app. I am creating an md5 for a file in windows to be checked later in linux. The problem is that the same code on the same file gives different Md5 hash results in each environment. Below is the method I use to calculate the Md5. (It is the same code on each end, and I am using Python 2.6.5 for both windows/linux environments) When I run this on the same file in different environments, I get md5 hashes that do not match.
def md5_for_file(filePath):
md5 = hashlib.md5()
file = open(filePath)
while True:
data = file.read(8192)
if not data:
break
md5.update(data)
file.close()
return md5.hexdigest()
Any ideas or suggestions are appreciated.
| [
"Change open(filePath) to open(filePath, 'rb'), where the b is for binary mode. You're currently opening in text mode, which can cause portability issues.\n",
"check if the two files use the same encoding and lineendings\n"
] | [
24,
0
] | [] | [] | [
"python"
] | stackoverflow_0003390484_python.txt |
Q:
Django Error: Unhandled Exception
after running: "python manage.py runserver", I'm getting the error:
Validating models...
Unhandled exception in thread started by <function inner_run at 0xc942a8>
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/base.py", line 245, in validate
num_errors = get_validation_errors(s, app)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home4/usr/.local/lib/python/massivecoupon/paypalxpress/models.py", line 96
self.charged = Decimal(amount) if amount is not None else None
^
SyntaxError: invalid syntax
Anybody have any suggestions as to what I can do to fix?
Thanks!
A:
Sounds like you are running a very old version of Python - versions 2.4 and earlier did not support y if x else z. You should upgrade, if possible, or find a version of the massivecoupon package that is compatible with Python 2.4.
A:
Python's only supported the 'a if b else c' syntax since version 2.5. Are you using an earlier version than that?
If so you could replace line 96 of /home4/usr/.local/lib/python/massivecoupon/paypalxpress/models.py with
self.charged = amount is not None and Decimal(amount) or None
Should work I think.
| Django Error: Unhandled Exception | after running: "python manage.py runserver", I'm getting the error:
Validating models...
Unhandled exception in thread started by <function inner_run at 0xc942a8>
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/commands/runserver.py", line 48, in inner_run
self.validate(display_num_errors=True)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/base.py", line 245, in validate
num_errors = get_validation_errors(s, app)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/core/management/validation.py", line 28, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/db/models/loading.py", line 78, in load_app
models = import_module('.models', app_name)
File "/home4/usr/.local/lib/python/Django-1.2.1-py2.4.egg/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home4/usr/.local/lib/python/massivecoupon/paypalxpress/models.py", line 96
self.charged = Decimal(amount) if amount is not None else None
^
SyntaxError: invalid syntax
Anybody have any suggestions as to what I can do to fix?
Thanks!
| [
"Sounds like you are running a very old version of Python - versions 2.4 and earlier did not support y if x else z. You should upgrade, if possible, or find a version of the massivecoupon package that is compatible with Python 2.4.\n",
"Python's only supported the 'a if b else c' syntax since version 2.5. Are you... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003390722_django_python.txt |
Q:
How do I search a range for a single integer?
My Python code generates a random number between 0 and 35 and stores that number as 'random'. I am looking to compare 'random' against several ranges of numbers to determine which of three groups it falls into and assign another value to 'winning' based on which group 'random' is in. The groups are: 0-16, 16-34, and 34-36. 'winning' always returns 2 though. Here's what I've tried so far.
import random #start python random number generator
random = random.randrange(36) #calls a random number between 0-35 and stores value
print random #test
for random in range(0, 16):
winning = 0
for random in range(16, 34):
winning = 1
for random in range(34, 36):
winning = 45
print winning #test
Thank you in advance for any help that you can give! This is my first time programming with Python.
A:
First of all, please don't name your variable random. It shadows the random module name and you won't be able to use the random module in the rest of scope because of this.
So let's call the result rnd.
You should use if rnd in range(0, 16): ... instead of for. The syntax
for a in list_:
foo(a)
will extract every element in the list_ one by one, assign it to a each time, then call the body. As seen from the for it is a loop. Therefore, you are actually setting winning = 0 17 times, etc.
On the other hand, the syntax
if b in list_:
foo(b)
which can be seen as
if (b in list_):
foo(b)
will check if b is an element of list_, and execute the body if the condition is true (the in is also an operator.)
You shouldn't use in range(...) to check if a number is in a numeric range because searching in a list takes linear time. The Pythonic way is to use the a <= b < c notation:
if 0 <= rnd < 16:
winning = 0
But actually it can be written more simply (no matter which language you use) as
if rnd < 16:
winning = 0
elif rnd < 34:
winning = 1
else:
winning = 45
A:
You should use if instead of for. for is a loop keyword.
if random in range(0, 16):
winning = 0
Actually this is not a great use of range since it will generate a full list of all numbers and then check each number to see if it equals random. It would be more efficient to do some simple comparisons:
if 0 <= random < 16:
winning = 0
# The above is a shorthand syntax for this:
# if 0 <= random and random < 16
A:
One implementation of what I think you want:
def getWinning(number):
ranges = {
0: (0, 16),
1: (16, 34),
45: (34, 36)
}
for key in ranges :
low, high = ranges[key]
if low <= number < high:
return key
A:
Using bisect.bisect is a nice way to replace the if statements:
import random
import bisect
num = random.randrange(36)
print num
grid=(0,16,34,36)
winning=bisect.bisect(grid,num)
winning=45 if winning==2 else winning
print(winning)
PS. Do not call your random number random. Doing so clobbers the module of the same name (making it impossible to call random.randrange, say, a second time). This leads to a potentially hard-to-find bug since the exception (AttributeError) can occur miles away from the true cause of the error.
A:
This is bit advanced code structure, but really not so much complicated.
from random import choice
# Do list weighted by the winning chances
winning=[0]*16+[1]*18+[45]*2
for lottery in range(10):
win = choice(winning)
print("Round %i:\t" % (lottery+1) +
("You won $%i" % win if win
else "No win this time")
)
| How do I search a range for a single integer? | My Python code generates a random number between 0 and 35 and stores that number as 'random'. I am looking to compare 'random' against several ranges of numbers to determine which of three groups it falls into and assign another value to 'winning' based on which group 'random' is in. The groups are: 0-16, 16-34, and 34-36. 'winning' always returns 2 though. Here's what I've tried so far.
import random #start python random number generator
random = random.randrange(36) #calls a random number between 0-35 and stores value
print random #test
for random in range(0, 16):
winning = 0
for random in range(16, 34):
winning = 1
for random in range(34, 36):
winning = 45
print winning #test
Thank you in advance for any help that you can give! This is my first time programming with Python.
| [
"First of all, please don't name your variable random. It shadows the random module name and you won't be able to use the random module in the rest of scope because of this.\nSo let's call the result rnd.\n\nYou should use if rnd in range(0, 16): ... instead of for. The syntax\nfor a in list_:\n foo(a)\n\nwill ext... | [
4,
3,
2,
2,
2
] | [] | [] | [
"python",
"random",
"range"
] | stackoverflow_0003390659_python_random_range.txt |
Q:
when updating an object, what do I call? session.add is for adding, where is update?
http://www.sqlalchemy.org/docs/reference/orm/sessions.html
I don't see anything for updating an object that was just retrieved from the database using:
q = session.query(products)
for p in q:
p.blah = 'hello'
sesion.????
session.commit()
A:
That line p.blah = 'hello' is updating the property (column) blah of the object p.
That's the power of object relational mapping in newer languages. Enjoy.
| when updating an object, what do I call? session.add is for adding, where is update? | http://www.sqlalchemy.org/docs/reference/orm/sessions.html
I don't see anything for updating an object that was just retrieved from the database using:
q = session.query(products)
for p in q:
p.blah = 'hello'
sesion.????
session.commit()
| [
"That line p.blah = 'hello' is updating the property (column) blah of the object p.\nThat's the power of object relational mapping in newer languages. Enjoy.\n"
] | [
4
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0003390915_python_sqlalchemy.txt |
Q:
Python introspection: description of the parameters a function takes
Is there is a tool similar to dir() for modules that will tell me what parameters a given function takes? For instance, I would like to do something like dir(os.rename) and have it tell me what parameters are documented so that I can avoid checking the documentation online, and instead use only the Python scripting interface to do this.
A:
I realize that you're more interested in help(thing) or thing.__doc__, but if you're trying to do programmatic introspection (instead of human-readable documentation) to find out about calling a function, then you can use the inspect module, as discussed in this question.
A:
help(thing) pretty prints all the docstrings that are in the module, method, whatever ...
| Python introspection: description of the parameters a function takes | Is there is a tool similar to dir() for modules that will tell me what parameters a given function takes? For instance, I would like to do something like dir(os.rename) and have it tell me what parameters are documented so that I can avoid checking the documentation online, and instead use only the Python scripting interface to do this.
| [
"I realize that you're more interested in help(thing) or thing.__doc__, but if you're trying to do programmatic introspection (instead of human-readable documentation) to find out about calling a function, then you can use the inspect module, as discussed in this question.\n",
"help(thing) pretty prints all the d... | [
12,
4
] | [] | [] | [
"introspection",
"python"
] | stackoverflow_0003391013_introspection_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.