Why Python.exe is breaking with memory dump??

2008-01-11 Thread abhishek
Hi group i have created a simple .pyd using which i m able call C
function from python code. There are around 6 such functions. 4 of
them work great. But when i try to run other two python's exe breaks
giving memory dump.

Any pros or cons on what led to such a situation.. Is it a problem in
my c code??

Thank you.
-- 
http://mail.python.org/mailman/listinfo/python-list


HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS??

2008-01-11 Thread abhishek
Hi group any idea on HOW  TO HANDLE POINTERS FROM NON-LOCAL HEAPS??


Thank you
-- 
http://mail.python.org/mailman/listinfo/python-list


how to deliver an application

2008-01-11 Thread jimgardener
hi
i have written a program that takes in user input thru a gui and then
does some calculations and then displays a result value.I have split
the code into 3 parts

1.the gui code--mygui.py  containing a class to handle all ui stuff
2.calculations.py (also has one class to do all processing)
3. documenthandler.py contains a class to deal with a specific type of
document(say .doc , may be later i will add other document support
here)

i run my code by calling python mygui.py
and this will call class from calculations.py to do the processing.
calculations.py will in turn call the class and fns of
documenthandler.py when needed

currently i have put all three .py files in one folder and run the
application.I would like to know if this can be packaged  better?
Finally how should i deliver the application? i would like to have
both windows and unix users be able to use my app

any advise most appreciated
jim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Analyzing Python GC output - what is a "cell", and what information is available about it.

2008-01-11 Thread Duncan Booth
John Nagle <[EMAIL PROTECTED]> wrote:

> I'm printing out each entry in "gc.garbage" after a garbage collection in
> DEBUG_LEAK mode, and I'm seeing many entries like
> 
>
> 
> That's the output of "repr".   Are "cell" objects created only from
> external C libraries, or can regular Python code generate them?  Is there
> any way to find out what the 'function object' is from within Python?
> 
Cell objects are created whenever you have a function that references a 
variable in an outer scope. e.g.

>>> def outer():
x = 42
def inner():
return x
return inner

>>> inner = outer()
>>> inner.func_closure[0]

>>> inner.func_closure[0].cell_contents
42


So in your case, cell.cell_contents.func_name might help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS??

2008-01-11 Thread Duncan Booth
abhishek <[EMAIL PROTECTED]> wrote:

> Hi group any idea on HOW  TO HANDLE POINTERS FROM NON-LOCAL HEAPS??
> 
> 
Yes, it indicates you haven't read 
http://catb.org/~esr/faqs/smart-questions.html
-- 
http://mail.python.org/mailman/listinfo/python-list


module finalizer - is there such a beast?

2008-01-11 Thread Helmut Jarausch
Hi,

when a module gets imported the statements not contained in
function definitions or classes are executed.
This can be thought of an initializer for the module.

But how can I get control when the module gets unloaded
either by Python's gc, Python's exit or by a module reload.

Many thanks for a hint,

Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS??

2008-01-11 Thread Gary Herron
abhishek wrote:
> Hi group any idea on HOW  TO HANDLE POINTERS FROM NON-LOCAL HEAPS??
>
>
> Thank you
>   
POINTERS?   Heaps?   Huh?   Ummm, let me think -- those terms *do* sound
vaguely familiar -- from sometime in the deep dark primitive past.  
Perhaps from back in my (shudder) C/C++ days -- ya, that's it. 
Thankfully, this is Python and the modern era -- we don't use no
stinking POINTERS here. 

Seriously, this group deals with Python.  There are no pointers in
Python.  Now please, what did you *really* mean to ask?

Gary Herron

-- 
http://mail.python.org/mailman/listinfo/python-list


python recursive function

2008-01-11 Thread Tom_chicollegeboy
here is what I have to do:

This question involves a game with teddy bears. The game starts when I
give you some bears. You then start giving me back some bears, but you
must follow these rules (where n is the number of bears that you
have):

If n is even, then you may give back exactly n/2 bears. (Hint: To test
whether n is even, use the expression ((n % 2) == 0).)
If n is divisible by 3 or 4, then you may multiply the last two digits
of n and give back this many bears. (By the way, the last digit of n
is n%10, and the next-to-last digit is (n%100)/10; this rule may not
be used if either of the last two digits is 0.)

If n is divisible by 5, then you may give back exactly 42 bears.
The goal of the game for you is to end up with EXACTLY 42 bears.

For example, suppose that you start with 250 bears. Then you could
make these moves:

Start with 250 bears.
Since 250 is divisible by 5, you may return 42 of the bears, leaving
you with 208 bears.
Since 208 is even, you may return half of the bears, leaving you with
104 bears.
Since 104 is even, you may return half of the bears, leaving you with
52 bears.
Since 52 is divisible by 4, you may multiply the last two digits
(resulting in 10) and return these 10 bears. This leaves you with 42
bears.
You have reached the goal!
Now, you are to write a program that, if I give you n bears, returns
true if it is at all possible for you to win the game. Your program
must use recursion to check all possible ways in which you can apply
the rules.


Usage:

>>> bears(42)
True
>>> bears(250)
True
>>> bears(50)
False
>>> bears(84)
True
>>> bears(41)
False


As you see my program must use recursion.

I came up with this idea but I am not sure if its right or are there
any minor errors that I can easily fix:

def bears (n):
if n==42:
return True
if n%5==0:
bears(n-42)
if n%2==0:
bears(n/2)
if n%3==0 or n%4==0:
one = (n%10)
two = ((n%100)/10)
if one!=0 and two!=0:
bears(n-(one*two))
return False

If a game hits 42 it should return True, otherwise False. If program
never hits 42 and return True, then it returns False. I figured out
base case, but I still get False when I enter bears(250). Any help
would be very appreciated!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Bruno Desthuilliers
Tom_chicollegeboy a écrit :
(snip)
> As you see my program must use recursion.

It's conceptually easier to express using recursions - but every 
recursion-based algorithm can be rewritten to use iteration (and 
vice-versa).

> I came up with this idea but I am not sure if its right or are there
> any minor errors that I can easily fix:
> 
> def bears (n):
> if n==42:
> return True
> if n%5==0:
> bears(n-42)

You want:
   return bears(n - 42)

> if n%2==0:
> bears(n/2)

idem

> if n%3==0 or n%4==0:
> one = (n%10)
> two = ((n%100)/10)
> if one!=0 and two!=0:
> bears(n-(one*two))

idem

> return False
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Gary Herron
Tom_chicollegeboy wrote:
> here is what I have to do:
>
> This question involves a game with teddy bears. The game starts when I
> give you some bears. You then start giving me back some bears, but you
> must follow these rules (where n is the number of bears that you
> have):
>   
This sounds very much like a homework assignment, and so should probably
not be answered here.  (Neither should it have been asked here.)   If,
in your attempt to write this program, you have some questions about
Python, then I encourage to ask those questions here.

Gary Herron


> If n is even, then you may give back exactly n/2 bears. (Hint: To test
> whether n is even, use the expression ((n % 2) == 0).)
> If n is divisible by 3 or 4, then you may multiply the last two digits
> of n and give back this many bears. (By the way, the last digit of n
> is n%10, and the next-to-last digit is (n%100)/10; this rule may not
> be used if either of the last two digits is 0.)
>
> If n is divisible by 5, then you may give back exactly 42 bears.
> The goal of the game for you is to end up with EXACTLY 42 bears.
>
> For example, suppose that you start with 250 bears. Then you could
> make these moves:
>
> Start with 250 bears.
> Since 250 is divisible by 5, you may return 42 of the bears, leaving
> you with 208 bears.
> Since 208 is even, you may return half of the bears, leaving you with
> 104 bears.
> Since 104 is even, you may return half of the bears, leaving you with
> 52 bears.
> Since 52 is divisible by 4, you may multiply the last two digits
> (resulting in 10) and return these 10 bears. This leaves you with 42
> bears.
> You have reached the goal!
> Now, you are to write a program that, if I give you n bears, returns
> true if it is at all possible for you to win the game. Your program
> must use recursion to check all possible ways in which you can apply
> the rules.
>
>
> Usage:
>
>   
 bears(42)
 
> True
>   
 bears(250)
 
> True
>   
 bears(50)
 
> False
>   
 bears(84)
 
> True
>   
 bears(41)
 
> False
>
>
> As you see my program must use recursion.
>
> I came up with this idea but I am not sure if its right or are there
> any minor errors that I can easily fix:
>
> def bears (n):
> if n==42:
> return True
> if n%5==0:
> bears(n-42)
> if n%2==0:
> bears(n/2)
> if n%3==0 or n%4==0:
> one = (n%10)
> two = ((n%100)/10)
> if one!=0 and two!=0:
> bears(n-(one*two))
> return False
>
> If a game hits 42 it should return True, otherwise False. If program
> never hits 42 and return True, then it returns False. I figured out
> base case, but I still get False when I enter bears(250). Any help
> would be very appreciated!
>   

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: improving performance of python webserver running python scripts in cgi-bin

2008-01-11 Thread Bruno Desthuilliers
Dale a écrit :
> I am using a simple python webserver (see code below) to serve up
> python scripts located in my cgi-bin directory.
> 
> import BaseHTTPServer
> import CGIHTTPServer
> class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
> cgi_directories = ['/cgi-bin']
> httpd = BaseHTTPServer.HTTPServer(('',8000), Handler)
> httpd.serve_forever()
> 
> 
> This works fine, but now I would like to combine the python scripts
> into the server program to eliminate starting the python interpreter
> on each script call.  I am new to python, and was wondering if there
> is a better techique that will be faster.
 >
> Also, can someone reccommend an alternative approach to
> httpd.serve_forever().  I would like to perform other python functions
> (read a serial port, write to an Ethernet port, write to a file, etc.)
> inside the web server program above.  Is there an example of how to
> modify the code for an event loop style of operation where the program
> mostly performs my python I/O functions until an HTTP request comes
> in, and then it breaks out of the I/O operations to handle the HTTP
> request.
> 
May I suggest that you take a look at more sophisticated solutions, like 
either wsgi, CherryPy or Twisted ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread cokofreedom
On Jan 11, 9:46 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> Tom_chicollegeboy wrote:
> > here is what I have to do:
>
> > This question involves a game with teddy bears. The game starts when I
> > give you some bears. You then start giving me back some bears, but you
> > must follow these rules (where n is the number of bears that you
> > have):
>
> This sounds very much like a homework assignment, and so should probably
> not be answered here.  (Neither should it have been asked here.)   If,
> in your attempt to write this program, you have some questions about
> Python, then I encourage to ask those questions here.
>
> Gary Herron
>
> > If n is even, then you may give back exactly n/2 bears. (Hint: To test
> > whether n is even, use the expression ((n % 2) == 0).)
> > If n is divisible by 3 or 4, then you may multiply the last two digits
> > of n and give back this many bears. (By the way, the last digit of n
> > is n%10, and the next-to-last digit is (n%100)/10; this rule may not
> > be used if either of the last two digits is 0.)
>
> > If n is divisible by 5, then you may give back exactly 42 bears.
> > The goal of the game for you is to end up with EXACTLY 42 bears.
>
> > For example, suppose that you start with 250 bears. Then you could
> > make these moves:
>
> > Start with 250 bears.
> > Since 250 is divisible by 5, you may return 42 of the bears, leaving
> > you with 208 bears.
> > Since 208 is even, you may return half of the bears, leaving you with
> > 104 bears.
> > Since 104 is even, you may return half of the bears, leaving you with
> > 52 bears.
> > Since 52 is divisible by 4, you may multiply the last two digits
> > (resulting in 10) and return these 10 bears. This leaves you with 42
> > bears.
> > You have reached the goal!
> > Now, you are to write a program that, if I give you n bears, returns
> > true if it is at all possible for you to win the game. Your program
> > must use recursion to check all possible ways in which you can apply
> > the rules.
>
> > Usage:
>
>  bears(42)
>
> > True
>
>  bears(250)
>
> > True
>
>  bears(50)
>
> > False
>
>  bears(84)
>
> > True
>
>  bears(41)
>
> > False
>
> > As you see my program must use recursion.
>
> > I came up with this idea but I am not sure if its right or are there
> > any minor errors that I can easily fix:
>
> > def bears (n):
> > if n==42:
> > return True
> > if n%5==0:
> > bears(n-42)
> > if n%2==0:
> > bears(n/2)
> > if n%3==0 or n%4==0:
> > one = (n%10)
> > two = ((n%100)/10)
> > if one!=0 and two!=0:
> > bears(n-(one*two))
> > return False
>
> > If a game hits 42 it should return True, otherwise False. If program
> > never hits 42 and return True, then it returns False. I figured out
> > base case, but I still get False when I enter bears(250). Any help
> > would be very appreciated!

Note that for ;
if one!=0 and two!=0:

you can use
if one and two:

which is my pythonic.

Also in your example with 52, shouldn't it divide by even first?
Obviously this must not happen, thus maybe you should run a check that
when you are returning a new value it does not go below 42? Frankly
this looks like a terrible way to use recursion.
-- 
http://mail.python.org/mailman/listinfo/python-list


How to POST call and retrieve result page

2008-01-11 Thread suyash jape
Hi all
i want to access a web page through python script, fillup the necessary
fields,
and press submit button (which does POST call) and retrieve the result page
and retrieve some values from it.

Here is the script i have written till now.

>import urllib2
> # create array of name/value pairs
> self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence':
'ATACATTATCCAAACATAGCATGGCTT'})
>
> # send http-post
> request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php";,
params)
>
> # read back each line of reply
> line = request.read()
>print line

This script fills up the correct values in the search.php page.But i am not
sure if it is doing the POST (submit call).
Beacause in 'line' varialble, i am getting the search.php page.Not the
result page which is blast_results.php.

How to retrieve the result page?



Thanks
Suyash
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python too slow?

2008-01-11 Thread Bruno Desthuilliers
Ross Ridge a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
>> And the reference implementation of Python (CPython) is not 
>> interpreted, it's compiled to byte-code, which is then executed by a VM 
>> (just like Java).
>  
> Ed Jensen a écrit :
>> Wow, this is pretty misleading.
> 
> Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>> Ho yes ??? Why so, please ? Care to point to anything *wrong* in the 
>> above statement ?
> 
> Python's byte-code interpreter is not "just like" Java's virtual machine.

of course it's not "just like" - different languages, different 
byte-codes, different implementations. What is "just like" is the 
byte-code/VM scheme. Thought this was obvious to anyone able to parse a 
simple sentence.

> You're deliberately trying to mislead people into thinking Python performs
> similarily to Java.

I don't know what you're smoking, but you should perhaps stop - because 
this seems  to drive you into paranoïd delirium.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Bruno Desthuilliers
Fredrik Lundh a écrit :
> A.T.Hofkamp wrote:
> 
>> Now the question you need to answer for yourself, is how much more 
>> worth is
>> your own time compared to the gain in CPU time. If you think they are 
>> equal (ie
>> the problem as a whole should be solved as fast as possible, thus the 
>> sum of
>> development time + execution time should be as short as possible), you 
>> can
>> spend an additional 1.5 seconds development in the alternative solution.
> 
> so you only run your programs once?

Lol !-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Chris
On Jan 11, 10:30 am, Tom_chicollegeboy <[EMAIL PROTECTED]> wrote:
> here is what I have to do:
>
> This question involves a game with teddy bears. The game starts when I
> give you some bears. You then start giving me back some bears, but you
> must follow these rules (where n is the number of bears that you
> have):
>
> If n is even, then you may give back exactly n/2 bears. (Hint: To test
> whether n is even, use the expression ((n % 2) == 0).)
> If n is divisible by 3 or 4, then you may multiply the last two digits
> of n and give back this many bears. (By the way, the last digit of n
> is n%10, and the next-to-last digit is (n%100)/10; this rule may not
> be used if either of the last two digits is 0.)
>
> If n is divisible by 5, then you may give back exactly 42 bears.
> The goal of the game for you is to end up with EXACTLY 42 bears.
>
> For example, suppose that you start with 250 bears. Then you could
> make these moves:
>
> Start with 250 bears.
> Since 250 is divisible by 5, you may return 42 of the bears, leaving
> you with 208 bears.
> Since 208 is even, you may return half of the bears, leaving you with
> 104 bears.
> Since 104 is even, you may return half of the bears, leaving you with
> 52 bears.
> Since 52 is divisible by 4, you may multiply the last two digits
> (resulting in 10) and return these 10 bears. This leaves you with 42
> bears.
> You have reached the goal!
> Now, you are to write a program that, if I give you n bears, returns
> true if it is at all possible for you to win the game. Your program
> must use recursion to check all possible ways in which you can apply
> the rules.
>
> Usage:
>
> >>> bears(42)
> True
> >>> bears(250)
> True
> >>> bears(50)
> False
> >>> bears(84)
> True
> >>> bears(41)
>
> False
>
> As you see my program must use recursion.
>
> I came up with this idea but I am not sure if its right or are there
> any minor errors that I can easily fix:
>
> def bears (n):
> if n==42:
> return True
> if n%5==0:
> bears(n-42)
> if n%2==0:
> bears(n/2)
> if n%3==0 or n%4==0:
> one = (n%10)
> two = ((n%100)/10)
> if one!=0 and two!=0:
> bears(n-(one*two))
> return False
>
> If a game hits 42 it should return True, otherwise False. If program
> never hits 42 and return True, then it returns False. I figured out
> base case, but I still get False when I enter bears(250). Any help
> would be very appreciated!

Stylistically I prefer 'if not n % 5', looks neater.
As for your assignment, the hardest task will be creating an effective
method of ensuring you recurse through all possibilities.

ie. do you brute force on every step, or when getting to step do you
fork your possibilities.
That is more a design question rather than a python one though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Duncan Booth
Bruno Desthuilliers <[EMAIL PROTECTED]> 
wrote:

> You want:
>return bears(n - 42)

Actually, no he doesn't. He needs to explore all options when the first 
attempt fails. But I'm not going to write his homework for him.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Bruno Desthuilliers
George Sakkis a écrit :
> On Jan 10, 3:37 am, Bruno Desthuilliers wrote:
> 
>> I fail to see how the existence of JIT compilers in some Java VM changes
>> anything to the fact that both Java (by language specification) and
>> CPython use the byte-code/VM scheme.
> 
> Because these "some Java VMs" with JIT compilers are the de facto
> standard used by millions; 

Repeating an argument doesn't make it more true nor more relevant. Once 
again, this doesn't change anything to the fact exposed above.

> the spec is pretty much irrelevant

I mentionned this because this kind of choice is usually not part of the 
language spec but of a specific implementation. Java is AFAIK the only 
language where this implementation stuff is part of the spec.

> (unless
> you're a compiler writer or language theorist).

I thought it was quite clear and obvious that I was talking about points 
relating to these fields.

> George
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread cokofreedom
> Stylistically I prefer 'if not n % 5', looks neater.
> As for your assignment, the hardest task will be creating an effective
> method of ensuring you recurse through all possibilities.

I was chatting to a friend about the 'if not n % 5' and while I am
happy to use it saying that when 5 % 5 is False because it returns
0...for this case just feels wrong to me.

I understand the reason to keep it this way...but still...having to
use not all the time is just annoying.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Bruno Desthuilliers
Ed Jensen a écrit :
> Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>> oh, please.  it was perfectly clear for anyone with the slightest clue 
>> what Bruno was talking about (especially if they'd read the post he was 
>> replying to), so the only question that remains is why you didn't 
>> understand it.
> 
> If you have something substantive to add to the discussion, by all
> means, do so.  But please, keep your childish and insulting comments
> to yourself.

I don't think you're going to make you some friends here insulting 
Fredrik. I don't know who Ed Jensen is, but we are quite a lot here to 
know and respect Mr Lundh for his contributions to Python as both a 
language and a community.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Bruno Desthuilliers
Gary Herron a écrit :
> Tom_chicollegeboy wrote:
>> here is what I have to do:
>>
>> This question involves a game with teddy bears. The game starts when I
>> give you some bears. You then start giving me back some bears, but you
>> must follow these rules (where n is the number of bears that you
>> have):
>>   
> This sounds very much like a homework assignment,

Indeed.

> and so should probably
> not be answered here.  (Neither should it have been asked here.)   If,
> in your attempt to write this program, you have some questions about
> Python, then I encourage to ask those questions here.

Garry, you should have read the whole post before answering. The OP's 
attempt at solving the problem was below, along with the question.

(snip)
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with Scons

2008-01-11 Thread anush
Can anybody tell how I could go about running python scripts with
scons.
-- 
http://mail.python.org/mailman/listinfo/python-list


help for installing PIL

2008-01-11 Thread Chan Kuang Lim
I'm using Window XP. How to install PIL 1.1.6? The Python i installed, is come 
with Plone. So, is it ok? Thank you.

Regards,
Chan Kuang Lim

   
-
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: what does **kw mean?

2008-01-11 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> I've been reading the following example, and couldn't figure out, what
> **kw mean. (It's an empty dictionary, but what's the semantics):

Keyword varargs. And FWIW, *args is for positional varargs.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does **kw mean?

2008-01-11 Thread Lie
On Jan 11, 4:38 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> I've been reading the following example, and couldn't figure out, what
> **kw mean. (It's an empty dictionary, but what's the semantics):

It's a keyword argument. It's some kind of repository for arguments
that aren't recognized.

If you have function like this:
def func(a, *args, *kw):
print a
print args
print kw

and you call the functin like this:
func('value A', 'value B', 'value C', argumentA = 'value D', argumentB
= 'value D')
the extra arguments would normally raise an error, but with the * and
**, Python would:
- assign 'value B' and 'value C' to args
- assign 'argumentA':'value D' and 'argumentB':'value E' to kw

so if you run the function, it will output:

value A
('value B', 'value C')
{'argumentB': 'value E', 'argumentA': 'value D'}


this args and kw can be accessed like a tuple and dictionary
respectively

See '4.7.2 Keyword Arguments' and '4.7.3 Arbitrary Argument Lists' on
Python Help File
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why Python.exe is breaking with memory dump??

2008-01-11 Thread Fredrik Lundh
abhishek wrote:

> Hi group i have created a simple .pyd using which i m able call C
> function from python code. There are around 6 such functions. 4 of
> them work great. But when i try to run other two python's exe breaks
> giving memory dump.
> 
> Any pros or cons on what led to such a situation.. Is it a problem in
> my c code??

yes.

check for reference counting errors, plus the usual C stuff: memory 
allocation errors, memory overwrites, bogus pointers, etc.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help for installing PIL

2008-01-11 Thread Fredrik Lundh
Chan Kuang Lim wrote:

> I'm using Window XP. How to install PIL 1.1.6? The Python i installed, 
> is come with Plone. So, is it ok? Thank you.

Just run the appropriate installer for your Python version:

 http://www.pythonware.com/products/pil

as the page says, "If the Windows installer cannot find a Python 
interpreter, you may have to register your interpreter", and links
to this page:

 http://effbot.org/zone/python-register.htm



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Property with Arguments

2008-01-11 Thread Fredrik Lundh
Lie wrote:

> Is there a way to create a property with arguments?

That's called method in Python, and has it's own syntax.  You cannot 
assign to methods.

 > Or an index value like a list?

Make the property that returns a list-like object (hooking __getitem__, 
__setitem__, etc).



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adding methods at runtime

2008-01-11 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Can I access the class attributes from a method added at runtime? 

Of course.

> (My
> experience says no.)

So there's something wrong with your experience !-)

> I experimented with the following code:
> 
> 
> class myclass(object):
> myattr = "myattr"
> 
> instance = myclass()
> def method(x):
> print x
> 
> instance.method = method

As Marc pointed out, you're not adding a method but a function. What you 
want is:

def method(self, x):
   print "x : %s - myattr : %s" % (x, self.myattr)

import new
instance.method = new.instancemethod(method, instance, myclass)

Note that this is only needed for per-instance methods - if you want to 
add a new method for all instances, you just set the function as 
attribute of the class. The lookup mechanism will then invoke the 
descriptor protocol on the function object, which will return a method 
(FWIW, you have to do it manually on per-instance methods because the 
descriptor protocol is not invoked on instance attributes, only on class 
attributes).

HTH
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Bruno Desthuilliers
Duncan Booth a écrit :
> Bruno Desthuilliers <[EMAIL PROTECTED]> 
> wrote:
> 
>> You want:
>>return bears(n - 42)
> 
> Actually, no he doesn't. He needs to explore all options when the first 
> attempt fails. 

Possibly - I didn't bother checking the algorithm correctness, just 
pointed out an obvious newbie programming error.

> But I'm not going to write his homework for him.

Nor do I.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding python code into text document question.

2008-01-11 Thread Thomas Troeger
Thanks guys, you've helped me very much :) Cheers & happy new year!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 rate limiting

2008-01-11 Thread Nick Craig-Wood
Dimitrios Apostolou <[EMAIL PROTECTED]> wrote:
>  I want to limit the download speed when using urllib2. In particular, 
>  having several parallel downloads, I want to make sure that their total 
>  speed doesn't exceed a maximum value.
> 
>  I can't find a simple way to achieve this. After researching a can try 
>  some things but I'm stuck on the details:
> 
>  1) Can I overload some method in _socket.py to achieve this, and perhaps 
>  make this generic enough to work even with other libraries than urllib2?
> 
>  2) There is the urllib.urlretrieve() function which accepts a reporthook 
>  parameter.

Here is an implementation based on that idea.  I've used urllib rather
than urllib2 as that is what I'm familiar with.


#!/usr/bin/python

"""
Fetch a url rate limited

Syntax: rate URL local_file_name
"""

import os
import sys
import urllib
from time import time, sleep

