Re: [Tutor] making a table

2005-09-09 Thread Johan Geldenhuys




def x():
... print 'C    F'
... for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100):
...    fahrenheit = (9.0/5.0) * i + 32
...    print (`i` + '  ' + `fahrenheit`)

Simple but look OK,

Johan


On Thu, 2005-09-08 at 19:46 -0700, bob wrote:

At 04:34 PM 9/8/2005, [EMAIL PROTECTED] wrote:

I would like to construct a table for my program but it does not seem to be coming out evenly. Could someone please let me know what to do so that everything will work out correctly? 

def main(): 
   print "This program shows a table of Celsius temperatures and there Fahrenheit equivalents every 10 degrees from 0C to 100C" 
   print "C F" 
   for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100): 
   fahrenheit = (9.0/5.0) * i + 32 
   print i 
   print "   ", 
   print fahrenheit 
    
main() 


1 - you are getting C and F on different lines because there is no , after print i. After you fix that you will get:
C F
0 32.0
10 50.0
... similar lines deleted
40 104.0
... similar lines deleted
100 212.0

Now the trick is to get things lined up. Here % formatting comes in:

print "  C   F"
...
    print '%3s    %5.1f' % (i, farenheit)

Giving:
  C  F
  0 32.0
 10 50.0
etc. 

___
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] making a table

2005-09-09 Thread mailing list
Hi Goofball223, 

Just a quick thing -

> for i in (0,10, 20, 30, 40, 50, 60, 70, 80, 90, 100):

Have you used range() before?

for i in range(10): 
 print i
 
0
1
2
3
4
5
6
7
8
9

It's handy for situations like yours. Also, you could use it like this - 

zeroToNine = range(10)
print zeroToNine 
[0,1,2,3,4,5,6,7,8,9]

for i in zeroToNine:
 print i

..Just a quick mention that range(x) counts up to, but not including
x. ( There's good reasons for this, which someone can explain if
needed.)

Also, by default it starts at zero, and increases by 1. You can change
these, however.

i.e. to create a list from 5 to 50 in increments of 5 - 

zeroToFifty = range(start = 5, stop = 55, step = 5)

Remember, it'll count up to but not including stop, so if you tell it
to count to two hundred in steps of 10, it'll count to 190, counting
to 16 by steps of 2 will count to 14. So always set it one step value
above what you want.

(start defaults to 0, step defaults to 1, hence you can just use
range(stop = 100) or
range(100) for short.)

You're looking good, however.

Cheers, 

Liam Clarke

On 9/9/05, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I would like to construct a table for my program but it does not seem to be
> coming out evenly. Could someone please let me know what to do so that
> everything will work out correctly? 
>  
> def main(): 
> print "This program shows a table of Celsius temperatures and there
> Fahrenheit equivalents every 10 degrees from 0C to 100C" 
> print "C F" 
> for i in(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100): 
> fahrenheit = (9.0/5.0) * i + 32 
> print i 
> print "   ", 
> print fahrenheit 
>  
> main() 
> ___
> 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] making a table

2005-09-09 Thread Alan G

>I would like to construct a table for my program but it does not seem 
>to be
> coming out evenly. Could someone please let me know what to do so 
> that
> everything will work out correctly?

The best way to build a table is to use a format string with every
field width specified explicitly. Thus in your example:

def main(min,max,step):
"""This program prints a table of Celsius temperatures
   and their Fahrenheit equivalents """
fmt = "%4s%4s"
print fmt % ('C','F')
for i in range(min, max, step):
fahrenheit = (9.0/5.0) * i + 32
print fmt % (i,farenheit)

main(0,101,10)

By applying the same format to the headings you ensure consistency and
by specifying the widths you get guaranteed text line-up. If you want
to print an HTML table you only need to add the tags to the format
string (although in that case you might want a different format
for the header)

I also parameterised the function so you can specify the range of
temperatures and the step size just for fun. :-)

Alan G 

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


[Tutor] directory recursion

2005-09-09 Thread Rob Andrews
I should already know this, and probably once did, but have never had
a real world use for it until now.

What's a nice, clean way to recursively scan through directories with
an arbitrary number of subdirectories?

In today's example, we're looking to grab the file name and third line
of the file for every text file in the directory tree, and dump into a
new text file. Everything but the walking of the tree was obvious
enough.

We used the following to grab the desired output from a single level
of directories:

import glob

for fileName in glob.glob('C:/stuff/jayfiles/*/*.txt'): # glob through
directories
newFile = open('C:/stuff/jayfiles/newFile.txt', 'a') # open
newFile to append
newFile.write(fileName) # append fileName to newFile
newFile.write('\t') # append a tab after fileName
currentFile = open(fileName, 'r') # open next file for reading
currentFile.readline() # this and the following line go through...
currentFile.readline() #...the 1st 2 lines of the file
thirdLine = currentFile.readline() # modify this to print to text file
newFile.write(thirdLine) # append thirdLine to newFile
currentFile.close() # close currentFile
newFile.close() # close newFile

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


Re: [Tutor] directory recursion

2005-09-09 Thread Danny Yoo


On Fri, 9 Sep 2005, Rob Andrews wrote:

> I should already know this, and probably once did, but have never had
> a real world use for it until now.
>
> What's a nice, clean way to recursively scan through directories with
> an arbitrary number of subdirectories?

Hi Rob,

You may want to look at os.walk():

http://www.python.org/doc/lib/os-file-dir.html#l2h-1628

If you have questions on it, please feel free to ask!

Hope this helps!

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


Re: [Tutor] directory recursion

2005-09-09 Thread Christopher Arndt
Rob Andrews schrieb:
> I should already know this, and probably once did, but have never had
> a real world use for it until now.
> 
> What's a nice, clean way to recursively scan through directories with
> an arbitrary number of subdirectories?

os.walk() is you friend! (Don't use os.path.walk() anymore)

"Off the top of my head":

for dir, dirnames, filenames in os.walk(topdir):
for dir in dirnames:
do_something_with_subdir(os.path.join(dir, dirname)
for file in filenames:
do_something_with_file(os.path.join(dir, filename)

HTH, Chris

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


Re: [Tutor] Substring substitution

2005-09-09 Thread Bernard Lebel
Hi Kent,

Once again, thanks a lot. Problem solved now, your suggestions work
like a charm. You were absolutely right about the last group matching.
I modified my matching pattern:

oRe = re.compile( "(\d\d_\d\d\_)(\d\d(\D|$))" )

Instead of

oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )


I had no idea you could put subgroups in groups, I tried that out of
inspiration and whoo it works. This is fantastic!

So here is the full script, followed by the output:


import os, re


def matchShot( sSubString, oRe ):

sNewString = oRe.sub( r'\g<1>0\2', sSubString )
return sNewString




def processPath( sString, bTest ):

"""
ARGUMENTS:
sString (string): the path to process
bTest (boolean): test the validity of paths at each step of the script
"""

# Create regular expression object
oRe = re.compile( "(\d\d_\d\d\_)(\d\d(\D|$))" )


if bTest == True:
# Test validity of integral path
if not os.path.exists( sString ): return None

# Break-up path
aString = sString.split( os.sep )

aNewPath = []

# Iterate individual components
for sSubString in aString:


if bTest == True:
# Test if this part of the path is working with the 
current path
sTempPath = '\\'.join( aNewPath )
sTempPath += '%s%s' % ( '\\', sSubString )
if not os.path.exists( sTempPath ): sSubString = 
matchShot( sSubString, oRe )
else: sSubString = matchShot( sSubString, oRe )


aNewPath.append( sSubString )


if bTest == True:
# Test again if path is valid with this substring
sTempPath = '\\'.join( aNewPath )
if not os.path.exists( sTempPath ): return None


sNewPath = '\\'.join( aNewPath )
print sNewPath




processPath( r'C:\temp\MT_03_03_03\allo.txt', False )
processPath( r'C:\temp\MT_03_04_04\mt_03_04_04_anim_v1.scn', False )
processPath( r'C:\temp\MT_03_05_005_anim\mt_03_05_05_anim_v1.scn', False )
processPath( r'C:\temp\MT_03_06_006\mt_03_06_006_anim_v1.scn', False )

# 

C:\temp\MT_03_03_003\allo.txt
C:\temp\MT_03_04_004\mt_03_04_004_anim_v1.scn
C:\temp\MT_03_05_005_anim\mt_03_05_005_anim_v1.scn
C:\temp\MT_03_06_006\mt_03_06_006_anim_v1.scn


This is exactly what I was after. Thanks a lot!!

Bernard




On 9/8/05, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Bernard Lebel wrote:
> > Ok I think I understand what is going: I'm using a 0 in the
> > replacement argument, between the two groups. If I try with a letter
> > or other types of characters it works fine. So how can use a digit
> > here?
> 
> There is a longer syntax for \1 - \g<1> means the same thing but without the 
> ambiguity of where it ends. So you can use r'\g<1>0\2' as your substitution 
> string.
> 
> >>def matchShot( sSubString ):
> >>
> >># Create regular expression object
> >>oRe = re.compile( "(\d\d_\d\d\_)(\d\d)" )
> >>
> >>oMatch = oRe.search( sSubString )
> >>if oMatch != None:
> >>sNewString = oRe.sub( r'\10\2', sSubString )
> >>return sNewString
> >>else:
> >>return sSubString
> 
> You don't have to do the search, oRe.sub() won't do anything if there is no 
> match. Also if you are doing this a lot you should pull the re.compile() out 
> of the function (so oRe is a module variable), this is an expensive step that 
> only has to be done once.
> 
> You hinted in your original post that you are trying to find strings where 
> the last _\d\d has only two digits. The re you are using will also match 
> something like 'mt_03_04_044_anim' and your matchShot() will change that to 
> 'mt_03_04_0044_anim'. If that is not what you want you have to put some kind 
> of a guard at the end of the re - something that won't match a digit. If you 
> always have the _ at the end it is easy, just use r"(\d\d_\d\d\_)(\d\d_)". If 
> you can't count on the underscore you will have to be more clever.
> 
> Kent
> 
> ___
> 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] directory recursion

2005-09-09 Thread Kent Johnson
Rob Andrews wrote:
> I should already know this, and probably once did, but have never had
> a real world use for it until now.
> 
> What's a nice, clean way to recursively scan through directories with
> an arbitrary number of subdirectories?

Jason Orendorff's path module is awesome for this kind of job - it's as easy as 
this:

from path import path
basePath = path('C:/stuff/jayfiles')
for filePath in basePath.walkfiles('*.txt'):
  currentFile = open(filePath)
  # etc

Highly recommended.
http://www.jorendorff.com/articles/python/path/

Kent

> 
> In today's example, we're looking to grab the file name and third line
> of the file for every text file in the directory tree, and dump into a
> new text file. Everything but the walking of the tree was obvious
> enough.
> 
> We used the following to grab the desired output from a single level
> of directories:
> 
> import glob
> 
> for fileName in glob.glob('C:/stuff/jayfiles/*/*.txt'): # glob through
> directories
> newFile = open('C:/stuff/jayfiles/newFile.txt', 'a') # open
> newFile to append
> newFile.write(fileName) # append fileName to newFile
> newFile.write('\t') # append a tab after fileName
> currentFile = open(fileName, 'r') # open next file for reading
> currentFile.readline() # this and the following line go through...
> currentFile.readline() #...the 1st 2 lines of the file
> thirdLine = currentFile.readline() # modify this to print to text file
> newFile.write(thirdLine) # append thirdLine to newFile
> currentFile.close() # close currentFile
> newFile.close() # close newFile
> 
> -Rob
> ___
> 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] mamelauncher

2005-09-09 Thread Max Russell
Hi:

I've been working on this for ages and am having real
problems with getting the wiring for a selected game
to launch when I click OK.

I haven't added my error handling yet.

Can anyone help?

I've tried using spawn, system etc etc to no avail.

#Mame Launcher

#GUI launcher for MAME games

#First 'hack' 15th June 2005

#Hacking again 19th August



import sys, os, subprocess



from Tkinter import *



class Mamelaunch(Frame):

""" GUI application to display MAME games in 

a list, then launch them. """ 

def __init__(self, master):

""" Initialize the frame. """

Frame.__init__(self, master)

self.grid()

self.create_widgets()

self.listgames()



def create_widgets(self):

""" Create button, text, and entry widgets.
"""

# create instruction label

self.inst_lbl = Label(self, text = "Please
select a game")

self.inst_lbl.grid(row = 0, column = 0,
columnspan = 2, sticky = W)



# create label for password  

self.pw_lbl = Label(self, text = "Click OK
when ready ")

self.pw_lbl.grid(row = 12, column = 0, sticky
= W)



#create the scrollbar for the listbox

self.yScroll = Scrollbar ( self,
orient=VERTICAL )

self.yScroll.grid ( row=1, column=1,
sticky=N+S )



# create listbox to list games

self.lstbx =Listbox(self, height = 20,
yscrollcommand=self.yScroll.set, borderwidth = 5,

relief = "sunken",
highlightcolor = "blue", selectbackground="orange",

selectmode="single")

self.lstbx.grid(row = 1, column =
0,sticky=N+S+W)

#lock the vertical scroll to the listbox.

self.yScroll["command"] = self.lstbx.yview



# create ok button

self.submit_bttn = Button(self, text = "OK")

self.submit_bttn.grid(row = 12, column = 1,
sticky = S+W)

self.submit_bttn.bind("",
self.launchmame)



# create quit button

self.submit_bttn = Button(self, text = "Quit",
command = self.quit)

self.submit_bttn.grid(row = 12, column = 2,
sticky = S+W)



#Try reading list in prior to creating relevant
widgets

def listgames(self):

"""reads list and populates listbox"""

try:

mamefile = open('C:\\mamelist.txt',
'r').readlines()

except EnvironmentError:

print "Please check file is in directory"

else:

#split list, populate listbox

for game in mamefile:

game = game.rstrip()

self.lstbx.insert(END, game)



def launchmame(self, event):

"""Mechanism to launch MAME game"""

selection = self.lstbx.curselection()

print selection

os.system("C:\\mame096b\\mame.exe"+""+
selection)



#try:

#os.system(echo "game")

#except:

#SystemError(), "Command not found"



# main

root = Tk()

root.title("MAME Launcher")

root.geometry("220x330")



app = Mamelaunch(root)





root.mainloop()





___ 
To help you stay safe and secure online, we've developed the all new Yahoo! 
Security Centre. http://uk.security.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] mamelauncher

2005-09-09 Thread Danny Yoo


On Fri, 9 Sep 2005, Max Russell wrote:

> I've been working on this for ages and am having real problems with
> getting the wiring for a selected game to launch when I click OK.
>
> I haven't added my error handling yet.

[code cut]


Hi Max,

Hmmm... Out of curiosity, what happens if you try doing it without the
GUI?

Let's try to isolate the problem; it's not clear at the moment if there's
something weird with the GUI, or if there's something weird with the
os.system() call.

If you can write a quick test case that calls os.system() in the same way,
then we can be more sure what's causing the problem.


I see that you have a function called launchmame:

def launchmame(self, event):
selection = self.lstbx.curselection()
os.system("C:\\mame096b\\mame.exe"+""+selection)

(Ah.  I do see a possible problem here, but I want YOU to see it too.
*grin*)



Try testing out the function:

##
def run_mame_selection(selection):
os.system("C:\\mame096b\\mame.exe"+""+selection)
##

It's mostly a copy and paste of what you had in launchmame, except that we
explicitly pass in the selection string.  But try it out with a hardcoded
selection, and see if it succeeds.


As a side note, you may want to consider using the 'subprocess' module
instead of manually constructing command strings through string
concatenation: doing it by string concatenation is a bug-prone process.
'subprocess' is less bug-prone, and you can find out more here:

http://www.python.org/doc/lib/module-subprocess.html


Good luck!

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


Re: [Tutor] mamelauncher

2005-09-09 Thread Alan G
> I've been working on this for ages and am having real
> problems with getting the wiring for a selected game
> to launch when I click OK.

So what problems are you having? Do you get an error trace?
A superficial glance tells me only that
1) You might find using Tix will simplify your code(scrollable 
listboxes etc)
2) Your mailer seems to be adding extra lines, ie I assume the code 
isn't
   really double spaced? :-)

So whats the specific problem?
Oh yes - and what version of Python?

Alan G.

> I haven't added my error handling yet.
>
> Can anyone help?
>
> I've tried using spawn, system etc etc to no avail.
>
> #Mame Launcher
>
> #GUI launcher for MAME games
>
> #First 'hack' 15th June 2005
>
> #Hacking again 19th August
>
>
>
> import sys, os, subprocess
>
>
>
> from Tkinter import *
>
>
>
> class Mamelaunch(Frame):
>
>""" GUI application to display MAME games in
>
>a list, then launch them. """
>
>def __init__(self, master):
>
>""" Initialize the frame. """
>
>Frame.__init__(self, master)
>
>self.grid()
>
>self.create_widgets()
>
>self.listgames()
>
>
>
>def create_widgets(self):
>
>""" Create button, text, and entry widgets.
> """
>
># create instruction label
>
>self.inst_lbl = Label(self, text = "Please
> select a game")
>
>self.inst_lbl.grid(row = 0, column = 0,
> columnspan = 2, sticky = W)
>
>
>
># create label for password
>
>self.pw_lbl = Label(self, text = "Click OK
> when ready ")
>
>self.pw_lbl.grid(row = 12, column = 0, sticky
> = W)
>
>
>
>#create the scrollbar for the listbox
>
>self.yScroll = Scrollbar ( self,
> orient=VERTICAL )
>
>self.yScroll.grid ( row=1, column=1,
> sticky=N+S )
>
>
>
># create listbox to list games
>
>self.lstbx =Listbox(self, height = 20,
> yscrollcommand=self.yScroll.set, borderwidth = 5,
>
>relief = "sunken",
> highlightcolor = "blue", selectbackground="orange",
>
>selectmode="single")
>
>self.lstbx.grid(row = 1, column =
> 0,sticky=N+S+W)
>
>#lock the vertical scroll to the listbox.
>
>self.yScroll["command"] = self.lstbx.yview
>
>
>
># create ok button
>
>self.submit_bttn = Button(self, text = "OK")
>
>self.submit_bttn.grid(row = 12, column = 1,
> sticky = S+W)
>
>self.submit_bttn.bind("",
> self.launchmame)
>
>
>
># create quit button
>
>self.submit_bttn = Button(self, text = "Quit",
> command = self.quit)
>
>self.submit_bttn.grid(row = 12, column = 2,
> sticky = S+W)
>
>
>
>#Try reading list in prior to creating relevant
> widgets
>
>def listgames(self):
>
>"""reads list and populates listbox"""
>
>try:
>
>mamefile = open('C:\\mamelist.txt',
> 'r').readlines()
>
>except EnvironmentError:
>
>print "Please check file is in directory"
>
>else:
>
>#split list, populate listbox
>
>for game in mamefile:
>
>game = game.rstrip()
>
>self.lstbx.insert(END, game)
>
>
>
>def launchmame(self, event):
>
>"""Mechanism to launch MAME game"""
>
>selection = self.lstbx.curselection()
>
>print selection
>
>os.system("C:\\mame096b\\mame.exe"+""+
> selection)
>
>
>
> #try:
>
> #os.system(echo "game")
>
> #except:
>
> #SystemError(), "Command not found"
>
>
>
> # main
>
> root = Tk()
>
> root.title("MAME Launcher")
>
> root.geometry("220x330")
>
>
>
> app = Mamelaunch(root)
>
>
>
>
>
> root.mainloop()
>
>
>
>
>
> ___
> To help you stay safe and secure online, we've developed the all new 
> Yahoo! Security Centre. http://uk.security.yahoo.com
>
> 

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