Re: [Tutor] max(len(item)) for cols

2005-06-20 Thread János Juhász
Dear Alan,

similar :)


I have scripted a small sql e-mail reporting simplified from
# written by Mike Brown
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/148061

import string

def TableStr(labels, rows, delim=' | '):
  columns = zip(*[labels] + rows)
  # get the maximum of each column by the string length of its items
  maxWidths = [max([len(str(cell)) for cell in column]) for column in
columns]
  result = delim.join(
[str.ljust(str(item),width) for (item,width) in
zip(labels,maxWidths)]
)+'\n'
  result +=  '='*(sum(maxWidths) + len(delim)*(len(columns)-1))+'\n'
  for row in rows:
result += delim.join(
  [str.ljust(str(item),width) for (item,width) in
zip(row,maxWidths)]
  )+'\n'
  return result

data = """\
WH,Stock,Qty
01,1001,10
01,1002,23
02,1432,4
03,This is long stockcode,100"""

table = string.split(data, '\n')
labels = string.split(table[0], ',')
rows = [string.split(row, ',') for row in table[1:]]

print ''
print TableStr(labels, rows, delim=' | ')


It makes beautiful tables from sql queries into e-mail as warning.


That I don't know is the asterisk in zip(*[labels] + rows)
I wasn't able to find in the python reference  what it means.
May you help me in that ?



Yours sincerely,
__
János Juhász




   
 "Alan G"   
   
 <[EMAIL PROTECTED] 
   
 .uk>   To  
   
János Juhász <[EMAIL 
PROTECTED]>,   
cc  
   
 2005.06.17 19:59   
   
Subject 
   
Re: [Tutor] max(len(item)) for 
cols

   

   




I have a 2D array:
>>>[['1', '2 ', '3'], ['longer ', 'longer', 'sort']]

> How can I  get what is the max(len(item)) for the columns ?
> I would like to get a list with the max_col_width values.

>>> tda = [['1', '2 ', '3'], ['longer ', 'longer',
'sort']]
>>> mcw = [[len(r) for r in c] for c in tda]
>>> mcw
[[1, 2, 5], [11, 10, 4]]
>>> mcw = [max([len(r) for r in c]) for c in tda]
>>> mcw
[5, 11]
>>> widest = max(mcw)
>>> widest
11

Is that what you mean?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] calling perl from python code

2005-06-20 Thread Shuying Wang
Hi,

Can anyone recommend a library that will let me call perl functions
from python? I have a python dictionary that I would like to convert
to a perl hash for some function.

cheers,
Shuying
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Layering Canvas widgets with Tkinter

2005-06-20 Thread Alan G
-
def menu(y):
   main.grid_remove ()
   root.update()
   if y ==1:
  menu1()
etc/...

def menu1():
   X=Canvas(root, width=200, height=200, bg="blue")
   X.grid(row=0,column=0)
   but2=Button(X,text="back",command=mainmenu)
   but2.grid()

def menu2():...
def menu3():...

root= Tk()
root.geometry('200x200')
main=Canvas(root,width=200,height=200,bg="grey")
main.grid(row=0,column=0)
root.mainloop()


I think one problem is that you initially call your canvas main.
In menu() you then remove main, but you don't ever replace it.
Thus on subsequent calls to menu() you are not actually 
removing anything!

This is partly a result of you using global variables everywhere
and partly a result of you mixing the object creation and their 
positioning in a single function.

It would IMHO be better to make the menuN() functions simply 
return the canvas objects rather than to use grid() internally.
That way you can associate them with main... That way the code 
changes to look something like:

def menu(y):
   main.grid_remove ()
   root.update()
   if y ==1:
  main = menu1()
   main.grid(row=0,column=0)
etc/...

def menu1():
   X=Canvas(root, width=200, height=200, bg="blue")
   but2=Button(X,text="back",command=mainmenu)
   but2.grid()
   return X

The other option would e to pass main into menuN() as a 
parameter and use that instead of X but I prefer the 
approach above...

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numbers & Characters As Dictionary Keys

2005-06-20 Thread Alan G
> "raw_input", but I get "H is not defined" when I run the script.  
> Essentially, I'd like the user to enter a number for most items, 
> but use letters for "Help", "Quit", and "Back to Main".

Are you sure? That kind of inconsistent input is one of the 
big no-nos of user interface design. It usually confuses 
the heck out of users!

Hoewever to the problem at hand.
It should just be a case of changing the keys in the dictionary.
Unfortunately you've told us the problem but shown us the code 
that woreks, not the broken copde. So we can only guess what 
you might have done!