class RateLimit(object):
"""Rate limit a url fetch"""
def __init__(self, rate_limit):
"""rate limit in kBytes / second"""
self.rate_limit = rate_limit
self.start = time()
def __call__(self, block_count, block_size, total_size):
total_kb = total_size / 1024
downloaded_kb = (block_count * block_size) / 1024
elapsed_time = time() - self.start
if elapsed_time != 0:
rate = downloaded_kb / elapsed_time
print "%d kb of %d kb downloaded %f.1 kBytes/s\n" % (downloaded_kb 
,total_kb, rate),
expected_time = downloaded_kb / self.rate_limit
sleep_time = expected_time - elapsed_time
print "Sleep for", sleep_time
if sleep_time > 0:
sleep(sleep_time)

def main():
"""Fetch the contents of urls"""
if len(sys.argv) != 4:
print 'Syntax: %s "rate in kBytes/s" URL "local output path"' % 
sys.argv[0]
raise SystemExit(1)
rate_limit, url, out_path = sys.argv[1:]
rate_limit = float(rate_limit)
print "Fetching %r to %r with rate limit %.1f" % (url, out_path, rate_limit)
urllib.urlretrieve(url, out_path, reporthook=RateLimit(rate_limit))

if __name__ == "__main__": main()


Use it like this

$ ./rate-limited-fetch.py 16 http://some/url/or/other z
Fetching 'http://some/url/or/other' to 'z' with rate limit 16.0
0 kb of 10118 kb downloaded 0.00.1 kBytes/s
Sleep for -0.0477550029755
8 kb of 10118 kb downloaded 142.073242.1 kBytes/s
Sleep for 0.443691015244
16 kb of 10118 kb downloaded 32.130966.1 kBytes/s
Sleep for 0.502038002014
24 kb of 10118 kb downloaded 23.952789.1 kBytes/s
Sleep for 0.498028993607
32 kb of 10118 kb downloaded 21.304672.1 kBytes/s
Sleep for 0.497982025146
40 kb of 10118 kb downloaded 19.979510.1 kBytes/s
Sleep for 0.497948884964
48 kb of 10118 kb downloaded 19.184721.1 kBytes/s
Sleep for 0.498008966446
...
1416 kb of 10118 kb downloaded 16.090774.1 kBytes/s
Sleep for 0.499262094498
1424 kb of 10118 kb downloaded 16.090267.1 kBytes/s
Sleep for 0.499293088913
1432 kb of 10118 kb downloaded 16.089760.1 kBytes/s
Sleep for 0.499292135239
1440 kb of 10118 kb downloaded 16.089254.1 kBytes/s
Sleep for 0.499267101288
...


-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: alternating string replace

2008-01-11 Thread cokofreedom
evenOrOdd = True
s1, s2 = "hi_cat_bye_dog_foo_bar_red", ""

for i in s1:
   if i == '_':
   s2 += ':' if evenOrOdd else ','
   evenOrOdd = not evenOrOdd
   else:
   s2 += i

print s2

Presently I cannot work out how to use .join instead of += ...
While I realise this is producing a new string (and I believe +=
rebuilds it a lot?) how much slower
is this going to be over the others?
-- 
http://mail.python.org/mailman/listinfo/python-list


what does **kw mean?

2008-01-11 Thread [EMAIL PROTECTED]
I've been reading the following example, and couldn't figure out, what
**kw mean. (It's an empty dictionary, but what's the semantics):


def wrap(method):
def wrapped(self, *args, **kw):
print "begin"
method(self, *args, **kw)
print "end"
return wrapped


class Test(object):
def method(self, name):
print "method(%r)" % name

t = Test()
t.method("pure")
Test.method = wrap(Test.method)
t.method("wrapped")

-- 
http://mail.python.org/mailman/listinfo/python-list


encrypting python modules

2008-01-11 Thread Paul Sijben
Hello,

this question has come by repeatedly in several guises over the past
years but has never been solved in this forum as far as I have been able
to Google.

However since so many people are asking the question, I hope someone has
made a solution and is willing to share it.

The problem: I have a client-server app written in python. I want to
make sure that the client is not:
1) destabilized by users accidentally or on purpose dropping python
files in the path (after which calling the helpdesk will not be useful)
2) extended with "new features" without me knowing about it (again
resulting in calls to my helpdesk...)
3) trivially decompiled.

Added issue, I want the client to be able to update itself when I have
fixed bugs or created new functionality.

I know that I can not stop a dedicated hacker deconstructing my code.
Since all clients need to go through the server I am not afraid of
"freeloaders".

I am now considering overriding import with some code that will only
import modules signed and crypted by me.

However I can not imagine that I would be the first one planning to do this.
So is there a solution like this available somewhere?

Paul Sijben

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does **kw mean?

2008-01-11 Thread Shane Geiger
Does this help?

def foobar(first_name,last_name, *args, **kwargs):
print first_name
print last_name
print "Tuple:",args
print "Dict:",kwargs

x = "has"
y = "demonstrated"
foobar('Shane','Geiger', x, y, adjective='useful', thing='PYTHON trick
known as extended call syntax', adverb='wonderfully')




[EMAIL PROTECTED] wrote:
> I've been reading the following example, and couldn't figure out, what
> **kw mean. (It's an empty dictionary, but what's the semantics):
>
>
> def wrap(method):
> def wrapped(self, *args, **kw):
> print "begin"
> method(self, *args, **kw)
> print "end"
> return wrapped
>
>
> class Test(object):
> def method(self, name):
> print "method(%r)" % name
>
> t = Test()
> t.method("pure")
> Test.method = wrap(Test.method)
> t.method("wrapped")
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Strange problem: MySQL and python logging using two separate cursors

2008-01-11 Thread Frank Aune
On Wednesday 09 January 2008 18:52:02 Dennis Lee Bieber wrote:
> On Wed, 9 Jan 2008 10:11:09 +0100, Frank Aune <[EMAIL PROTECTED]>
>
> declaimed the following in comp.lang.python:
> > The only clue I have so far, is that the cursor in task 1 seems to be
> > unable to "register" any new entries in the log table produced by task 2
> > as soon as task 1 perform an SQL query of some kind.
>
>   How often do you issue a commit? 

I experience the behaviour for task 1 even if the select query only reads out 
data and no commit is needed.

Do I really need to perform commits on a handler even though it only reads out 
data? From a MySQL shell I can see the changes from the other handler without 
the commits, but afaics that shouldnt be the case if the above were true.

Thanks,
Frank

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread HYRY

> def bears (n):
> if n==42:
> return True
> if n%5==0:
> bears(n-42)
> if n%2==0:
> bears(n/2)
> if n%3==0 or n%4==0:
> one = (n%10)
> two = ((n%100)/10)
> if one!=0 and two!=0:
> bears(n-(one*two))
> return False
>
> If a game hits 42 it should return True, otherwise False. If program
> never hits 42 and return True, then it returns False. I figured out
> base case, but I still get False when I enter bears(250). Any help
> would be very appreciated!

try this:

def bears (n):
if n==42:
return True
if n%5==0:
if bears(n-42):
return True
if n%2==0:
if bears(n/2):
return True
if n%3==0 or n%4==0:
one = (n%10)
two = ((n%100)/10)
if one!=0 and two!=0:
if bears(n-(one*two)):
return True
return False

print bears(42)
print bears(250)
print bears(50)
print bears(84)
print bears(41)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: alternating string replace

2008-01-11 Thread Chris
On Jan 9, 12:34 pm, cesco <[EMAIL PROTECTED]> wrote:
> Hi,
>
> say I have a string like the following:
> s1 = 'hi_cat_bye_dog'
> and I want to replace the even '_' with ':' and the odd '_' with ','
> so that I get a new string like the following:
> s2 = 'hi:cat,bye:dog'
> Is there a common recipe to accomplish that? I can't come up with any
> solution...
>
> Thanks in advance
> Cesco

A simple list comprehension is all that is needed.

input_string = 'hi_cat_bye_dog'.split('_')
output_string = ','.join([':'.join(input_string[i:i+2]) for i in
xrange(0,len(input_string),2)])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adding methods at runtime

2008-01-11 Thread John Machin
On Jan 11, 10:44 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 10 Jan 2008 14:55:18 -0800, [EMAIL PROTECTED] wrote:
> > Can I access the class attributes from a method added at runtime? (My
> > experience says no.)
> > I experimented with the following code:
>
> > [Code snipped]
>
> > So it seems to me, if you add a method to an instance, the method will
> > not get "self" as parameter.
>
> You are not adding a method but a function.  Take a look at
> `types.MethodType()` to create a method from a function, instance, and
> class.
>

Just in case gentle readers are wondering where to find the docs for
types.MethodType, here's a hint:

>>> import types, new; types.MethodType is new.instancemethod
True
>>>


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python via a little word frequency program

2008-01-11 Thread rent
import collections

names = "freddy fred bill jock kevin andrew kevin kevin jock"
freq = collections.defaultdict(int)
for name in names.split():
  freq[name] += 1
keys = freq.keys()
keys.sort(key = freq.get, reverse = True)
for k in keys:
  print "%-10s: %d" % (k, freq[k])

On Jan 9, 6:58 pm, Andrew Savige <[EMAIL PROTECTED]> wrote:
> I'm learning Python by reading David Beazley's "Python Essential Reference"
> book and writing a few toy programs. To get a feel for hashes and sorting,
> I set myself this little problem today (not homework, BTW):
>
>   Given a string containing a space-separated list of names:
>
> names = "freddy fred bill jock kevin andrew kevin kevin jock"
>
>   produce a frequency table of names, sorted descending by frequency.
>   then ascending by name. For the above data, the output should be:
>
> kevin : 3
> jock  : 2
> andrew: 1
> bill  : 1
> fred  : 1
> freddy: 1
>
> Here's my first attempt:
>
> names = "freddy fred bill jock kevin andrew kevin kevin jock"
> freq = {}
> for name in names.split():
> freq[name] = 1 + freq.get(name, 0)
> deco = zip([-x for x in freq.values()], freq.keys())
> deco.sort()
> for v, k in deco:
> print "%-10s: %d" % (k, -v)
>
> I'm interested to learn how more experienced Python folks would solve
> this little problem. Though I've read about the DSU Python sorting idiom,
> I'm not sure I've strictly applied it above ... and the -x hack above to
> achieve a descending sort feels a bit odd to me, though I couldn't think
> of a better way to do it.
>
> I also have a few specific questions. Instead of:
>
> for name in names.split():
> freq[name] = 1 + freq.get(name, 0)
>
> I might try:
>
> for name in names.split():
> try:
> freq[name] += 1
> except KeyError:
> freq[name] = 1
>
> Which is preferred?
>
> Ditto for:
>
> deco = zip([-x for x in freq.values()], freq.keys())
>
> versus:
>
> deco = zip(map(operator.neg, freq.values()), freq.keys())
>
> Finally, I might replace:
>
> for v, k in deco:
> print "%-10s: %d" % (k, -v)
>
> with:
>
> print "\n".join("%-10s: %d" % (k, -v) for v, k in deco)
>
> Any feedback on good Python style, performance tips, good books
> to read, etc. is appreciated.
>
> Thanks,
> /-\
>
>   Make the switch to the world's best email. Get the new Yahoo!7 Mail 
> now.www.yahoo7.com.au/worldsbestemail

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: alternating string replace

2008-01-11 Thread bearophileHUGS
Dennis Lee Bieber:
> So� in Python, your str[n] :=
> ':' just can not be done! You would have to create a new string
> containing everything in front of n, the ':', and then everything behind
> n (skipping n itself, of course). This is a painfully slow operation in
> Python as it allocates memory for the parts, allocates memory for the
> new combined string, and then garbage collects (potentially) the
> original string and parts. The recommended Python idiom is to break
> strings into a list of separate parts (str.split('_'), for example),
> manipulate those parts, and at the end of manipulation, rejoin them
> using some delimiter ( ",".join(partslist) )

An alternative solution, that's often good, expecially wity Psyco, is
to use an:
array.array("c", originalstring)
and then mutate it, as you do with Pascal strings.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list

Property with Arguments

2008-01-11 Thread Lie
Is there a way to create a property with arguments? Or an index value
like a list?

To be used in the form like:

someClass.someProperty['arguments'] = 'some value'
or
someClass.someProperty('argument1', 'argument2') = 'some value'

-- 
http://mail.python.org/mailman/listinfo/python-list


import gzip error (please help)

2008-01-11 Thread syahreza.octadian
Dear all,

Please help, i have error message when i import gzip module. The error
like this below:

bash-3.00$ python
Python 2.5 (r25:51908, Sep 20 2006, 03:46:40)
[GCC 3.4.6] on sunos5
Type "help", "copyright", "credits" or "license" for more information.
>>> import gzip
Traceback (most recent call last):
  File "", line 1, in 
  File "/usr/local/lib/python2.5/gzip.py", line 9, in 
import zlib
ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/
lib/python2.5/lib-dynload/zlib.so: symbol inflateCopy: referenced
symbol not found


Thx u.
Syahreza Octadian
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: module finalizer - is there such a beast?

2008-01-11 Thread Thomas Troeger
You can execute cleanup code if the interpreter exits:

http://docs.python.org/lib/module-atexit.html

This will only cover the `Python's exit' part of your question, not the 
module reloading stuff. On the other hand, if you load a module you 
could set a global variable and check for it on reload...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python via a little word frequency program

2008-01-11 Thread Paul Rubin
rent <[EMAIL PROTECTED]> writes:
> keys = freq.keys()
> keys.sort(key = freq.get, reverse = True)
> for k in keys:
>  print "%-10s: %d" % (k, freq[k])

I prefer (untested):

  def snd((x,y)): return y   # I wish this was built-in
  sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True)
  for k,f in sorted_freq:
 print "%-10s: %d" % (k, f)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: loading a script from text data

2008-01-11 Thread Fredrik Lundh
Patrick Stinson wrote:

> Is it possible to load a script from it's text data, and not from a 
> file? I'm writing a scripting engine and need to run the scripts right 
> from the editor.

look up the "exec" statement and, optionally, the "compile" function in 
the manual.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a specific column from file

2008-01-11 Thread A.T.Hofkamp
On 2008-01-11, cesco <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a file containing four columns of data separated by tabs (\t)
> and I'd like to read a specific column from it (say the third). Is
> there any simple way to do this in Python?
>
> I've found quite interesting the linecache module but unfortunately
> that is (to my knowledge) only working on lines, not columns.
>
> Any suggestion?

the csv module may do what you want.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: import gzip error (please help)

2008-01-11 Thread Fredrik Lundh
syahreza.octadian wrote:

> Please help, i have error message when i import gzip module. The error
> like this below:
> 
> bash-3.00$ python
> Python 2.5 (r25:51908, Sep 20 2006, 03:46:40)
> [GCC 3.4.6] on sunos5
> Type "help", "copyright", "credits" or "license" for more information.
 import gzip
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/usr/local/lib/python2.5/gzip.py", line 9, in 
> import zlib
> ImportError: ld.so.1: python: fatal: relocation error: file /usr/local/
> lib/python2.5/lib-dynload/zlib.so: symbol inflateCopy: referenced
> symbol not found

the core zlib library (libz.so) isn't installed on your machine.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Nick Craig-Wood
HYRY <[EMAIL PROTECTED]> wrote:
>  def bears (n):
>  if n==42:
>  return True
>  if n%5==0:
>  if bears(n-42):
>  return True
>  if n%2==0:
>  if bears(n/2):
>  return True
>  if n%3==0 or n%4==0:
>  one = (n%10)
>  two = ((n%100)/10)
>  if one!=0 and two!=0:
>  if bears(n-(one*two)):
>  return True
>  return False

Almost but you missed a case...

>>> for i in range(100):
... try:
... print i, bears(i)
... except RuntimeError, e:
... print i, e
...
0 0 maximum recursion depth exceeded
1 False
2 False
3 False
4 False
5 False
6 False
7 False
8 False
9 False
10 10 maximum recursion depth exceeded
11 False
12 12 maximum recursion depth exceeded
113 False
14 False
15 15 maximum recursion depth exceeded
16 16 maximum recursion depth exceeded
17 False
[snip]
89 False
90 90 maximum recursion depth exceeded
91 False
92 False
93 93 maximum recursion depth exceeded
94 False
95 False
96 96 maximum recursion depth exceeded
97 False
98 False
99 99 maximum recursion depth exceeded

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a bidimensional list in a bidimensional array

2008-01-11 Thread Santiago Romero
> > - Speed Performance: Do you think that changing from list to Array()
> > would improve speed? I'm going to do lots of tilemap[y][x] checks (I
> > mean, player jumping around the screen, checking if it's falling over
> > a non-zero tile, and so).

> First of all: if you have enough memory to use a python list, then I
> suggest you to use a list.
>
> Often python lists are faster than array.array (maybe because python
> lists actually contain pyobjects).


 My problem is that, in my game, each screen is 30x20, and I have
about 100 screens, so my tilemap contains 32*20*100 = 6 python
objects (integers).

 If each integer-python-object takes 16 bytes, this makes 6 * 16 =
almost 1MB of memory just for the tilemaps...

 Using array of type H (16 bits per item = 2 bytes), my maps take just
6*2 = 120KB of memory.

 After that, I just will access tilemap data for reading (i.e.  value
= tilemap.GetTile(x,y)) ...

 Do you think I should still go with lists instead of an H-type array?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a specific column from file

2008-01-11 Thread Chris
On Jan 11, 2:15 pm, cesco <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a file containing four columns of data separated by tabs (\t)
> and I'd like to read a specific column from it (say the third). Is
> there any simple way to do this in Python?
>
> I've found quite interesting the linecache module but unfortunately
> that is (to my knowledge) only working on lines, not columns.
>
> Any suggestion?
>
> Thanks and regards
> Francesco

for (i, each_line) in enumerate(open('input_file.txt','rb')):
try:
column_3 = each_line.split('\t')[2].strip()
except IndexError:
print 'Not enough columns on line %i of file.' % (i+1)
continue

do_something_with_column_3()
-- 
http://mail.python.org/mailman/listinfo/python-list


reading a specific column from file

2008-01-11 Thread cesco
Hi,

I have a file containing four columns of data separated by tabs (\t)
and I'd like to read a specific column from it (say the third). Is
there any simple way to do this in Python?

I've found quite interesting the linecache module but unfortunately
that is (to my knowledge) only working on lines, not columns.

Any suggestion?

Thanks and regards
Francesco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a specific column from file

2008-01-11 Thread Peter Otten
A.T.Hofkamp wrote:

> On 2008-01-11, cesco <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I have a file containing four columns of data separated by tabs (\t)
>> and I'd like to read a specific column from it (say the third). Is
>> there any simple way to do this in Python?
>>
>> I've found quite interesting the linecache module but unfortunately
>> that is (to my knowledge) only working on lines, not columns.
>>
>> Any suggestion?
> 
> the csv module may do what you want.

Here's an example:

>>> print open("tmp.csv").read()
alpha   betagamma   delta
one two three   for

>>> records = csv.reader(open("tmp.csv"), delimiter="\t")
>>> [record[2] for record in records]
['gamma', 'three']

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with Windows build of Yapgvb Python extension

2008-01-11 Thread Lonnie Princehouse
I'm the author of Yapgvb, a Python binding for Graphviz.  Yapgvb
enjoys modest success, but for some time it has been in dire need of a
Python 2.5 build for Windows. I'm posting this message in the hopes of
finding someone who is interested in making this build.

This is a relatively quick task for someone who is comfortable with
building C extensions and has an operational Windows build environment
for Python 2.5 (which I don't).  Alternately, it's a great way to
learn about these things, and to get involved with a small open source
project.

Technologies used:
  graphviz
  distutils
  boost.python
  boost.graph

See: http://yapgvb.sourceforge.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Hrvoje Niksic
Bruno Desthuilliers <[EMAIL PROTECTED]>
writes:

> fact 1: CPython compiles source code to byte-code.
> fact 2: CPython executes this byte-code.
> fact 3: Sun's JDK compiles source code to byte-code.
> fact 4: Sun's JDK executes this byte-code.
>
> Care to prove me wrong on any of these points ? Don't bother: you
> can't.

Fact 4 is misleading because it is only one option available to Sun's
JDK.  Sun's JDK is also capable of transforming the byte-code to
native code and letting the processor execute that instead of the
original byte code, and that is where the most significant speed
increase comes from.  Most importantly, it does so automatically, by
default, with no programmer intervention or configuration, and with
100% compatibility, so it doesn't compare well to Python accelerators
like psyco.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help needed

2008-01-11 Thread Hyuga
On Jan 10, 9:15 pm, tijo <[EMAIL PROTECTED]> wrote:
> Hi mate
>
> i need o do a python program to connect 2 systems using TCP/IP and
> UDP. Also i need to check the performance of these two protocols (how
> many bytes received and how much time took). I havent worked in python
> earlier and have no idea of this. Could someone pls help me. I created
> a program which can connect between 2 systems using these UDP and TCP/
> IP protocols. I dont know how to check the rest like how many bytes
> send or how much time taken
> since this is part of my course work could someone please help me
> thanks in advance.
>
> tijo

The standard library documentation, while lacking in some areas, is
very much your friend here:

>From http://docs.python.org/lib/socket-objects.html (emphasis mine)
send(string[, flags])
Send data to the socket. The socket must be connected to a remote
socket. The optional flags argument has the same meaning as for recv()
above. *Returns the number of bytes sent.*

recv(bufsize[, flags])
Receive data from the socket. The return value is a string
representing the data received.

For timing you can probably use the timeit module (http://
docs.python.org/lib/module-timeit.html) but I'm not really sure how
you're defining "performance".  I mean, I can already tell you that
overall UDP will be "faster", as it has much less overhead.  Surely
your course has covered this...

Hyuga
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python recursive function

2008-01-11 Thread Fidtz
On 11 Jan, 08:30, Tom_chicollegeboy <[EMAIL PROTECTED]> wrote:
> here is what I have to do:
>
> This question involves a game with teddy bears. The game starts when I
> give you some bears. You then start giving me back some bears, but you
> must follow these rules (where n is the number of bears that you
> have):
>
> If n is even, then you may give back exactly n/2 bears. (Hint: To test
> whether n is even, use the expression ((n % 2) == 0).)
> If n is divisible by 3 or 4, then you may multiply the last two digits
> of n and give back this many bears. (By the way, the last digit of n
> is n%10, and the next-to-last digit is (n%100)/10; this rule may not
> be used if either of the last two digits is 0.)
>
> If n is divisible by 5, then you may give back exactly 42 bears.
> The goal of the game for you is to end up with EXACTLY 42 bears.
>
> For example, suppose that you start with 250 bears. Then you could
> make these moves:
>
> Start with 250 bears.
> Since 250 is divisible by 5, you may return 42 of the bears, leaving
> you with 208 bears.
> Since 208 is even, you may return half of the bears, leaving you with
> 104 bears.
> Since 104 is even, you may return half of the bears, leaving you with
> 52 bears.
> Since 52 is divisible by 4, you may multiply the last two digits
> (resulting in 10) and return these 10 bears. This leaves you with 42
> bears.
> You have reached the goal!
> Now, you are to write a program that, if I give you n bears, returns
> true if it is at all possible for you to win the game. Your program
> must use recursion to check all possible ways in which you can apply
> the rules.
>
> Usage:
>
> >>> bears(42)
> True
> >>> bears(250)
> True
> >>> bears(50)
> False
> >>> bears(84)
> True
> >>> bears(41)
>
> False
>
> As you see my program must use recursion.
>
> I came up with this idea but I am not sure if its right or are there
> any minor errors that I can easily fix:
>
> def bears (n):
> if n==42:
> return True
> if n%5==0:
> bears(n-42)
> if n%2==0:
> bears(n/2)
> if n%3==0 or n%4==0:
> one = (n%10)
> two = ((n%100)/10)
> if one!=0 and two!=0:
> bears(n-(one*two))
> return False
>
> If a game hits 42 it should return True, otherwise False. If program
> never hits 42 and return True, then it returns False. I figured out
> base case, but I still get False when I enter bears(250). Any help
> would be very appreciated!

May != Must and Could != Should
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Ross Ridge
Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>fact 1: CPython compiles source code to byte-code.
>fact 2: CPython executes this byte-code.
>fact 3: Sun's JDK compiles source code to byte-code.
>fact 4: Sun's JDK executes this byte-code.
>
>Care to prove me wrong on any of these points ? Don't bother: you can't. 
>So my first assertion that "CPython is compiled to byte-code, which is 
>then executed by a VM" is true, and since the same assertion also stands 
>for Java (ie: sun's JDK), then the "just like" qualifier is true too. 
>Period.

No, the "just like" qualifier is false.  Python doesn't compile "just
like" Java, nor does it execute "just like" Java.  The "byte-code"
langauges are very different and they perform much differently.
Java compiles slower but executes faster.  Python's byte-code is ment to
quickly generated on the fly to save having to reparse the source code.
Java code is compiled using optimizations into a virtual machine languague
ment to be executed as fast as possible on a wide range of processors.
The similarities between the two are superficial, Python doesn't compile
and execute code "just like" Java.

Try all you want to try to reparse what you wrote in to a different
meaning, it doesn't change the fact your intent was to mislead.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


SQLObject 0.10.0b1

2008-01-11 Thread Oleg Broytmann
Hello!

I'm pleased to announce the 0.10.0b1, the first beta release of a new
SQLObject branch, 0.10.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and
Firebird.  It also has newly added support for Sybase, MSSQL and MaxDB (also
known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.10.0b1

News and changes:
http://sqlobject.org/News.html


What's New
==

Features & Interface


* Dropped support for Python 2.2. The minimal version of Python for
  SQLObject is 2.3 now.

* Removed actively deprecated attributes;
  lowered deprecation level for other attributes to be removed after 0.10.

* SQLBuilder Select supports the rest of SelectResults options (reversed,
  distinct, joins, etc.)

* SQLObject.select() (i.e., SelectResults) and DBConnection.queryForSelect()
  use SQLBuilder Select queries; this make all SELECTs implemented
  internally via a single mechanism.

* SQLBuilder Joins handle SQLExpression tables (not just str/SQLObject/Alias)
  and properly sqlrepr.

* SQLBuilder tablesUsedDict handles sqlrepr'able objects.

* Added SQLBuilder ImportProxy. It allows one to ignore the circular import
  issues with referring to SQLObject classes in other files - it uses the
  classregistry as the string class names for FK/Joins do, but specifically
  intended for SQLBuilder expressions. See
  tests/test_sqlbuilder_importproxy.py.

* Added SelectResults.throughTo. It allows one to traverse relationships
  (FK/Join) via SQL, avoiding the intermediate objects. Additionally, it's
  a simple mechanism for pre-caching/eager-loading of later FK
  relationships (i.e., going to loop over a select of somePeople and ask
  for aPerson.group, first call list(somePeople.throughTo.group) to preload
  those related groups and use 2 db queries instead of N+1). See
  tests/test_select_through.py.

* Added ViewSQLObject.

* Added sqlmeta.getColumns() to get all the columns for a class (including
  parent classes), excluding the column 'childName' and including the column
  'id'. sqlmeta.asDict() now uses getColumns(), so there is no need to
  override it in the inheritable sqlmeta class; this makes asDict() to work
  properly on inheritable sqlobjects.

* Changed the implementation type in BoolCol under SQLite from TINYINT to
  BOOLEAN and made fromDatabase machinery to recognize it.

* Added rich comparison methods; SQLObjects of the same class are
  considered equal is they have the same id; other methods return
  NotImplemented.

* MySQLConnection (and DB URI) accept a number of SSL-related parameters:
  ssl_key, ssl_cert, ssl_ca, ssl_capath.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[EMAIL PROTECTED]
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Windows build of Yapgvb Python extension

2008-01-11 Thread Mike
On Jan 11, 8:41 am, Lonnie Princehouse <[EMAIL PROTECTED]>
wrote:
> I'm the author of Yapgvb, a Python binding for Graphviz.  Yapgvb
> enjoys modest success, but for some time it has been in dire need of a
> Python 2.5 build for Windows. I'm posting this message in the hopes of
> finding someone who is interested in making this build.
>
> This is a relatively quick task for someone who is comfortable with
> building C extensions and has an operational Windows build environment
> for Python 2.5 (which I don't).  Alternately, it's a great way to
> learn about these things, and to get involved with a small open source
> project.
>
> Technologies used:
>   graphviz
>   distutils
>   boost.python
>   boost.graph
>
> See:http://yapgvb.sourceforge.net

What do you need exactly? One of those executables created using bdist
or are you going for the msi?

I usually attempt to create these things doing

python setup.py bdist_wininst

...for executable installers.

If you can provide a valid setup.py, I can probably create the exe/
msi.

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Scons

2008-01-11 Thread Hyuga
On Jan 11, 5:20 am, anush <[EMAIL PROTECTED]> wrote:
> Can anybody tell how I could go about running python scripts with
> scons.

Have you tried reading the SCons user guide (http://www.scons.org/doc/
production/HTML/scons-user.html)?  It's actually pretty good.
I'm not too clear on what you're asking though.  SCons scripts are
written in Python (as is SCons itself)...

Hyuga
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Chris Mellon
On Jan 11, 2008 9:10 AM, George Sakkis <[EMAIL PROTECTED]> wrote:
> On Jan 11, 8:59 am, Bruno Desthuilliers 
> [EMAIL PROTECTED]> wrote:
> > George Sakkis a écrit :
> >
> >
> >
> > > On Jan 11, 4:12 am, Bruno Desthuilliers  > > [EMAIL PROTECTED]> wrote:
> >
> > >> George Sakkis a écrit :
> >
> > >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote:
> >  I fail to see how the existence of JIT compilers in some Java VM 
> >  changes
> >  anything to the fact that both Java (by language specification) and
> >  CPython use the byte-code/VM scheme.
> > >>> Because these "some Java VMs" with JIT compilers are the de facto
> > >>> standard used by millions;
> > >> Repeating an argument doesn't make it more true nor more relevant. Once
> > >> again, this doesn't change anything to the fact exposed above.
> >
> > >>> the spec is pretty much irrelevant
> > >> I mentionned this because this kind of choice is usually not part of the
> > >> language spec but of a specific implementation. Java is AFAIK the only
> > >> language where this implementation stuff is part of the spec.
> >
> > >>> (unless
> > >>> you're a compiler writer or language theorist).
> > >> I thought it was quite clear and obvious that I was talking about points
> > >> relating to these fields.
> >
> > > No it wasn't,
> >
> > """
> >  > or is Python just too slow
> >  > as an interpreted language
> >
> > Being "interpreted" is a quality of an implementation, not of a language.
> > """
> > If that isn't clear enough what I'm talking about, then sorry but I
> > can't help.
>
> Pedantic once again. For languages with a single (or practically
> single) implementation such as Python, the average user couldn't care
> less about the distinction. Your point might have more merit if
> PyPy or IronPython or Jython enter the same league with CPython in
> terms of usage.
>
> > >  and besides the OP is most likely interested in these as
> > > a simple user so the distinction between a spec and a de facto
> > > standard implementation (such as JDK for Java and CPython for Python)
> > > are almost pedantic if not misleading.
> >
> > I can live with being called "pedantic" - even I'm not sure whether
> > correcting a wrong statement about CPython's execution model is pedantic
> > or not. But I *still* fail to see how it could be "misleading", and
> > *you* still fail to explain in which way it could be misleading.
> >
> > If your point is that saying that CPython uses a byte-code/VM scheme
> > "just like Java" necessarily implies JIT compilation just because some
> > JVM support this feature, then it would be time you pay more attention
> > to what is effectively written.
>
> What three different people in this thread have been trying to tell
> you but you seem to miss is that claiming CPython's VM "is just like
> Java" is comparable to saying "a Yugo's car engine is just like a
> BMW's" (or "humans are just like chimpanzees"), which for some value
> of "just like" is technically correct but it's not what most people
> would call an accurate statement.
>

The statement was in response to a claim that Python was slow because
it is interpreted. This is a little like correcting someone who says
that a Yugo is slow because it has a steam engine by telling that no,
it's internal combustion, just like the BMW has.

It's possible for this a claim like this to lead to a clarifying and
informative discussion about JIT technology and how it improves Javas
performance, and the use of corresponding techniques in Python. What
we got instead was someone who felt some sort of juvenile urge to jump
all over a what he thought of as a claim that Python is as fast as
Java (which, of course, it sometimes is - the issue is more
complicated than a sound bite).

> > >  We're not Lisp (yet ;-)), with
> > > five major implementations and a dozen of minor ones.
> >
> > And ? In which way does it make the distinction between a language and a
> > language implementation less true ?
>
> In the way that most plain users care (or not) about.

Not that I think any of you care about anything except your e-penis at
this point, but there is no reason to proscribe discussion to only
what "plain users" want, even if the OP was such a person.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: python recursive function

2008-01-11 Thread Reedick, Andrew


> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Tom_chicollegeboy
> Sent: Friday, January 11, 2008 3:30 AM
> To: python-list@python.org
> Subject: python recursive function
> 
> Now, you are to write a program that, if I give you n bears, returns
> true if it is at all possible for you to win the game. Your program
> must use recursion to check all possible ways in which you can apply
> the rules.
> 

> if n==42:
> return True

> return False

You have to check for all possible paths.  Returning True/False is
futile since the recursive chains will be returning a mix of true and
false.  Use a global variable to indicate if a solution is found.  (Or
pass the flag in using a list, since lists are passed by reference (if n
== 42: found_it[0] = True; return.)

There's also another teaching exercise in here.  Do you follow the
literal directions ('check all possible ways') and generate all possible
paths?  Or do you 'interpret' that to mean try all possible paths until
you find a solution?  (i.e. do you short circuit the recursion once you
have a solution?)

One of the most difficult things about programming is conveying the
requirements from Human A to Human Programmer B.  This is especially
difficult since business people and techies speak different languages
and, more importantly, think differently (different assumptions,
different paradigms, different levels of hand-waving away of details,
etc..)  And don't get me started about the people in marketing...



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


-- 
http://mail.python.org/mailman/listinfo/python-list


MFC app to Python IDLE communication

2008-01-11 Thread konstantin . smolin
Hi all
In my MFC application I need to call Python IDLE, pass some terms (or
scripts or values - they are simple strings or memo fields) there so
that user may modify/evaluate/interpret it and then return the
modified terms back to the application.

How can I do it the best way (MFC->IDLE)?

As for IDLE->MFC, I'm afraid that copy-paste is the way out... Is it
so?

Thanks in advance for the hints.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread George Sakkis
On Jan 11, 8:59 am, Bruno Desthuilliers  wrote:
> George Sakkis a écrit :
>
>
>
> > On Jan 11, 4:12 am, Bruno Desthuilliers  > [EMAIL PROTECTED]> wrote:
>
> >> George Sakkis a écrit :
>
> >>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote:
>  I fail to see how the existence of JIT compilers in some Java VM changes
>  anything to the fact that both Java (by language specification) and
>  CPython use the byte-code/VM scheme.
> >>> Because these "some Java VMs" with JIT compilers are the de facto
> >>> standard used by millions;
> >> Repeating an argument doesn't make it more true nor more relevant. Once
> >> again, this doesn't change anything to the fact exposed above.
>
> >>> the spec is pretty much irrelevant
> >> I mentionned this because this kind of choice is usually not part of the
> >> language spec but of a specific implementation. Java is AFAIK the only
> >> language where this implementation stuff is part of the spec.
>
> >>> (unless
> >>> you're a compiler writer or language theorist).
> >> I thought it was quite clear and obvious that I was talking about points
> >> relating to these fields.
>
> > No it wasn't,
>
> """
>  > or is Python just too slow
>  > as an interpreted language
>
> Being "interpreted" is a quality of an implementation, not of a language.
> """
> If that isn't clear enough what I'm talking about, then sorry but I
> can't help.

Pedantic once again. For languages with a single (or practically
single) implementation such as Python, the average user couldn't care
less about the distinction. Your point might have more merit if
PyPy or IronPython or Jython enter the same league with CPython in
terms of usage.

> >  and besides the OP is most likely interested in these as
> > a simple user so the distinction between a spec and a de facto
> > standard implementation (such as JDK for Java and CPython for Python)
> > are almost pedantic if not misleading.
>
> I can live with being called "pedantic" - even I'm not sure whether
> correcting a wrong statement about CPython's execution model is pedantic
> or not. But I *still* fail to see how it could be "misleading", and
> *you* still fail to explain in which way it could be misleading.
>
> If your point is that saying that CPython uses a byte-code/VM scheme
> "just like Java" necessarily implies JIT compilation just because some
> JVM support this feature, then it would be time you pay more attention
> to what is effectively written.

What three different people in this thread have been trying to tell
you but you seem to miss is that claiming CPython's VM "is just like
Java" is comparable to saying "a Yugo's car engine is just like a
BMW's" (or "humans are just like chimpanzees"), which for some value
of "just like" is technically correct but it's not what most people
would call an accurate statement.

> >  We're not Lisp (yet ;-)), with
> > five major implementations and a dozen of minor ones.
>
> And ? In which way does it make the distinction between a language and a
> language implementation less true ?

In the way that most plain users care (or not) about.

George
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop without variable

2008-01-11 Thread Paul Rubin
Fredrik Lundh <[EMAIL PROTECTED]> writes:
> (and if you use sane naming conventions, the risk for collisions is
> near zero as well).

I haven't felt that way, I'm always worried about clobbering something
by leaking a variable.  Maybe collisions don't really happen much, but
it's always seemed cleaner to me to use the most restricted scopes
possible just to minimize or eliminate the possibility.  This is
especially attractie in a language like Python, with no declarations
and no compile-time type safety.
-- 
http://mail.python.org/mailman/listinfo/python-list


Define installation directory for python

2008-01-11 Thread HajoEhlers
Task:
build and install python 2.5.1 on AIX  5.3 to /opt/python2.5 with the
subdirectories:
./lib
./bin
./include
./man
./info

a.s.o

The ./bin ./man are created fine but for ./lib & ./include  the
structure is
  /opt/python2.5/lib/python2.5
 /opt/python2.5/include/python2.5
 where  i would like to have only /opt/python2.5/lib and /opt/
python2.5/include

Looking at the make install output i see that setup.py is using a
option called
--install-platlib
but how do i set this option during configure ? Or do i have to patch
the setup.py ?

Any hints
tia
Hajo
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for loop without variable

2008-01-11 Thread Fredrik Lundh
Paul Rubin wrote:

> it just seems way too obscure though.  Python style seems to favor
> spewing extra variables around.

that's because (local) variables have near-zero cost, and zero overhead. 
  use as many as you want, and reuse them as often as you want to.

(and if you use sane naming conventions, the risk for collisions is near 
zero as well).



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread George Sakkis
On Jan 11, 4:12 am, Bruno Desthuilliers  wrote:

> George Sakkis a écrit :
>
> > On Jan 10, 3:37 am, Bruno Desthuilliers wrote:
>
> >> I fail to see how the existence of JIT compilers in some Java VM changes
> >> anything to the fact that both Java (by language specification) and
> >> CPython use the byte-code/VM scheme.
>
> > Because these "some Java VMs" with JIT compilers are the de facto
> > standard used by millions;
>
> Repeating an argument doesn't make it more true nor more relevant. Once
> again, this doesn't change anything to the fact exposed above.
>
> > the spec is pretty much irrelevant
>
> I mentionned this because this kind of choice is usually not part of the
> language spec but of a specific implementation. Java is AFAIK the only
> language where this implementation stuff is part of the spec.
>
> > (unless
> > you're a compiler writer or language theorist).
>
> I thought it was quite clear and obvious that I was talking about points
> relating to these fields.

No it wasn't, and besides the OP is most likely interested in these as
a simple user so the distinction between a spec and a de facto
standard implementation (such as JDK for Java and CPython for Python)
are almost pedantic if not misleading. We're not Lisp (yet ;-)), with
five major implementations and a dozen of minor ones.

George
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: module finalizer - is there such a beast?

2008-01-11 Thread Peter Otten
Helmut Jarausch wrote:

> But how can I get control when the module gets unloaded
> either by Python's gc, Python's exit or by a module reload.

Here's a simple approach using the finalizer of an object in the module's
globals():

$ cat nirvana.py
class Exit(object):
def __del__(self):
print "exiting", __name__

exit_watch = Exit()
$ python
Python 2.5.1 (r251:54863, May  2 2007, 16:56:35) 
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nirvana
>>> reload(nirvana)
exiting nirvana

>>> 
exiting None
$

But don't trust it too much and don't try to access other global objects.
These may already be set to None as demonstrated above.

Peter
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HOW TO HANDLE POINTERS FROM NON-LOCAL HEAPS??

2008-01-11 Thread James Matthews
Ahh it's good to know that you "love" pointers like everyone else!

On Jan 11, 2008 9:30 AM, Gary Herron <[EMAIL PROTECTED]> wrote:
> abhishek wrote:
> > Hi group any idea on HOW  TO HANDLE POINTERS FROM NON-LOCAL HEAPS??
> >
> >
> > Thank you
> >
> POINTERS?   Heaps?   Huh?   Ummm, let me think -- those terms *do* sound
> vaguely familiar -- from sometime in the deep dark primitive past.
> Perhaps from back in my (shudder) C/C++ days -- ya, that's it.
> Thankfully, this is Python and the modern era -- we don't use no
> stinking POINTERS here.
>
> Seriously, this group deals with Python.  There are no pointers in
> Python.  Now please, what did you *really* mean to ask?
>
> Gary Herron
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread George Sakkis
On Jan 11, 9:41 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Bruno Desthuilliers <[EMAIL PROTECTED]>
> writes:
>
> > fact 1: CPython compiles source code to byte-code.
> > fact 2: CPython executes this byte-code.
> > fact 3: Sun's JDK compiles source code to byte-code.
> > fact 4: Sun's JDK executes this byte-code.
>
> > Care to prove me wrong on any of these points ? Don't bother: you
> > can't.
>
> Fact 4 is misleading because it is only one option available to Sun's
> JDK.  Sun's JDK is also capable of transforming the byte-code to
> native code and letting the processor execute that instead of the
> original byte code, and that is where the most significant speed
> increase comes from.  Most importantly, it does so automatically, by
> default, with no programmer intervention or configuration, and with
> 100% compatibility, so it doesn't compare well to Python accelerators
> like psyco.

Plus, IIRC Java's JIT is not limited to optimizing special cases,
while psyco helps primarily with number-crunching code (admittedly an
important special case) and can have zero or even (small) negative
effect on arbitrary Python programs.

George
-- 
http://mail.python.org/mailman/listinfo/python-list


scope question in a switch mixin

2008-01-11 Thread browerg
The code that follows is the result of noodling around with switches as a 
learning tool. I've played with python for a few years, but I'm self-taught, so 
. . .

Class Switch builds a set of functions. Method switch executes one of them 
given a value of the switch variable.

My question is, why are modules imported at the top of the program not visible 
to the functions Switch builds? There is
no problem when the import is in the function, but I thought initially that 
imports at the top would be in its globals.

The import that works is at line 111 in the code.

Thanks in advance!

George

'''Mixin Switch provides function switch(key) that executes an appropriate 
function.

   Each instance can: use a different switch variable.
  be used as many places in a program as desirable.
  be changed in one place, no matte how many places it is 
used.

   Usage: inst = Switch(keys, vals, base)
   whose arguments are sequenes:
   keys has switch values ('su', 'mo', . . .),
   base has the shared fore and aft parts of instance functions, and
   vals has the individual parts of instane functions.

   Example: Suppose you want to switch on days of the week:
keys = ('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa', 'de')
vals = ('Sundayis Comic-day.', 'Mondayis Moan-day.',
'Tuesday   is Twos-day.',  'Wednesday is Hump-day.',
'Thursday  is Shop-day.',  'Fridayis TGIF-day.',
'Saturday  is Food-day.',  'Anything else is Party-day!')
fore = "def %s(self, *args):\n\tprint '"
aft  = "'\\n"

produces functions of the form:
def su(self, *args):\\n\\tprint 'Sundayis Comic-day.'\\n
or, for humans:
def su(self, *args):
print 'Sundayis Comic-day.'

Test code (below) for this example produces:
Sundayis Comic-day.
Mondayis Moan-day.
. . .
Anything else is Party-day!
key {}  keys must be hashable (immutable) objects.

   Example: Suppose you want to swith on a function and its argument.
Test code (below) returns calculated values using functions like:
def %s(self, *args):\\n\\timport math\\n\\ttmp = (args[0] / 
math.pi)\\n\\treturn tmp\\n
or, for humans:
def %s(self, *args):
import math
tmp = (args[0] / math.pi)
return tmp
that produce:
In toplevel: circ.switch(dC,10), d = 3.18309886184
In toplevel: circ.switch(Cd,  3.18), C = 9.99026463842
In toplevel: circ.switch(rC, 5), r = 0.795774715459
In toplevel: circ.switch(Cr, 0.796), C = 5.00141550451
In toplevel: circ.switch(A , 5), A = 78.5398163397

   Thanks to Jean-Paul Calderone for his post at
   http://mail.python.org/pipermail/python-list/2007-June/446648.html
   in response to a question by vasudevrama t
   http://mail.python.org/pipermail/python-list/2007-June/446618.html
   '''

#import math

class Switch(object):

   def __init__(self, keys, vals, base):
   self.dictionary = {}
   tmpd = {}
   for i in range(len(vals)):
   func = ''.join([base[0] % keys[i], vals[i], base[1]])
   compile(func, '', 'exec')
   exec(func, tmpd)
   for k, v in tmpd.items():
   if k in keys:
   self.dictionary[k] = v

   def switch(self, key, *args, **kwargs):
   try:
   result = self.dictionary[key](self, *args, **kwargs)
   except KeyError:
   result = self.dictionary['de'](self, *args, **kwargs)
   return result

if '__main__' == __name__:
   '''Case 1: execute a statement.
   '''
   keys = ('su', 'mo', 'tu', 'we', 'th', 'fr', 'sa', 'de')
   vals = ('Sundayis Comic-day.', 'Mondayis Moan-day.',
   'Tuesday   is Twos-day.',  'Wednesday is Hump-day.',
   'Thursday  is Shop-day.',  'Fridayis TGIF-day.',
   'Saturday  is Food-day.',  'Anything else is Party-day!')
   fore = "def %s(self, *args):\n\tprint '"
   aft  = "'\n"
   base = (fore, aft)
   day = Switch(keys, vals, base)
   for k in keys:
   try:
   day.switch(k)
   except TypeError:
   print 'key %s %s keys must be hashable (immutable) objects.' % (k, 
type(k))
   for k in ('xx', 1234, 12.3, {}):
   try:
   day.switch(k)
   except TypeError:
   print 'key %s %s keys must be hashable (immutable) objects.' % (k, 
type(k))

   '''Case 2: execute an expression.
   '''
   keys = ('dC', 'Cd', 'rC', 'Cr', 'A', 'de')
   vals = ("(args[0] / math.pi)",   # diameter given Circumference
   "(math.pi * args[0])",   # Circumferene given diameter
   "(args[0] / (2 * 

Using eggs

2008-01-11 Thread oj
Hi all!

As is about to become apparent, I really don't know what I'm doing
when it comes to using eggs.

I'm writing some software that is going to be deployed on a machine as
a number of eggs. Which is all well and good.

These eggs all end up depending on each other; modules in egg A want
to import modules in egg B etc.

It's not really practical to add the path to each individual egg to
the PYTHONPATH (although there's all in a directory that is in
PYTHONPATH).

Do I have to add boiler-plate code to the beginning of all the modules
with these dependencies to check if modules are available and require
the eggs if they aren't? Or is there a way I can have stuff 'just
work' as it does in the development environment when the modules
haven't been bundled up into eggs?

On a similar note, I can't seem to get the automatic script creation
stuff in setuptools to create scripts that have additional
requirements. I tried defining extra requires giving the names of
other eggs that will be required, and then specifying these as extras
to the console_scripts, but the generated scripts were no different.
Am I doing something wrong? Or am I just not understanding something?

I'm muddling through getting this all working at the moment, but I get
the distinct impression that there's a better (correct?) way that I'm
not aware of.

Sorry for such a vague posting.

-Oli
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does **kw mean?

2008-01-11 Thread [EMAIL PROTECTED]
On Jan 11, 12:24 pm, Lie <[EMAIL PROTECTED]> wrote:
> On Jan 11, 4:38 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
> > I've been reading the following example, and couldn't figure out, what
> > **kw mean. (It's an empty dictionary, but what's the semantics):
>
> It's a keyword argument. It's some kind of repository for arguments
> that aren't recognized.
>
> If you have function like this:
> def func(a, *args, *kw):
> print a
> print args
> print kw
>
> and you call the functin like this:
> func('value A', 'value B', 'value C', argumentA = 'value D', argumentB
> = 'value D')
> the extra arguments would normally raise an error, but with the * and
> **, Python would:
> - assign 'value B' and 'value C' to args
> - assign 'argumentA':'value D' and 'argumentB':'value E' to kw
>
> so if you run the function, it will output:
> 
> value A
> ('value B', 'value C')
> {'argumentB': 'value E', 'argumentA': 'value D'}
> 
>
> this args and kw can be accessed like a tuple and dictionary
> respectively
>
> See '4.7.2 Keyword Arguments' and '4.7.3 Arbitrary Argument Lists' on
> Python Help File

Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Analyzing Python GC output - what is a "cell", and what information is available about it.

2008-01-11 Thread John Nagle
Duncan Booth wrote:
> John Nagle <[EMAIL PROTECTED]> wrote:
> 
>> I'm printing out each entry in "gc.garbage" after a garbage collection in
>> DEBUG_LEAK mode, and I'm seeing many entries like
>>
>> 
>>
>> That's the output of "repr".   Are "cell" objects created only from
>> external C libraries, or can regular Python code generate them?  Is there
>> any way to find out what the 'function object' is from within Python?
>>
> Cell objects are created whenever you have a function that references a 
> variable in an outer scope. e.g.
> 
> So in your case, cell.cell_contents.func_name might help.

Tried that:

print repr(item).encode('ascii','replace')  
print "Type:",type(item)
try:
print item.cell_contents
except Exception, message:
print "Unprintable:",message


Type: 
Unprintable: 'cell' object has no attribute 'cell_contents'

So it doesn't have a "cell_contents" attribute.

Tried:
print item.dir()
got:
'cell' object has no attribute 'dir'

Tried:
print item.__dict__
got:
'cell' object has no attribute '__dict__'

It looks like this is a low-level PyCellObject not generated from Python code.
Any ideas?  I'm using the M2Crypto and MySQLdb libraries, and suspect
a reference count bug in one of those.

John Nagle
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with Windows build of Yapgvb Python extension

2008-01-11 Thread Lonnie Princehouse
On Jan 11, 9:44 am, Mike <[EMAIL PROTECTED]> wrote:
> On Jan 11, 8:41 am, Lonnie Princehouse <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > I'm the author of Yapgvb, a Python binding for Graphviz.  Yapgvb
> > enjoys modest success, but for some time it has been in dire need of a
> > Python 2.5 build for Windows. I'm posting this message in the hopes of
> > finding someone who is interested in making this build.
>
> > This is a relatively quick task for someone who is comfortable with
> > building C extensions and has an operational Windows build environment
> > for Python 2.5 (which I don't).  Alternately, it's a great way to
> > learn about these things, and to get involved with a small open source
> > project.
>
> > Technologies used:
> >   graphviz
> >   distutils
> >   boost.python
> >   boost.graph
>
> > See:http://yapgvb.sourceforge.net
>
> What do you need exactly? One of those executables created using bdist
> or are you going for the msi?
>
> I usually attempt to create these things doing
>
> python setup.py bdist_wininst
>
> ...for executable installers.
>
> If you can provide a valid setup.py, I can probably create the exe/
> msi.
>
> Mike


Yes, a bdist_wininst installer is what I had in mind.  MSI would be
fine, too --- whichever is easier.

If anyone wants to have a look, there's a README file that details
what I did to build yapgvb for Python 2.4.

The source is available from anonymous subversion:

   svn co https://yapgvb.svn.sourceforge.net/svnroot/yapgvb yapgvb

and is also web-browseable, http://yapgvb.svn.sourceforge.net/viewvc/yapgvb/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using eggs

2008-01-11 Thread Mike
On Jan 11, 10:33 am, oj <[EMAIL PROTECTED]> wrote:
> Hi all!
>
> As is about to become apparent, I really don't know what I'm doing
> when it comes to using eggs.
>
> I'm writing some software that is going to be deployed on a machine as
> a number of eggs. Which is all well and good.
>
> These eggs all end up depending on each other; modules in egg A want
> to import modules in egg B etc.
>
> It's not really practical to add the path to each individual egg to
> the PYTHONPATH (although there's all in a directory that is in
> PYTHONPATH).
>
> Do I have to add boiler-plate code to the beginning of all the modules
> with these dependencies to check if modules are available and require
> the eggs if they aren't? Or is there a way I can have stuff 'just
> work' as it does in the development environment when the modules
> haven't been bundled up into eggs?
>
> On a similar note, I can't seem to get the automatic script creation
> stuff in setuptools to create scripts that have additional
> requirements. I tried defining extra requires giving the names of
> other eggs that will be required, and then specifying these as extras
> to the console_scripts, but the generated scripts were no different.
> Am I doing something wrong? Or am I just not understanding something?
>
> I'm muddling through getting this all working at the moment, but I get
> the distinct impression that there's a better (correct?) way that I'm
> not aware of.
>
> Sorry for such a vague posting.
>
> -Oli

I know when I've asked questions about eggs and setup-tools, I was
referred to the Distutils user group. I would cross-post there for
double the fun!

http://mail.python.org/mailman/listinfo/distutils-sig

Mike
-- 
http://mail.python.org/mailman/listinfo/python-list


virtualpython / workingenv / virtualenv ... shouldn't this be part of python

2008-01-11 Thread Damjan
There are several attempts to allow python to work with per user (or even
per session) 'site-packages' like virtualpython / workingenv / virtualenv.

But they all have their own shortcomings and quirks.

My question is, shoudn't it be enough to set PYTHONPATH and everything
automagically to work then? Is there some work done on this for python 3.0
or 2.6 perhaps?


-- 
damjan
-- 
http://mail.python.org/mailman/listinfo/python-list


ftplib question (cannot open data connection)

2008-01-11 Thread Laszlo Nagy

  Hi All,

I'm using a simple program that uploads a file on a remote ftp server. 
This is an example (not the whole program):


def store(self,hostname,username,password,destdir,srcpath):
self.ftp = ftplib.FTP(hostname)
self.ftp.login(username,password)
self.ftp.set_pasv(False)
self.ftp.cwd(destdir)
fobj = file(srcpath,"rb")
destname = os.path.split(srcpath)[1]
self.ftp.storbinary("STOR "+destname,fobj)


The ftp server cannot use passive connections, and I can do nothing 
about that. Here is the problem: I can connect to this ftp server from 
my home computer, which is behind a NAT firewall. I can also connect to 
it from another computer, but I'm not able to upload any file. I tried 
to debug with a simple "ftp -v -d" command line program and apparently 
the problem is with the "EPRT" command:

ftp> ls
---> EPRT |1|195.228.74.135|55749|
200 Port command successful.
---> LIST
425 Cannot open data connection.
ftp>

Well, the port number given by EPRT is bad - it is a closed port on this 
computer. I can open a small port range for this, but I would not like 
to open all ports and disable the firewall completely.

Here are my questions:

1. How can I instruct ftplib to use specific ports for incoming 
connections? (For example, ports between 55000 and 56000).
2. How it is possible that the same program works from another computer 
that is behind a NAT firewall?

Thanks,

   Laszlo

-- 
http://mail.python.org/mailman/listinfo/python-list


newbie question regarding int(input(:))

2008-01-11 Thread Craig Ward
Hi experts!
I am trying to write a menu script that will execute bash scripts.
Everything is fine until the script executes and I want to see if there are
any more options to run before quitting. Example:

def menu(opt1 = "something", opt2 = "something else"):


-- 
Computers are like air conditioners.
They stop working when you open Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: alternating string replace

2008-01-11 Thread Paddy
On Jan 11, 9:31 am, [EMAIL PROTECTED] wrote:
> evenOrOdd = True
> s1, s2 = "hi_cat_bye_dog_foo_bar_red", ""
>
> for i in s1:
>if i == '_':
>s2 += ':' if evenOrOdd else ','
>evenOrOdd = not evenOrOdd
>else:
>s2 += i
>
> print s2
>
> Presently I cannot work out how to use .join instead of += ...
Do
s2 = []
then later: s2.append(i)

and at the end: print ''.join(s2)


- Paddy.

> While I realise this is producing a new string (and I believe +=
> rebuilds it a lot?) how much slower
> is this going to be over the others?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Bruno Desthuilliers
George Sakkis a écrit :
> On Jan 11, 4:12 am, Bruno Desthuilliers  [EMAIL PROTECTED]> wrote:
> 
>> George Sakkis a écrit :
>>
>>> On Jan 10, 3:37 am, Bruno Desthuilliers wrote:
 I fail to see how the existence of JIT compilers in some Java VM changes
 anything to the fact that both Java (by language specification) and
 CPython use the byte-code/VM scheme.
>>> Because these "some Java VMs" with JIT compilers are the de facto
>>> standard used by millions;
>> Repeating an argument doesn't make it more true nor more relevant. Once
>> again, this doesn't change anything to the fact exposed above.
>>
>>> the spec is pretty much irrelevant
>> I mentionned this because this kind of choice is usually not part of the
>> language spec but of a specific implementation. Java is AFAIK the only
>> language where this implementation stuff is part of the spec.
>>
>>> (unless
>>> you're a compiler writer or language theorist).
>> I thought it was quite clear and obvious that I was talking about points
>> relating to these fields.
> 
> No it wasn't,

"""
 > or is Python just too slow
 > as an interpreted language

Being "interpreted" is a quality of an implementation, not of a language.
"""

If that isn't clear enough what I'm talking about, then sorry but I 
can't help.

>  and besides the OP is most likely interested in these as
> a simple user so the distinction between a spec and a de facto
> standard implementation (such as JDK for Java and CPython for Python)
> are almost pedantic if not misleading.

I can live with being called "pedantic" - even I'm not sure whether 
correcting a wrong statement about CPython's execution model is pedantic 
or not. But I *still* fail to see how it could be "misleading", and 
*you* still fail to explain in which way it could be misleading.

If your point is that saying that CPython uses a byte-code/VM scheme 
"just like Java" necessarily implies JIT compilation just because some 
JVM support this feature, then it would be time you pay more attention 
to what is effectively written.

>  We're not Lisp (yet ;-)), with
> five major implementations and a dozen of minor ones.

And ? In which way does it make the distinction between a language and a 
language implementation less true ?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Frontend/GUI for C Program

2008-01-11 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> I have a C program that works very well. However, being C it has no
> GUI. Input and Output are stdin and stdout... works great from a
> terminal. Just wondering, has anyone every written a Python GUI for an
> existing C program? Any notes or documentation available?
> 
> I have experience using wxPython from within Python apps and I like it
> a lot for its cross-platform capabilities. I was hoping to use
> wxPython for this as well.

Modules subprocess and pexpect (3rd-party-package) are your friends. 
Alternatively, if you have the source for the C-app, exposing it's 
functionality as DLL/SO and using ctypes as means to access it might 
work as well.

Diez
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Frontend/GUI for C Program

2008-01-11 Thread byte8bits
I have a C program that works very well. However, being C it has no
GUI. Input and Output are stdin and stdout... works great from a
terminal. Just wondering, has anyone every written a Python GUI for an
existing C program? Any notes or documentation available?

I have experience using wxPython from within Python apps and I like it
a lot for its cross-platform capabilities. I was hoping to use
wxPython for this as well.

Thanks,
Brad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading a specific column from file

2008-01-11 Thread Fredrik Lundh
cesco wrote:

> I have a file containing four columns of data separated by tabs (\t)
> and I'd like to read a specific column from it (say the third). Is
> there any simple way to do this in Python?

use the "split" method and plain old indexing:

for line in open("file.txt"):
 columns = line.split("\t")
 print columns[2] # indexing starts at zero

also see the "csv" module, which can read all sorts of 
comma/semicolon/tab-separated spreadsheet-style files.

> I've found quite interesting the linecache module

the "linecache" module seems to be quite popular on comp.lang.python 
these days, but it's designed for a very specific purpose (displaying 
Python code in tracebacks), and is a really lousy way to read text files 
in the general case.  please unlearn.



-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Magic function

2008-01-11 Thread oj
On Jan 11, 4:29 pm, [EMAIL PROTECTED] wrote:
> Hi all,
>
> I'm part of a small team writing a Python package for a scientific
> computing project. The idea is to make it easy to use for relatively
> inexperienced programmers. As part of that aim, we're using what we're
> calling 'magic functions', and I'm a little bit concerned that they
> are dangerous code. I'm looking for advice on what the risks are (e.g.
> possibility of introducing subtle bugs, code won't be compatible with
> future versions of Python, etc.).
>
> Quick background: Part of the way our package works is that you create
> a lot of objects, and then you create a new object which collects
> together these objects and operates on them. We originally were
> writing things like:
>
> obj1 = Obj(params1)
> obj2 = Obj(params2)
> ...
> bigobj = Bigobj(objects=[obj1,obj2])
> bigobj.run()
>
> This is fine, but we decided that for clarity of these programs, and
> to make it easier for inexperienced programmers, we would like to be
> able to write something like:
>
> obj1 = Obj(params1)
> obj2 = Obj(params2)
> ...
> run()
>
> The idea is that the run() function inspects the stack, and looks for
> object which are instances of class Obj, creates a Bigobj with those
> objects and calls its run() method.
>
> So, any comments on that approach?
>
> I'm including the code I've written to do this, and if you have time
> to look through it, I'd also be very grateful for any more specific
> comments about the way I've implemented it (in particular, can it be
> made faster, is my program creating cycles that stop the garbage
> collection from working, etc.). I hope the code will be formatted
> correctly:
>
> def
> getInstances(instancetype,level=1,includeglobals=True,containersearchdepth=1,exclude={},predicate=lambda
> x:True):
> """Find all instances of a given class at a given level in the
> stack
> """
> vars = {}
> # Note: we use level+1 because level refers to the level relative
> to the function calling this one
> if includeglobals: vars.update(stack()[level+1][0].f_globals)
> vars.update(stack()[level+1][0].f_locals)
> # Note that you can't extract the names from vars.itervalues() so
> we provide via knownnames the names vars.iterkeys(),
> # containersearchdepth+1 is used because vars.itervalues() is the
> initial container from the point of view of this
> # function, but not from the point of view of the person calling
> getInstances
> objs, names =
> extractInstances(instancetype,vars.itervalues(),containersearchdepth
> +1,knownnames=vars.iterkeys(),exclude=exclude,predicate=predicate)
> return (objs,names)
>
> def
> extractInstances(instancetype,container,depth,containingname='vars()',knownnames=None,exclude={},predicate=lambda
> x:True):
> if depth<=0: return ([],[])
> if isinstance(container,str): return ([],[]) # Assumption: no need
> to search through strings
> # Ideally, this line wouldn't be here, but it seems to cause
> programs to crash, probably because
> # some of the simulator objects are iterable but shouldn't be
> iterated over normally
> # TODO: Investigate what is causing this to crash, and possibly
> put in a global preference to turn this line off?
> if not isinstance(container,
> (list,tuple,dict,type({}.itervalues(: return ([],[])
> # Note that knownnames is only provided by the initial call of
> extractInstances and the known
> # names are from the dictionary of variables. After the initial
> call, names can only come from
> # the __name__ attribute of a variable if it has one, and that is
> checked explicitly below
> if knownnames is None:
> knewnames = False
> knownnames = repeat(containingname)
> else:
> knewnames = True
> objs = []
> names = []
> try: # container may not be a container, if it isn't, we'll
> encounter a TypeError
> for x,name in zip(container,knownnames):
> # Note that we always have a name variable defined, but if
> knewnames=False then this is just
> # a copy of containingname, so the name we want to give it
> in this instance is redefined in this
> # case. We have to use this nasty check because we want to
> iterate over the pair (x,name) as
> # variables in the same position in the container have the
> same name, and we can't necessarily
> # use __getitem__
> if hasattr(x,'__name__'): name = x.__name__
> elif not knewnames: name = 'Unnamed object, id =
> '+str(id(x))+', contained in: '+containingname
> if isinstance(x,instancetype):
> if x not in exclude and predicate(x):
> objs.append(x)
> names.append(name)
> else: # Assumption: an object of the instancetype is not
> also a container we want to search in.
> # Note that x may not be a container, but then
> extractInstances will just return an emp

Re: How to POST call and retrieve result page

2008-01-11 Thread Mike Meyer
On Fri, 11 Jan 2008 14:44:19 +0530 "suyash jape" <[EMAIL PROTECTED]> wrote:

> Hi all
> i want to access a web page through python script, fillup the necessary
> fields,
> and press submit button (which does POST call) and retrieve the result page
> and retrieve some values from it.
> 
> Here is the script i have written till now.
> 
> >import urllib2
> > # create array of name/value pairs
> > self.params = urllib.urlencode({'seqname': 'BioSequence', 'sequence':
> 'ATACATTATCCAAACATAGCATGGCTT'})
> >
> > # send http-post
> > request = urllib.urlopen("http://www.hydrazome.metazome.net/search.php";,
> params)
> >
> > # read back each line of reply
> > line = request.read()
> >print line
> 
> This script fills up the correct values in the search.php page.But i am not
> sure if it is doing the POST (submit call).
> Beacause in 'line' varialble, i am getting the search.php page.Not the
> result page which is blast_results.php.
> 
> How to retrieve the result page?

Sounds like you're not POSTing to the right page.

The form on .../search.php lets you fill in values, but those values
are not necessarily POSTed to search.php. In particular, the form element
has an action attribute that has a URL to which the values on the page
should be posted. If that points to .../blast_results.php, then that's
the page you need to pass to urlopen with your data.

  http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: newbie question regarding int(input(:)) - sorry for the spam

2008-01-11 Thread Craig Ward
sorry for the spam Here is the complete message!
I am trying to write a menu script that will execute bash scripts.
Everything is fine until the script executes and I want to see if there are
any more options to run before quitting.

 Example:
=
def menu(opt1 = "something", opt2 = "something else"):
  print "1)", opt1 ""
  print "2)", opt2""
def anythingelse(opt 3 = "final check"):
   menu()
   print "3)", opt3""
menu()
choice = int(input(":"))
if choice == 1
   command
   anythingelse()
elif choice == 2
   command 2
   anythingelse()
else choice ==3
command 3
quit

===
My newbie problem is that although the menu repeats there is no chance to
have a second input and I can't put the int(input(":") in the function
because I get the error 'int' is not callable plus my choice variable is not
defined. can someone please enlighten me? :-)

-- Forwarded message --
From: Craig Ward <[EMAIL PROTECTED]>
Date: Jan 11, 2008 11:21 AM
Subject: newbie question regarding int(input(:))
To: python-list@python.org


Hi experts!
I am trying to write a menu script that will execute bash scripts.
Everything is fine until the script executes and I want to see if there are
any more options to run before quitting. Example:

def menu(opt1 = "something", opt2 = "something else"):


-- 
Computers are like air conditioners.
They stop working when you open Windows.



-- 
Computers are like air conditioners.
They stop working when you open Windows.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python too slow?

2008-01-11 Thread Ed Jensen
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> I don't think you're going to make you some friends here insulting 
> Fredrik. I don't know who Ed Jensen is, but we are quite a lot here to 
> know and respect Mr Lundh for his contributions to Python as both a 
> language and a community.

I'll keep in mind that some people around these parts are untouchable
and have a free pass to be insulting and childish.

Thanks for the tip.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detecting OS platform in Python

2008-01-11 Thread Paul Boddie
On 11 Jan, 04:14, Mike Meyer <[EMAIL PROTECTED]>
wrote:
> On Thu, 10 Jan 2008 18:37:59 -0800 (PST) Devraj <[EMAIL PROTECTED]> wrote:
>
> > My Python program needs reliably detect which Operating System its
> > being run on, infact it even needs to know which distribution of say
> > Linux its running on. The reason being its a GTK application that
> > needs to adapt itself to be a Hildon application if run on devices
> > like the N800.
>
> I don't think it can be done. For most Unix system, os.uname() will give
> you the information you want:
>
> >>> os.uname()

[...]

> GNU/Linux distributions are collections of lots of people software, so
> each has it's own way to state what "distribution" it is. I believe
> there's some sort of standard - except not everybody follows it. So
> you wind up using a series of heuristics to chase this information
> down.

On Red Hat distributions, there appears to be a file called /etc/
redhat-release containing the distribution name. I can't remember the
Debian equivalent, but it may be /etc/debian_version or something like
that. There's LSB-related stuff, too, but I'm not sure if any of that
tells you about the distribution itself.

[...]

> I'm not a GTK programmer, and have never even heard of Hildon. Is
> there some associated module you could try and import that doesn't
> exist on the N800? I.e.:
>
> try:
> import gtk
> mygui = 'gtk'
> except ImportError:
> import Hildon
> mygui = 'Hildon'
>
> or maybe something like:
>
> import gtk
> mygui = 'gtk' if not hasattr(gtk, 'Hildon') else 'Hildon'

There must be Hildon-related modules or features that one can import
or test for, as Mike suggests. In the desktop module [1], I generally
test various environment variables or the output of various programs
in order to deduce which desktop environment is being used, but this
is in software which isn't generally trying to display a graphical
user interface. Just testing for the presence of a file or a program
isn't usually enough because on systems where desktop environments co-
exist, for example, the presence of a GNOME-related file or program
doesn't mean that the user is actually using GNOME at that particular
time. If you might be using Hildon and are actually displaying a GUI,
however, attempting to get the resources you need should be enough to
confirm whether you're running Hildon or not.

Paul

[1] http://www.python.org/pypi/desktop
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python via a little word frequency program

2008-01-11 Thread Mike Meyer
On 11 Jan 2008 03:50:53 -0800 Paul Rubin <"http://phr.cx"@NOSPAM.invalid> wrote:

> rent <[EMAIL PROTECTED]> writes:
> > keys = freq.keys()
> > keys.sort(key = freq.get, reverse = True)
> > for k in keys:
> >  print "%-10s: %d" % (k, freq[k])
> 
> I prefer (untested):
> 
>   def snd((x,y)): return y   # I wish this was built-in

What's wrong with operator.itemgetter?

>   sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True)

(still untested)

from operator import itemgetter
sorted_freq = sorted(freq.iteritems(), key=itemgetter(2), reverse=True)

  http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: reading a specific column from file

2008-01-11 Thread Reedick, Andrew
> -Original Message-
> From: [EMAIL PROTECTED] [mailto:python-
> [EMAIL PROTECTED] On Behalf Of Ivan Novick
> Sent: Friday, January 11, 2008 12:46 PM
> To: python-list@python.org
> Subject: Re: reading a specific column from file
> 
> 
> You say you would like to "read" a specific column.  I wonder if you
> meant read all the data and then just seperate out the 3rd column or
> if you really mean only do disk IO for the 3rd column of data and
> thereby making your read faster.  The second seems more interesting
> but much harder and I wonder if any one has any ideas.  

Do what databases do.  If the columns are stored with a fixed size on
disk, then you can simply compute the offset and seek to it.  If the
columns are of variable size, then you need to store (and maintain) the
offsets in some kind of index.



*

The information transmitted is intended only for the person or entity to which 
it is addressed and may contain confidential, proprietary, and/or privileged 
material. Any review, retransmission, dissemination or other use of, or taking 
of any action in reliance upon this information by persons or entities other 
than the intended recipient is prohibited. If you received this in error, 
please contact the sender and delete the material from all computers. GA623


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python too slow?

2008-01-11 Thread Ross Ridge
Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> And the reference implementation of Python (CPython) is not 
> interpreted, it's compiled to byte-code, which is then executed by a VM 
> (just like Java).
  
Ross Ridge a écrit :
> Python's byte-code interpreter is not "just like" Java's virtual machine.

Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>of course it's not "just like" - different languages, different 
>byte-codes, different implementations. What is "just like" is the 
>byte-code/VM scheme.

No the schemes aren't "just like" each other.  They perform much
differently.

> Thought this was obvious to anyone able to parse a simple sentence.

What's obvious is that you're lying.

>> You're deliberately trying to mislead people into thinking Python performs
>> similarily to Java.
>
>I don't know what you're smoking, but you should perhaps stop - because 
>this seems  to drive you into paranoïd delirium.

This isn't the first time you've tried to mislead people into
thinking Python's byte-code interpreter works just like Java's VM.
Your over-zealous Python advocacy is benefiting no one.  

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Learning Python via a little word frequency program

2008-01-11 Thread Hrvoje Niksic
Mike Meyer <[EMAIL PROTECTED]> writes:

> On 11 Jan 2008 03:50:53 -0800 Paul Rubin <"http://phr.cx"@NOSPAM.invalid> 
> wrote:
>
>> rent <[EMAIL PROTECTED]> writes:
>> > keys = freq.keys()
>> > keys.sort(key = freq.get, reverse = True)
>> > for k in keys:
>> >  print "%-10s: %d" % (k, freq[k])
>> 
>> I prefer (untested):
>> 
>>   def snd((x,y)): return y   # I wish this was built-in
>
> What's wrong with operator.itemgetter?
>
>>   sorted_freq = sorted(freq.iteritems(), key=snd, reverse=True)
>
> (still untested)
>
> from operator import itemgetter
> sorted_freq = sorted(freq.iteritems(), key=itemgetter(2), reverse=True)

It should be itemgetter(1).  See how easy it is to get it wrong?  :-)


(Okay, this was too easy a shot to miss out on; I actually like
itemgetter.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Magic function

2008-01-11 Thread Mike Meyer
On Fri, 11 Jan 2008 08:29:18 -0800 (PST) [EMAIL PROTECTED] wrote:

> Hi all,
> 
> I'm part of a small team writing a Python package for a scientific
> computing project. The idea is to make it easy to use for relatively
> inexperienced programmers. As part of that aim, we're using what we're
> calling 'magic functions', and I'm a little bit concerned that they
> are dangerous code. I'm looking for advice on what the risks are (e.g.
> possibility of introducing subtle bugs, code won't be compatible with
> future versions of Python, etc.).
> 
> Quick background: Part of the way our package works is that you create
> a lot of objects, and then you create a new object which collects
> together these objects and operates on them. We originally were
> writing things like:
> 
> obj1 = Obj(params1)
> obj2 = Obj(params2)
> ...
> bigobj = Bigobj(objects=[obj1,obj2])
> bigobj.run()
> 
> This is fine, but we decided that for clarity of these programs, and
> to make it easier for inexperienced programmers, we would like to be
> able to write something like:
> 
> obj1 = Obj(params1)
> obj2 = Obj(params2)
> ...
> run()
> 
> The idea is that the run() function inspects the stack, and looks for
> object which are instances of class Obj, creates a Bigobj with those
> objects and calls its run() method.
> 
> So, any comments on that approach?

The basic idea is ok, but looking at the stack makes me a bit
nervous. That makes the code complicated, and probably fragile in the
face of changing python versions.

The unittest module does much the same thing - you run unittest.main,
and it runs all the tests in any TestCase subclass in your module
(assuming you didn't do something to limit it). However, it does it by
examining the module, not the stack. The real difference is that your
"magic" classes have to be global to your module. On the other hand,
it provides some nice tools to let you partition things, so you can
easily run subsets of the classes from the command line.

It's probably worth a look.

   http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2008-01-11 Thread m . s . mould

Hi,
I have what I suspect to be a fairly simple problem while using python Numeric.
I am attempting to count the number of times that an element 'b' occurs in
numeric array 'a'. I tried unsuccessfully to find a more efficient function to
do this for me such as that offered when using a list, but couldn't seem to find
anything for Numeric arrays. However, I suspect that my loop is not the most
efficient way to achieve this.

def countel(a, b): #counts the number of times value 'b' is found in array 'a'
i=0
count=0
while (ihttp://mail.python.org/mailman/listinfo/python-list


Re: Analyzing Python GC output - what is a "cell", and what information is available about it.

2008-01-11 Thread Francesco Guerrieri
On Jan 11, 2008 6:20 PM, John Nagle <[EMAIL PROTECTED]> wrote:
> Tried:
> print item.dir()
> got:
> 'cell' object has no attribute 'dir'

I don't know nothing about cell objects...
but why don't you try dir(item) instead?

Francesco
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Frontend/GUI for C Program

2008-01-11 Thread Mike Meyer
On Fri, 11 Jan 2008 08:12:48 -0800 (PST) [EMAIL PROTECTED] wrote:
> I have a C program that works very well. However, being C it has no
> GUI.

What does C have to do with it not having a GUI? I've written more C
programs with a GUI than Python ones - and the C experience was
generally better. Of course, I was using Intuition, not X.

> I have experience using wxPython from within Python apps and I like it
> a lot for its cross-platform capabilities. I was hoping to use
> wxPython for this as well.

Sure, the GUI can be disconnected from the application. In fact,
that's the right way to do it - it allows you to change the GUI as
times move forward.

I've done this in three different ways. Diez pegged them two of them.

When the underlying C code is poorly organized, use subprocess to run
the the C application, build what you're going to send to it's
standard in, and watch what it writes to standard output.

If the C code is well-organized - structures with routines that
manipulate them, so you can identify objects - and command handling on
standard in is basically "parse the arguments, then invoke the the
right function with those values", then you can wrap the structures as
object - with the appropriate functions as methods, and use it in two
ways. One is to expose things via a shared library, and the use ctypes
to talk to it. The other is to embed a python into your application,
and have it launch the script that's going to provide the GUI.

  http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >