Re: [Tutor] Plz help me from this

2007-09-05 Thread Steve Willoughby
Carlos Daniel Ruvalcaba Valenzuela wrote:
> Yes is very possible to do this with python.
> 
> Checkout the os.system and os.popen functions to run external commands
> (chmod, chown).

While those are ways of calling external commands, it is best to use 
built-in language features like os.chmod() and os.chown() whenver 
possible.  They will be much faster and less prone to errors and 
security issues.



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


Re: [Tutor] Problems with wx in Vista...

2007-09-05 Thread Alan Gauld

"Trey Keown" <[EMAIL PROTECTED]> wrote

> Although I should have expected at least a few problems, I have a 
> question
> about a glitch in vista using a wx-implemented script.

So give us a clue, what is the glitch?

> Here's the example script-
> =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
snipped
> =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
> This makes a window pop up with 3 buttons that changes the color of 
> a box.
> Now, my question is, is this a vista-specific problem

It sounds like its doing the right thing?
What did you expect it to do?

Alan G 


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


Re: [Tutor] advanced sorting

2007-09-05 Thread Alan Gauld

"chinni" <[EMAIL PROTECTED]> wrote

> i am using a macpro version(10.4.11) and python version is "2.3.5"

Thats the problem, you need Python v2.4 to use the key= feature
of sort.

There is a way to modify sort behaviour in older versions of Python
The docs say:
--
The sort() method takes an optional argument specifying a
comparison function of two arguments (list items) which should return
a negative, zero or positive number depending on whether the first
argument is considered smaller than, equal to, or larger than
the second argument. Note that this slows the sorting process
down considerably;.

As an example of using the cmpfunc argument to the sort()
method, consider sorting a list of sequences by the second
element of that list:

def mycmp(a, b):
return cmp(a[1], b[1])

mylist.sort(mycmp)
---

Check your v2.3.5 Library Reference docs for more details.

http://www.python.org/doc/2.3.5/lib/typesseq-mutable.html#l2h-220

HTH,
-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld




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


Re: [Tutor] Dynamically changing a class

2007-09-05 Thread Alan Gauld

"Kent Johnson" <[EMAIL PROTECTED]> wrote

>> Wanted to change the mfunc method but ONLY for an instance, not a 
>> class:
>
> I believe the correct way to do this is to use the __get__() method 
> of
> the function object to create a bound method and assign that to the
> instance attribute:

Wow! Another new trick. I've never noticed __get__ before.
Time for some playing I think.

Thanks Kent,

Alan G 


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


[Tutor] Drag image

2007-09-05 Thread Ndoe jtki
i want to drag image for my tasks in my college,but i can't understand 
following example in wx.python 2.6 Docs demo and tool. Have you another simple 
example for drag image? Thanks 


   
-
Bergabunglah dengan orang-orang yang berwawasan, di bidang Anda di Yahoo! 
Answers___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically changing a class

2007-09-05 Thread Ricardo Aráoz
Alan Gauld wrote:
> "Kent Johnson" <[EMAIL PROTECTED]> wrote
> 
>>> Wanted to change the mfunc method but ONLY for an instance, not a 
>>> class:
>> I believe the correct way to do this is to use the __get__() method 
>> of
>> the function object to create a bound method and assign that to the
>> instance attribute:
> 
> Wow! Another new trick. I've never noticed __get__ before.

That'd be two this week ;-)

> Time for some playing I think.

Yep. And once you've got it pls explain it too me, too lazy today to
pick the manual. :)
Any easier way?


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


Re: [Tutor] advanced sorting

2007-09-05 Thread Kent Johnson
Alan Gauld wrote:

> There is a way to modify sort behaviour in older versions of Python
> The docs say:
> --
> The sort() method takes an optional argument specifying a
> comparison function of two arguments

Another way to do this is with the 'Decorate-Sort-Undecorate' idiom. I 
talk about it here:
http://personalpages.tds.net/~kent37/kk/7.html

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


Re: [Tutor] searching a text file

2007-09-05 Thread زياد بن عبدالعزيز البات لي
Alan Gauld wrote:
> "Diana Hawksworth" <[EMAIL PROTECTED]> wrote
> 
>> How do I find a particular name, change the score and then save
>> the changes back to the text file again??
> 
> iterate over the file checking (and modifying) each line
> write the line back out:
> 
> Pseudo code
> 
> Out = open('foo.txt','w')
BEWARE: this will truncate the file immediately, erasing all the data in 
it!!!

Use a temporary file and after you finish processing the data in the 
original file, move (or rename) the temporary file to the original name.

> for line in file('foo.txt'):
> if 'somestring' in line:
>line = 'I changed it\n'
> Out.write(line)
> 
> Out.close()
> 
> You will find much more on this in my file handling topic in my 
> tutorial.
> 
> 

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


Re: [Tutor] Dynamically changing a class

2007-09-05 Thread Kent Johnson
Ricardo Aráoz wrote:

> Yep. And once you've got it pls explain it too me, too lazy today to
> pick the manual. :)

I included a link to my explanation previously. I'm too lazy to try to 
do better.

> Any easier way?

Easier how? I don't know what could be easier to implement than a single 
function call. What did you have in mind? These are all equivalent, take 
your pick:

myObj.mfunc = newfunc.__get__(myObj, MyClass)
myObj.mfunc = types.MethodType(newfunc, myObj, MyClass)
myObj.mfunc = new.instancemethod(newfunc, myObj, MyClass)

For my own interest I looked into how these are actually implemented 
with an eye to which one might be preferred.

new.instancemethod has the advantage of being documented in the library 
reference but the source says it is deprecated and it is a synonym for 
types.MethodType (in new.py).

types.MethodType is defined in types.py as
   MethodType = type(_x._m)
where _x is a class and _m is a method; i.e. types.MethodType is 
literally 'the type of a bound method'. It is fairly explicit at the 
point of use - 'give me a method'.

newfunc.__get__ is defined by func_descr_get() in Objects/funcobject.c. 
It delegates to PyMethod_New() so it is essentially calling MethodType. 
It's a bit obscure at the point of use.

So I guess I prefer MethodType(newfunc, myObj, MyClass)

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


Re: [Tutor] searching a text file

2007-09-05 Thread Kent Johnson
زياد بن عبدالعزيز الباتلي wrote:
> Alan Gauld wrote:
>> "Diana Hawksworth" <[EMAIL PROTECTED]> wrote
>>
>>> How do I find a particular name, change the score and then save
>>> the changes back to the text file again??
>> iterate over the file checking (and modifying) each line
>> write the line back out:
>>
>> Pseudo code
>>
>> Out = open('foo.txt','w')
> BEWARE: this will truncate the file immediately, erasing all the data in 
> it!!!
> 
> Use a temporary file and after you finish processing the data in the 
> original file, move (or rename) the temporary file to the original name.

The fileinput module can help with this. It lets you edit a file 
line-by-line, in place, with a backup:
import fileinput
for line in fileinput.input('test.txt', inplace=1, backup='.bak'):
 if 'somestring' in line:
line = 'I changed it\n'
 print line,

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


Re: [Tutor] Dynamically changing a class

2007-09-05 Thread Jason Doege
Thanks for the good and useful information on this. Now for the why...

I am building an API and for various reasons I have chosen Python to
implement it. I'd like to separate the implementation from the interface
as, for instance, C++ does with separate .hpp and .cpp files. Apart from
defining a class with a bunch of empty methods and then redefining them,
I have not seen a good way to do this in Python. Can you recommend the
Pythonic way to do this?

Best regards,
Jason Doege
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Dynamically changing a class

2007-09-05 Thread Kent Johnson
Jason Doege wrote:
> Thanks for the good and useful information on this. Now for the why...
> 
> I am building an API and for various reasons I have chosen Python to
> implement it. I'd like to separate the implementation from the interface
> as, for instance, C++ does with separate .hpp and .cpp files. Apart from
> defining a class with a bunch of empty methods and then redefining them,
> I have not seen a good way to do this in Python. Can you recommend the
> Pythonic way to do this?

For smaller projects don't bother. For large projects Zope Interface 
seems to be popular: http://wiki.zope.org/Interfaces/FrontPage

PyProtocols is similar but no longer actively developed: 
http://peak.telecommunity.com/PyProtocols.html

A different approach, perhaps more Pythonic, is for consumers to check 
what kind of thing they are given. One way to do this is here:
http://oakwinter.com/code/typecheck/

You might also be interested in
http://www.python.org/dev/peps/pep-0246/
http://www.python.org/dev/peps/pep-3107/

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


[Tutor] more on reading binary... a better way?

2007-09-05 Thread John
Hello everyone,

Here's my solution for reading binary data (unformatted mixed types) and
packing it into a dictionary. It works, but somehow doesn't seem so
'pythonic'. Just seeking comments on how I might make it more efficient.
Thanks!

def readheader(filename):
 import struct
 
I={0:'rl',1:'ibdate',2:'ibtime',3:'version',4:'void1',5:'void2',6:'loutstep',7:'loutaver',8:'loutsample',9:'void3',10:'void4',11:'outlon0',12:'oulat0',13:'numxgrid',14:'numygrid',15:'dxout',16:'dyout',17:'void5',18:'void6',19:'numzgrid'}
 B={}
 f2=file(filename,'rb')
 #Define Header format
 
Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i']
#format for binary reading first bits
 if f2:
  print filename + ' has been opened'
  #create a dictionary from header file
  a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt]
  for i in range(len(a)):
   B[I[i]]=a[i][0]
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] The IF statement

2007-09-05 Thread Toby Holland
Hi gang,

Just doing what I can to understand as I study


I have been reading about testing modules this is the statement that I have
been given

if __name__ == "__main__":


I understand that all modules have a built in attribute __name__, but what
does the __main__ have to do with this attribute.  Is it saying that
__name__ is the same as __main__?

I know that if the module is imported then __name__is the moules file name,
but is this just for the script that your writing while using that module or
is it just to show that the module was imported?

correct me if I'm wrong please, the modules file name is __main__ when its
being used as a stand alone program?

If this is the case the difference is whether or not the module is a program
by itself or intigrated with a script that is what determines its name (i.e.
__name__ and __main__)

I hope this question makes senses


thanks for the help!!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Condensing Some Massive Code

2007-09-05 Thread Tino Dai
On 9/2/07, David Millar <[EMAIL PROTECTED]> wrote:
>
> Hello. I'm working on a text adventure game right now, and I seem to be
> kind of stuck. There's a huge chunk of code called moreaction() that pulls
> scripted events for certain locations. It's ever-changing so I'm not looking
> for specifics, but can anyone suggest good ways to clean up or condense the
> code without sacrificing clarity? The latest version of the source is found
> at http://thegriddle.net/python/v006.txt Any help is much appreciated :) -
> Dave M.


I just took a look at  the code, it seems that you are in if-then hell. I
think that I have a solution for you that improve the readability of the
code. It's using multiple dictionaries to get you out of if-then hell. Let's
say we have:

sceneDict = {}
# We populate these with the difference scene numbers. In the sceneDict, we
have eventDict if there are any events.

Lets say we take your first piece of code:

if thescene == 3:
if event[1] == 0:
global choins
choins = choins - 10
add_item("BEAN",1)
map[2].add_opt("NORTH",4)
map[2].set_desc("You are just outside a nasty looking
movie theatre. Shady Latin gang members have a shell game set up
nearby, and from previous experiences you know to avoid gambling like
the plague.")
event[1] = 1
elif event[1] == 1:
map[3].set_desc("You walk up to the gangsters and the boss
guy says 'Get lost, fool!'")
event[1] = 2
elif event[1] == 3:
map[3].set_desc("You walk up to the gangsters but they
tell you to get lost.")
if (inventory.has_key("ARMONDO'S NOTE") == 0):
print "\nYou walk up to the gangsters and flash a
picture of Candy in front of them. 'Woah, is that Candy?' the boss guy
asks. I ain't seen her since high school!' He scribbles something on
the back of a receipt for frozen wonton burrito meals, and you do the
math and realize that he wants you to give candy the number."
add_item("ARMONDO'S NOTE",1)
elif event[1] == 4:
print "\nYou see Candy with Armondo, and they wave you
over. 'Hey, thanks for hooking us up again! And sorry Armondo took
your choins in his little game, teehee!' She hands you 5 choins. 'Uhh,
he took 10 choins from me, not fi-' 'SHUT UP RUBE!' Candy laughs at
Armondo and kisses him on the cheek. 'We're going to the back seat of
Armondo's car for coffee. See ya! They walk away and get into
Armondo's car, which starts bucking around a bit. Then it suddenly
starts up and leaves, opening the street to the south."
choins += 5
map[2].rem_opt("TALK")
map[2].add_opt("SOUTH",15)
map[1].add_opt("ORDER",16)
elif thescene == 6:
map[5].rem_opt("EAST")
add_item('MAIN MAP',1)
add_recipe('ICED COFFEE','COFFEE','ICE',1)
add_recipe('ESPRESSO','COFFEE','BEAN',2)
add_recipe('CAPPUCCINO','ESPRESSO','MILK',2)
add_recipe('CREAMY COFFEE','COFFEE','MILK',1)
elif thescene == 8:
if event[1] >= 3 and (book.has_key("SYRUP") == 0):
print "\n'PROTIP!' 'Huh?' you respond. 'PROTIP! CANDY and
WATER make various sugary SYRUPS to add to your drinks!' Wow.
Interesting."
add_recipe('SYRUP','CANDY','WATER',1)
disp_menu(0)


sceneDict = { 3:"" , 6:"",8:""}
sceneDict[3] = { 0:"",1:"",2:"",4:""}  #  The key 3 points to a
dictionary of event dictionary.

I have to research how to get the values of these dictionary to be
executeable code :). Tell me what you think (by the way, you will need one
or two if statements and perhaps an try-except block to make this code
work). More tonight or if Kent, Alan or Bob want to step in. :)

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


Re: [Tutor] The IF statement

2007-09-05 Thread Kent Johnson
Toby Holland wrote:
> Hi gang,
> 
> Just doing what I can to understand as I study
> 
> 
> I have been reading about testing modules this is the statement that I 
> have been given
> 
> if __name__ == "__main__":
> 
> 
> I understand that all modules have a built in attribute __name__, but 
> what does the __main__ have to do with this attribute.  Is it saying 
> that __name__ is the same as __main__?

Yes. Note that __name__ is a variable and "__main__" is a string. So 
this says that the value of the variable __name__ is the string "__main__".

> I know that if the module is imported then __name__is the moules file 
> name,

It is the module name which is not quite the same as the file name. 
__file__ has the file name.

> but is this just for the script that your writing while using that 
> module or is it just to show that the module was imported?

It is a way to tell if the module was imported or run directly as a script.

> correct me if I'm wrong please, the modules file name is __main__ when 
> its being used as a stand alone program?

The modules name, not the file name; otherwise yes.

> If this is the case the difference is whether or not the module is a 
> program by itself or intigrated with a script that is what determines 
> its name (i.e. __name__ and __main__)

Yes.

It is handy to be able to write a module so it can be used by being 
imported into another module, or by being run on its own. When run on 
its own it might provide a simple command line interface or run unit 
tests or whatever the developer finds useful. When imported as a library 
for another module then this behaviour is not wanted so it is hidden by the
   if __name__ == '__main__':
condition.

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


Re: [Tutor] Dynamically changing a class

2007-09-05 Thread Ricardo Aráoz
Kent Johnson wrote:
> Ricardo Aráoz wrote:
> 
>> Yep. And once you've got it pls explain it too me, too lazy today to
>> pick the manual. :)
> 
> I included a link to my explanation previously. I'm too lazy to try to
> do better.
> 

LOL, too tired yesterday to even think straight.
Thanks for your answer.

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


Re: [Tutor] more on reading binary... a better way?

2007-09-05 Thread Alan Gauld

"John" <[EMAIL PROTECTED]> wrote

> packing it into a dictionary. It works, but somehow doesn't seem so
> 'pythonic'. Just seeking comments on how I might make it more 
> efficient.

I don't think its too bad but I'd probably try reading all the data in 
one go.

> #Define Header format
> Dfmt=['i','i','i','13s','i','i','i','i','i','i','i','f','f','i','i','f','f','i','i','i']

Dfmt = "iii13s"
ln = 19 * struct.calcsize('i') + struct.calcsize('13s')
a = struct.unpack(Dfmt,f2.read(ln))

Which should return a tuple of all your values in one go.
Now you can go straight to the last for loop below...

All untested of course! :-)


> #format for binary reading first bits
> if f2:
>  print filename + ' has been opened'
>  #create a dictionary from header file
>  a=[struct.unpack(ft,f2.read(struct.calcsize(ft))) for ft in Dfmt]
>  for i in range(len(a)):
>   B[I[i]]=a[i][0]

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


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


Re: [Tutor] Dynamically changing a class

2007-09-05 Thread Kent Johnson
Kent Johnson wrote:
> Jason Doege wrote:
>> I am building an API and for various reasons I have chosen Python to
>> implement it. I'd like to separate the implementation from the interface
>> as, for instance, C++ does with separate .hpp and .cpp files. Apart from
>> defining a class with a bunch of empty methods and then redefining them,
>> I have not seen a good way to do this in Python. Can you recommend the
>> Pythonic way to do this?
> 
> For smaller projects don't bother.

A bit more on this...it is common for Python APIs to be defined by 
convention, documentation and example rather than by code artifacts such 
as formal interfaces.

In Python itself, examples are file-like objects, sequences, mappings, 
iterators, decorators, descriptors and context managers, to name the 
ones that come to immediately mind. All of these are defined 
more-or-less clearly by documentation and usage.

A more extensive example is Python DB-API which defines a way to 
interface to a database. This is defined entirely by the spec:
http://www.python.org/dev/peps/pep-0249/

Kent

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


Re: [Tutor] Metaclass programming

2007-09-05 Thread Kent Johnson
Orest Kozyar wrote:
> You're right.  I just figured out that for some reason, when I use the
> SQLAlchemy mapper() function to map my classes to the corresponding table
> object, it seems to affect inspect.getargspec().  
> 
> For example:
> 
> from sqlalchemy.orm import mapper
> from sqlalchemy import Table, MetaData
> import inspect
> 
> class Foo:
>   def __init__(self, x, y):
>   pass
> 
> print inspect.getargspec(Foo.__init__)
> 
>>> (['self', 'x', 'y'], None, None, None)
> 
> metadata = MetaData()
> foo_table = Table('foo', metadata)
> mapper(Foo, foo_table)
> 
> print inspect.getargspec(Foo.__init__)
> 
>>> (['instance'], 'args', 'kwargs', None)
> 
> I'm not sure why this would be the case, but is a bit frustrating since I do
> need the names of the positional arguments sometimes.

I can't be sure without looking at the code but it looks like SA is 
decorating the class methods; this usually loses the signature of the 
method. The problem is described here:
http://www.phyast.pitt.edu/~micheles/python/documentation.html#statement-of-the-problem

>> Why are you doing this?
> 
> Partially as an exercise to help me better understand Python inspection as
> well as metaclass programming.

Note that there is no metaclass in the above code, unless mapper() is 
introducing one behind the scene...

   I also am using it in a EntitySingleton
> metaclass that I adapted from the SQLAlchemy wiki
> (http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject).  Some of my
> classes have unique constraints, and I want the metaclass to check these
> unique constraints and return an object from the database if an object
> meeting these constraints already exists.  
> 
> For example:
> 
> class User:
>   __unique__ = ['firstname', 'lastname']
>   __metaclass__ = EntitySingleton
> 
>   def __init__(self, firstname, lastname, password):
>   pass
> 
> The metaclass knows what the "unique" constraints are based on the
> __unique__ list, but needs to use inspect.getargspec() to get the variable
> names and match them up with the *args list that EntitySingleton.__call__
> recieves.  At least, that's how I'm trying to do it, but I expect this might
> not be the best way to do it?  Either case, when the class is mapped to a
> database table, I lose all this information, so will need to figure out a
> different way of approaching this.

You should probably look for a different way to do it. Depending on your 
tolerance for hacks, it may be possible to work around the decorator. 
The original function is probably contained within the closure of the 
decorator and you can dig it out. For example,

make a simple decorator and decorate a function:

In [5]: def deco(f):
...: def _deco(*args, **kwds):
...: print 'about to call', f.__name__
...: f(*args, **kwds)
...: return _deco
...:
In [6]: @deco
...: def f(): print 'foo here'
...:

Hey, it works!

In [7]: f()
about to call f
foo here

but the decorated function has the signature of the decoration:

In [8]: import inspect
In [9]: inspect.getargspec(f)
Out[9]: ([], 'args', 'kwds', None)

If we dig hard enough we can find the original and get its signature:

In [11]: f.func_closure
Out[11]: (,)

In [14]: f.func_closure[0].cell_contents
Out[14]: 
In [15]: inspect.getargspec(f.func_closure[0].cell_contents)
Out[15]: ([], None, None, None)
In [16]: f.func_closure[0].cell_contents.__name__
Out[16]: 'f'

I don't think I would want to rely on this in production code though...

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


Re: [Tutor] Condensing Some Massive Code

2007-09-05 Thread Kent Johnson
David Millar wrote:
> Hello. I'm working on a text adventure game right now, and I seem to be 
> kind of stuck. There's a huge chunk of code called moreaction() that 
> pulls scripted events for certain locations. It's ever-changing so I'm 
> not looking for specifics, but can anyone suggest good ways to clean up 
> or condense the code without sacrificing clarity? The latest version of 
> the source is found at http://thegriddle.net/python/v006.txt Any help is 
> much appreciated :) - Dave M.

One way to help with this is to use functions and a dispatch table. For 
example instead of

 elif lookup == "COVER":
 print "\nYou close the book and stare dumbly at the cover, 
sideways:"
  return
 elif lookup == "TOC":
 print "\nYou glance over the table of contents. You have 
recipes for the following:"
 b = book.keys()
 b.sort()
 for r in b:
 print "*",r,
 print "*"
 return
 elif lookup == "SYRUP":
 print "\n* SYRUP *"
 print "* SYRUP is an interesting drink."
 return

you could write

def cover():
 print "\nYou close the book and stare dumbly at the cover, 
sideways:"

def toc():
 print "\nYou close the book and stare dumbly at the cover, 
sideways:"
  return
 elif lookup == "TOC":
 print "\nYou glance over the table of contents. You have 
recipes for the following:"
 b = book.keys()
 b.sort()
 for r in b:
 print "*",r,
 print "*"

def syrup():
 print "\n* SYRUP *"
 print "* SYRUP is an interesting drink."
 return

dispatch = dict(COVER=cover, TOC=toc, SYRUP=syrup)

fn = dispatch[lookup]
fn()


That is the basic idea. There are a lot of possible complications and 
variations. If some of the functions need arguments, you need to make a 
common protocol for passing arguments and returning values. You might 
want to make the functions methods of a class so they can share state. 
Clever use of introspection can make the dispatch table unnecessary.

You might want to look at the cmd module in the Python standard library 
as an example of this approach.

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


[Tutor] Importing Excel sheet data

2007-09-05 Thread saradhi dinavahi
hello all,

I am new to the Python Programming. I want to Import Excel sheet data using
Python. Can any one please provide me the code and explain the basic steps
and method of executing the code.

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


Re: [Tutor] Importing Excel sheet data

2007-09-05 Thread Ian Witham
Hi,

You should look at the 'csv' module in the Python Standard Library. If you
export your excel data to csv format, you can easily import the data in to
python using the csv module.

Ian

On 9/6/07, saradhi dinavahi <[EMAIL PROTECTED]> wrote:
>
> hello all,
>
> I am new to the Python Programming. I want to Import Excel sheet data
> using Python. Can any one please provide me the code and explain the basic
> steps and method of executing the code.
>
>  Thank You All
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Importing Excel sheet data

2007-09-05 Thread Ian Witham
HI Saradhi,

I too am fairly new to Python, but I use the csv module successfully for my
work. Could you be a little more specific as to what your requirements are
and where you are finding difficulty?

Ian.

On 9/6/07, saradhi dinavahi <[EMAIL PROTECTED]> wrote:
>
> hi Ian ,
>
> I have read the CSV module. But I felt difficult to write a code for my
> requirement.
>
>   Thank You.
>
>
> On 9/5/07, Ian Witham <[EMAIL PROTECTED]> wrote:
> >
> > Hi,
> >
> > You should look at the 'csv' module in the Python Standard Library. If
> > you export your excel data to csv format, you can easily import the data in
> > to python using the csv module.
> >
> > Ian
> >
> > On 9/6/07, saradhi dinavahi < [EMAIL PROTECTED] > wrote:
> > >
> > >  hello all,
> > >
> > > I am new to the Python Programming. I want to Import Excel sheet data
> > > using Python. Can any one please provide me the code and explain the basic
> > > steps and method of executing the code.
> > >
> > >  Thank You All
> > >
> > >
> > > ___
> > > Tutor maillist  -   Tutor@python.org
> > > http://mail.python.org/mailman/listinfo/tutor
> > >
> > >
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Importing Excel sheet data

2007-09-05 Thread Ian Witham
Hi Saradhi,

The first step is to export your excel data to the .csv format. This is done
in Excel from the file menu.

CSV means "comma separated values". If you have exported the data correctly
it may look something like this:

"8803","16/9/2007","299000","BEO","13B Mandeville Crescent","Grenada
Village","2.00PM","","3"
"8844","16/9/2007","599000","BEO","89 Kahu Road","Paremata","2.00PM","","4"
"8855","16/9/2007","37","BEO","8 Salford Street","Newlands","2.00PM
","","2"

Lots of values, separated by commas, often with quotation marks containing
the values.

The code I use to import this type of data looks like this:

>>> import csv
>>> oh_reader = csv.reader(open('openhomes.csv', 'U'), dialect='excel')
>>> for row in oh_reader:
print row


['8803', '16/9/2007', '299000', 'BEO', '13B Mandeville Crescent', 'Grenada
Village', '2.00PM', '', '3']
['8844', '16/9/2007', '599000', 'BEO', '89 Kahu Road', 'Paremata', '2.00PM',
'', '4']
['8855', '16/9/2007', '37', 'BEO', '8 Salford Street', 'Newlands', '
2.00PM', '', '2']

There is all my data in list format.

There is also another class in csv called DictReader which presents your
data in dictionary form. To do this you must provide a list of 'keys' to use
for your dictionary. Think of these keys as being analogous to a header row
in excel. eg:

my_header_row = ['list_number', '

>>> my_header_row = ['list_number', 'date', 'price', 'price2', 'add1',
'add2', 'start', 'finish', 'bedrooms']
>>> dict_reader = csv.DictReader(open('openhomes.csv', 'U'), my_header_row,
dialect='excel')
>>> for row in dict_reader:
print row


{'finish': '', 'add2': 'Grenada Village', 'add1': '13B Mandeville Crescent',
'price': '299000', 'list_number': '8803', 'start': '2.00PM', 'bedrooms':
'3', 'date': '16/9/2007', 'price2': 'BEO'}
{'finish': '', 'add2': 'Paremata', 'add1': '89 Kahu Road', 'price':
'599000', 'list_number': '8844', 'start': '2.00PM', 'bedrooms': '4', 'date':
'16/9/2007', 'price2': 'BEO'}
{'finish': '', 'add2': 'Newlands', 'add1': '8 Salford Street', 'price':
'37', 'list_number': '8855', 'start': '2.00PM', 'bedrooms': '2', 'date':
'16/9/2007', 'price2': 'BEO'}

And there is my data in dictionary format. CSV also has tools for exporting
both lists and dicts to csv format again, and from there you can import the
data back to excel. I hope I have been helpful to you.

Ian.

On 9/6/07, saradhi dinavahi <[EMAIL PROTECTED]> wrote:
>
> Hi Ian,
>
> I have read the Python CSV module .But I cant understand to use that
> module to Import Excel Sheet data.As I am new to the Python programming ,
> I dont know the way to  write  code using that module to meet my
> requirement.
>
> On 9/5/07, Ian Witham <[EMAIL PROTECTED]> wrote:
> >
> > HI Saradhi,
> >
> > I too am fairly new to Python, but I use the csv module successfully for
> > my work. Could you be a little more specific as to what your requirements
> > are and where you are finding difficulty?
> >
> > Ian.
> >
> > On 9/6/07, saradhi dinavahi <[EMAIL PROTECTED] > wrote:
> > >
> > > hi Ian ,
> > >
> > > I have read the CSV module. But I felt difficult to write a code for
> > > my requirement.
> > >
> > >   Thank You.
> > >
> > >
> > >  On 9/5/07, Ian Witham <[EMAIL PROTECTED] > wrote:
> > > >
> > > > Hi,
> > > >
> > > > You should look at the 'csv' module in the Python Standard Library.
> > > > If you export your excel data to csv format, you can easily import the 
> > > > data
> > > > in to python using the csv module.
> > > >
> > > > Ian
> > > >
> > > > On 9/6/07, saradhi dinavahi < [EMAIL PROTECTED] > wrote:
> > > > >
> > > > >  hello all,
> > > > >
> > > > > I am new to the Python Programming. I want to Import Excel sheet
> > > > > data using Python. Can any one please provide me the code and explain 
> > > > > the
> > > > > basic steps and method of executing the code.
> > > > >
> > > > >  Thank You All
> > > > >
> > > > >
> > > > > ___
> > > > > Tutor maillist  -   Tutor@python.org
> > > > > http://mail.python.org/mailman/listinfo/tutor
> > > > >
> > > > >
> > > >
> > >
> >
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] unicode encoding hell

2007-09-05 Thread David Bear
I'm using universal feed parser to grab an rss feed.

I'm carefull not to use any sys.out, print, file write ops, etc, UNLESS I
use a decode('utf-i') to convert the unicode string I get from feed parser
to utf-8. However, I'm still getting the blasted decode error stating that
one of the items in the unicode string is out range. I've checked the
encoding from the feed and it does indeed say it is utf-8. The content-type
header is set to application/rss+xml . I am using the following syntax on a
feedparser object:

feedp.entry.title.decode('utf-8', 'xmlcharrefreplace')

I assume it would take any unicode character and 'do the right thing',
including replacing higher ordinal chars with xml entity refs. But I still
get

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in
position 31: ordinal not in range(128)

Clearly, I completely do not understand how unicode is working here. Can
anyone enlighten me?


--
David Bear
College of Public Programs at Arizona State University

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


[Tutor] Importing Excel sheet data

2007-09-05 Thread János Juhász
Dear Saradhi,

I am using COM on Win32 for this, 
based on the sample of Mark Hammond & Andy Robinson 
in the "Programing Python on Win32" book.
That is a fairly simple way to do that.

The code itself can be downloaded from 
http://examples.oreilly.com/pythonwin32/ppw32_samples.zip

You can find some information about it googling for EasyExcel.

The book itself is an essential to work on win32 with python.
# My personal favorite chapters are the ones about double-entry 
bookkeeping :)

> Date: Wed, 5 Sep 2007 21:07:41 -0500
> From: "saradhi dinavahi" <[EMAIL PROTECTED]>

> I am new to the Python Programming. I want to Import Excel sheet data 
using
> Python. Can any one please provide me the code and explain the basic 
steps
> and method of executing the code.


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