But basically here is a sample program that does approximately 
what you want:

def hello(): print 'hello'
def goodbye(): print 'goodbye'

menu = { '1' : ('hello', hello),
 'Q' : ('goodbye', goodbye)}

for m in menu.keys():
   print "%s\t%s" % (m,menu[m][0])

cmd = raw_input('pick one ').upper()
menu[cmd][1]()

Does that help?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Every Other

2005-06-20 Thread Alan G
> What would be the most Pythonic way 

THats always going to be subjective but...

> of printing (or extracting) every 
> other element of a list? 

I'd probably use range with a step of 2.

for index in range(0,len(mylist),2):
   ptint mylist[index]

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Every Other

2005-06-20 Thread Alan G
JOhn,

> This is probably it:
> >>> arr = range(20)
> >>> arr[::2]

You are probably right, I forgot that slicing now 
had a 3rd element... :-)

Alan G.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Calling web browser from Python

2005-06-20 Thread Andre Engels
Is it possible to call a web browser from Python, opening a certain
page? Preferably the user's standard web browser.

Andre Engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling web browser from Python

2005-06-20 Thread Brian van den Broek
Andre Engels said unto the world upon 20/06/2005 04:26:
> Is it possible to call a web browser from Python, opening a certain
> page? Preferably the user's standard web browser.
> 
> Andre Engels
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

IDLE 1.1.1
 >>> import webbrowser
 >>> webbrowser.open('www.google.ca')
 >>>

Best,

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] calling perl from python code

2005-06-20 Thread Danny Yoo


On Mon, 20 Jun 2005, Shuying Wang wrote:

> Can anyone recommend a library that will let me call perl functions from
> python? I have a python dictionary that I would like to convert to a
> perl hash for some function.

Hi Shuying,

Sure!  You may want to look at the PyPerl project:

http://wiki.python.org/moin/PyPerl

The module acts as a bridge between the two langauges, so it should be
relatively easy to convert Python dictionaries to Perl hashes and pass
them back and forth.


Best of wishes!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Calling web browser from Python

2005-06-20 Thread jfouhy
Quoting Andre Engels <[EMAIL PROTECTED]>:

> Is it possible to call a web browser from Python, opening a certain
> page? Preferably the user's standard web browser.

Check the webbrowser module :-)

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] max(len(item)) for cols

2005-06-20 Thread jfouhy
Quoting János Juhász <[EMAIL PROTECTED]>:

> That I don't know is the asterisk in zip(*[labels] + rows)
> I wasn't able to find in the python reference what it means.
> May you help me in that ?

You can find it in the language reference: http://docs.python.org/ref/calls.html

Basically, suppose you have a list:

>>> myList = ['foo', 42, None]

and a function:

>>> def doSomething(s, n, t):
... print 'The meaning of %s is %d' % (s, n)
... if t:
... return True
... return False
...

Then you can call like this:

>>> doSomething(*myList)
The meaning of foo is 42
False

The *myList means "expand myList into a bunch of positional parameters".  So,
doSomething got the first element of myList as s, the second element as n, and
the third element as t.

You can do the same thing in reverse, in the function definition.  eg:

>>> def myFunction(*args):
... for x in args:
... print x,
... print
...
>>> myFunction(1, 2, 'foo', 'bar', 37)
1 2 foo bar 37

In this case, all the positional arguments got combined into a tuple, and given
the name 'args'.

Finally, this works with keyword arguments as well, but you have to use
dictionaries, and you use two asterisks instead of one.

>>> myDict = { 'x':3, 'y':7, 'z':19 }
>>> def doSomeArithmetic(y=0, z=0, x=0):
... return y*z+x
...
>>> doSomeArithmetic(**myDict)
136

HTH!

-- 
John.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Refreshing the interpreter environment

2005-06-20 Thread lawrence wang
How do I refresh the interpreter environment without restarting it, if
possible? For example, I'm using the interpreter to test a class I'm
writing; importing and instantiating it reveals a typo; I go and fix
the typo. Now, is there any way to reload the class afresh? Simply
importing again doesn't seem to do it. Thanks in advance for your
help.

Lawrence Wang
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Refreshing the interpreter environment

2005-06-20 Thread Javier Ruere
lawrence wang wrote:
> How do I refresh the interpreter environment without restarting it, if
> possible? For example, I'm using the interpreter to test a class I'm
> writing; importing and instantiating it reveals a typo; I go and fix
> the typo. Now, is there any way to reload the class afresh? Simply
> importing again doesn't seem to do it. Thanks in advance for your
> help.

Yes:

(echo "a=1" > a.py)
>>> import a
>>> a.a
1
(echo "a=2" > a.py)
>>> a = reload(a)
>>> a.a
2

Javier


signature.asc
Description: OpenPGP digital signature
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numbers & Characters As Dictionary Keys

2005-06-20 Thread Don Parris
On Mon, 20 Jun 2005 09:11:53 +0100
"Alan G" <[EMAIL PROTECTED]> wrote:

> > "raw_input", but I get "H is not defined" when I run the script.  
> > Essentially, I'd like the user to enter a number for most items, 
> > but use letters for "Help", "Quit", and "Back to Main".
> 
> Are you sure? That kind of inconsistent input is one of the 
> big no-nos of user interface design. It usually confuses 
> the heck out of users!
> 

Hmmm, good point.  It was a thought.  I am trying to avoid confusing my
users.  If this kind of input will cause confusion, I should avoid it.  I
was looking to provide a consistent help/quit/main single-key scheme across
all menus. I can (and presently am) using a double-digit number for this
purpose in the current script.  On the other hand, I thought people would
easily recognize at least the "H" & "Q" for "help" and "quit". 
Alternatively, I could link these to "F1" & [Ctrl]+Q, or something like
that.  Many people would understand "F1".

Basically, the sub-menu offers choices:
1-3 - add/edit/delete
4-? - standard reports
10-12 - H/Q/M 


> Hoewever to the problem at hand.
> It should just be a case of changing the keys in the dictionary.
> Unfortunately you've told us the problem but shown us the code 
> that woreks, not the broken copde. So we can only guess what 
> you might have done!
> 
> But basically here is a sample program that does approximately 
> what you want:
> 
> def hello(): print 'hello'
> def goodbye(): print 'goodbye'
> 
> menu = { '1' : ('hello', hello),
>  'Q' : ('goodbye', goodbye)}
> 
> for m in menu.keys():
>print "%s\t%s" % (m,menu[m][0])
> 
I am curious what the "%" by itself is doing.

> cmd = raw_input('pick one ').upper()
> menu[cmd][1]()
> 
> Does that help?
> 
I'll tinker with this a bit.

Don
-- 
evangelinuxGNU Evangelist
http://matheteuo.org/   http://chaddb.sourceforge.net/
"Free software is like God's love - you can share it with anyone anytime
anywhere."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numbers & Characters As Dictionary Keys

2005-06-20 Thread Brian van den Broek
Don Parris said unto the world upon 20/06/2005 14:10:
> On Mon, 20 Jun 2005 09:11:53 +0100
> "Alan G" <[EMAIL PROTECTED]> wrote:



>>for m in menu.keys():
>>   print "%s\t%s" % (m,menu[m][0])
>>
> 
> I am curious what the "%" by itself is doing.



> Don


Hi Don,

it is indicating that the tuple that follows is the source that the 
values for the '%s's in "%s\t%s" will be drawn from. I generally write 
it without the space between the '%' and the tuple; I don't know what 
the general practise is.

 >>> print "%s won't %s" ('this', 'work')
Traceback (most recent call last):
   File "", line 1, in ?
TypeError: 'str' object is not callable
 >>> print "%s will %s" %('this', 'work')
this will work
 >>> print "%s will %s" % ('this', 'work, too')
this will work, too
 >>>

Best,

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Using code objects?

2005-06-20 Thread Chinook
Using code objects?
===

As an OO exercise I have a factory pattern that returns class objects that 
each have an "action" method.  ClassObj.action() in turn returns a code 
object in my recursive process loop.

I create the code objects as a one time step outside my factory pattern and 
potential class definitions, then reference them in my potential classes 
which seems to work as expected.  

When I create the code objects though, it seems a couple different ways work 
and I'm wondering which is better and why (or is there a more correct 
technique in this situation)?

The two different ways are illustrated below:

Python 2.4.1 (#2, Mar 31 2005, 00:05:10) 
[GCC 3.3 20030304 (Apple Computer, Inc. build 1666)]
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(st):
...   print st
... 
>>> exp1 = 'foo("#expersion 1#")'
>>> exp2 = 'foo("#expersion 2#")'
>>> obj1 = compile(exp1, 'whatever', 'single')
>>> exec obj1
#expersion 1#
>>> obj2 = compile(exp2, 'whatever', 'exec')
>>> exec obj2
#expersion 2#
>>> 

Thank you,
Lee C


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor