Re: [Tutor] Using sys.exit()

2006-11-02 Thread Dick Moores
At 11:09 PM 11/1/2006, Luke Paireepinart wrote:
>>If I can manage to use "break", all 3 exits are silent. Why is it 
>>wrong to use "break" to exit?
>>
>'break' doesn't exit.  It ends a loop.
>It's not wrong to use a 'break' to exit a loop.  That's what it's there for.
>But what if you were doing something after the loop?
>'break' wouldn't help you there.

Yes, I realize that. But what if I'm not doing anything after the 
loop? In that case is there anything wrong with using break to end 
the script? I'm getting the idea from the responses that there IS 
something wrong, but I don't see what it is.

>A SystemExit immediately ends the program at that call
>(unless you catch the exception :)
>
>The reason the exits with break are 'silent'
>is because no exceptions are occurring.

But that's exactly what I want--a silent exit.

>SystemExit is an exception.
>There's nothing wrong with using it.
>You could raise an IOError if you wanted.

Please explain how to do that, and why I would want to.

Thanks,

Dick



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


Re: [Tutor] Using sys.exit()

2006-11-02 Thread Luke Paireepinart

>
> Yes, I realize that. But what if I'm not doing anything after the 
> loop? In that case is there anything wrong with using break to end the 
> script? I'm getting the idea from the responses that there IS 
> something wrong, but I don't see what it is.
Generally, something that exits with a break would be a normal exit case 
for a loop.  An exception would be an abnormal exit case.
Like...

while 1:
x = raw_input('choice? "hi",  "exit"  ')
if x == 'exit':
   break
elif x == 'hi':
   print "Hello!"
else:
   raise SystemExit

see, it only raises the error if the user inputs an invalid value.
>
>> A SystemExit immediately ends the program at that call
>> (unless you catch the exception :)
>>
>> The reason the exits with break are 'silent'
>> is because no exceptions are occurring.
>
> But that's exactly what I want--a silent exit.
So don't use exceptions then.
The point of exceptions is so that there's a traceback that the 
developer can see and
use to debug.
If that's not what you're trying to do, don't use an exception.

I never read your original code, so I'm not sure what you were doing,
and there may be other factors that the other Tutor subscribers felt 
contributed to the
decision of using SystemExit over break.
Just remember, SystemExit will always exit your program where you tell 
it to,
and depending on not having code after your loops so that it's not executed
when you break is probably a 'bad idea.'

>
>> SystemExit is an exception.
>> There's nothing wrong with using it.
>> You could raise an IOError if you wanted.
>
> Please explain how to do that, and why I would want to.
How to do it:
raise IOError

why?
No reason.
I was just pointing out that it doesn't particularly matter that you're 
raising a SystemExit.
Your program will terminate at any exception that's raised, and you will 
get an identical traceback.
The only reason you want to use SystemExit, is so that if someone else 
is using your function, they can capture the
SystemExit (with an except: statement) and do something with it.
An example of this would be, if you had the function

def convert_to_int(astr):
for item in astr:
   if item.isalpha() == True:
  raise SystemExit
return int(astr)

and I wanted to use it to convert user input to an integer,
I'd do

try:
a = convert_to_int(raw_input('please enter an integer: '))
except SystemExit:
print "You entered some alpha characters!"

Note that ValueError would be more appropriate here, instead of SystemExit.
Also note the function doesn't check for characters that aren't alpha or 
numbers, so a $ will pass our item.isalpha() test,
and when the function attempts to return int(astr) the int call will 
raise a ValueError.

Obviously, it would be less helpful if everything just raised one type 
of error, so that's why there's different types.
It's up to you to standardize their usage, though.  You can write 
classes that raises ValueErrors whenever anything goes
wrong, but why would you want to?
Remember, Python expects that the developer will be responsible.  It 
won't keep you from shooting yourself in the foot.
So try to raise reasonable exceptions.

I think SystemExit may have some extra magic, and it's not just a normal 
exception,
but I'm not sure about this.  Someone else know?

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


[Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Dick Moores
I'm working on a program named unitConversion.py. In it, I give the 
user a chance to see a list of all the measurement units the program 
handles, and their abbreviations. The user needs the abbreviations to 
do the conversions. So I have a couple of functions (see below) that 
together will print a list of unit abbreviations and their full names 
(but not their respective categories). At this point there are 46 
units, and that's a long list for the user to see if the printing is 
done one unit per line. What I'd like to do is print the list in 
maybe 3 neat columns. I'm sure this is possible, but after hours of 
experimentation, I can't get a neat one to print. I know I could 
stick a neat 3-column one in the script, but I'd like to learn how it 
could be done with just the two functions 
allUnitsAndTheirAbbreviationsAndCategories() and a modification of 
printListOfAllUnitsAndAbbreviations().

BTW allUnitsAndTheirAbbreviationsAndCategories() is used elsewhere in 
the program, so I don't want to change it, if possible.

Thanks very much,

Dick Moores

def allUnitsAndTheirAbbreviationsAndCategories():
"""
A list of all units, their abbreviations and categories.
"""
abbs = [
'l mi: mile',
'l km: kilometer',
'l m: meter',
'l yd: yard',
'l ft: foot',
'l in: inch',
'l cm: centimeter',
'l mm: millimeter',
'l fur: furlong',
'l lea: league',
'l nm: nautical mile',
'a ha: hectare',
'a ac: acre',
'a mi2: square mile',
'a km2: square kilometer',
'a m2: square meter',
'a yd2: square yard',
'a ft2: square foot',
'a in2: square inch',
'a cm2: square centimeter',
'w kg: kilogram',
'w lb: pound',
'w gm: gram',
'w oz: ounce',
'v qt: quart',
'v oz: ounce',
'v l: liter',
'v ml: milliliter',
'v gal: gallon',
'v tbsp: tablespoon',
'v tsp: teaspoon',
'v impgal: Imperial Gallon',
'v yd3: cubic yard',
'v m3: cubic meter',
'v ft3: cubic foot',
'v mi3: cubic mile',
'v km3: cubic kilometer',
't F: Fahrenheit',
't C: Celsius',
't K: Kelvin',
's mph: miles per hour',
's knots: knots',
's mps: miles per second',
's fps: feet per second',
'd deg: degree',
'd rad: radian'
]
return abbs

def printListOfAllUnitsAndAbbreviations():
"""
Prints a list of all units and their abbreviations, but not their 
categories.
"""
lstAll = allUnitsAndTheirAbbreviationsAndCategories()
for x in lstAll:
print x[2:]
print

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


Re: [Tutor] Using sys.exit()

2006-11-02 Thread Andreas Kostyrka
Am Mittwoch, den 01.11.2006, 22:16 -0800 schrieb Dick Moores:
> At 03:56 PM 11/1/2006, Andreas Kostyrka wrote:
> >Am Mittwoch, den 01.11.2006, 15:43 -0800 schrieb Dick Moores:
> > > At 12:14 AM 10/31/2006, Alan Gauld wrote:
> > >
> > > >"Dick Moores" <[EMAIL PROTECTED]> wrote
> > > > > I'd like to know how to use sys.exit() to quit a program.
> > > > >
> > > >
> > > >I see that you already figured that out.
> > > >You can also quit by raising SystemExit, which is
> > > >what sys.exit does... but you don't need to import sys...
> > >
> > > I'm afraid I don't know what you mean. How do I raise SystemExit, and
> > > why don't I need to import sys?
> >
> >raise SystemExit(2)
> >
> >is equal to sys.exit(2) (actually sys.exit(2) just raises SystemExit(2))
> 
> OK, that works well. But why the 2?

2 is the usual error code for invalid cmdline parameters in the Unix
world. Just an example here.

> 
> BTW at the command line, "raise SystemExit(2)" produces a completely 
> silent exit. In Win IDE I get "SystemExit: 2". With IDLE:
> 
> Traceback (most recent call last):
>File "E:\Python25\dev\1unitConversion5a.py", line 425, in 
>  main()
>File "E:\Python25\dev\1unitConversion5a.py", line 413, in main
>  s = formatAndCheckStringFromUser(s)
>File "E:\Python25\dev\1unitConversion5a.py", line 342, in 
> formatAndCheckStringFromUser
>  s = stripResponseAndCheckForUserRequestForHelpOrToQuit(s)
>File "E:\Python25\dev\1unitConversion5a.py", line 253, in 
> stripResponseAndCheckForUserRequestForHelpOrToQuit
>  raise SystemExit(2)
> SystemExit: 2
> 
> If I can manage to use "break", all 3 exits are silent. Why is it 
> wrong to use "break" to exit?

Because it does not:

for i in xrange(50):
for j in xrange(50, 100):
if j == 77:
break

will not stop the program when it hits the break.

But yes, there are no reason why you should not let your script just
end.

Andreas

> 
> Dick Moores
> 
> Dick Moores
> 


signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Luke Paireepinart
Instead of helping you with your specific problem, I'll give you this 
information and see what you can make of it.

 >>> print 'a'.ljust(20)+'b'.ljust(20)
a   b  
 >>> print 'carrah'.ljust(20)+'foobar'.ljust(20)
carrah  foobar 


Notice how they're all lined up on the left (if the font in this e-mail 
is fixed-width.  Either way, the number of spaces for both columns is 
the same.)

ljust's functionality is essentially this:

def left_justify(astr,width):
x = len(astr)
while x < width:
astr += ' '
x += 1

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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Dick Moores
At 01:45 AM 11/2/2006, Luke Paireepinart wrote:
>Instead of helping you with your specific problem, I'll give you this
>information and see what you can make of it.
>
>  >>> print 'a'.ljust(20)+'b'.ljust(20)
>a   b
>  >>> print 'carrah'.ljust(20)+'foobar'.ljust(20)
>carrah  foobar
>
>
>Notice how they're all lined up on the left (if the font in this e-mail
>is fixed-width.  Either way, the number of spaces for both columns is
>the same.)
>
>ljust's functionality is essentially this:
>
>def left_justify(astr,width):
> x = len(astr)
> while x < width:
> astr += ' '
> x += 1

Ah, that's beautiful! Thanks, Luke! (And thanks Python!) Didn't know 
about ljust(). Here's my modified printListOfAllUnitsAndAbbreviations().

def printListOfAllUnitsAndAbbreviations():
 """
 Prints a list of all units and their abbreviations, but not 
their categories.
 """
 lstAll = allUnitsAndTheirAbbreviationsAndCategories()
 for i in range(0, len(lstAll)-1, 3):
 print lstAll[i][2:].ljust(27) + 
lstAll[i+1][2:].ljust(27) + lstAll[i+2][2:].ljust(27)
 print

Dick

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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Kent Johnson
Luke Paireepinart wrote:
> Instead of helping you with your specific problem, I'll give you this 
> information and see what you can make of it.
> 
>  >>> print 'a'.ljust(20)+'b'.ljust(20)
> a   b  
>  >>> print 'carrah'.ljust(20)+'foobar'.ljust(20)
> carrah  foobar

Another way to do this is with string formatting, I think it is a more 
readable and flexible solution:

In [1]: print '%-20s %-20s' % ('a', 'b')
ab

In [2]: print '%-20s %-20s' % ('carrah', 'foobar')
carrah   foobar

See this page for details:
http://docs.python.org/lib/typesseq-strings.html

Kent

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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Dick Moores
At 03:13 AM 11/2/2006, Kent Johnson wrote:
>Luke Paireepinart wrote:
> > Instead of helping you with your specific problem, I'll give you this
> > information and see what you can make of it.
> >
> >  >>> print 'a'.ljust(20)+'b'.ljust(20)
> > a   b
> >  >>> print 'carrah'.ljust(20)+'foobar'.ljust(20)
> > carrah  foobar
>
>Another way to do this is with string formatting, I think it is a more
>readable and flexible solution:
>
>In [1]: print '%-20s %-20s' % ('a', 'b')
>ab
>
>In [2]: print '%-20s %-20s' % ('carrah', 'foobar')
>carrah   foobar
>
>See this page for details:
>http://docs.python.org/lib/typesseq-strings.html

Thanks, Kent. I agree. So now that function has become

def printListOfAllUnitsAndAbbreviations():
 """
 Prints a 3-column list of all units and their abbreviations, 
but not their categories.
 """
 lstAll = allUnitsAndTheirAbbreviationsAndCategories()
 for i in range(0, len(lstAll)-1 ,3):
 print '%-27s %-27s %-27s' % (lstAll[i][2:], 
lstAll[i+1][2:], lstAll[i+2][2:])
 print



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


[Tutor] Cal command in python...

2006-11-02 Thread Asrarahmed Kadri
 
Folks,
 
Does anybody have an idea of the logic used in cal command... I want to know the algorithm so that I can implement in Python.
 
A pseudo code might be helpful...
 
TIA.
 
Regards,
~Asrarahmed~
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cal command in python...

2006-11-02 Thread Kent Johnson
Asrarahmed Kadri wrote:
> 
>  
> Folks,
>  
> Does anybody have an idea of the logic used in cal command... I want to 
> know the algorithm so that I can implement in Python.

See the calendar module. Source code in the library if you want to see 
how it is done.

In [1]: import calendar

In [2]: calendar.prmonth(2006, 10)
 October 2006
Mo Tu We Th Fr Sa Su
1
  2  3  4  5  6  7  8
  9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31

Kent

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


Re: [Tutor] Cal command in python...

2006-11-02 Thread Asrarahmed Kadri
 
I got the command and saw its output..? But where to look for the source code..?
Which library ?
 
TIA.
 
Regards,
Asrarahmed
 
 
On 11/2/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Asrarahmed Kadri wrote:>>> Folks,>> Does anybody have an idea of the logic used in cal command... I want to
> know the algorithm so that I can implement in Python.See the calendar module. Source code in the library if you want to seehow it is done.In [1]: import calendarIn [2]: calendar.prmonth
(2006, 10)October 2006Mo Tu We Th Fr Sa Su   12  3  4  5  6  7  89 10 11 12 13 14 1516 17 18 19 20 21 2223 24 25 26 27 28 2930 31Kent
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Cal command in python...

2006-11-02 Thread Kent Johnson
Asrarahmed Kadri wrote:
>  
> I got the command and saw its output..? But where to look for the source 
> code..?
> Which library ?

In the Python standard library. Much of the library is written in Python 
and supplied as source. On Windows it will be something like 
C:\Python25\Lib\calendar.py. On other platforms I don't know the path 
but it will be part of the Python installation.

Kent

>  
> TIA.
>  
> Regards,
> Asrarahmed
>  
> 
>  
> On 11/2/06, *Kent Johnson* <[EMAIL PROTECTED] > 
> wrote:
> 
> Asrarahmed Kadri wrote:
>  >
>  >
>  > Folks,
>  >
>  > Does anybody have an idea of the logic used in cal command... I
> want to
>  > know the algorithm so that I can implement in Python.
> 
> See the calendar module. Source code in the library if you want to see
> how it is done.
> 
> In [1]: import calendar
> 
> In [2]: calendar.prmonth (2006, 10)
> October 2006
> Mo Tu We Th Fr Sa Su
>1
> 2  3  4  5  6  7  8
> 9 10 11 12 13 14 15
> 16 17 18 19 20 21 22
> 23 24 25 26 27 28 29
> 30 31
> 
> Kent
> 
> 
> 
> 
> -- 
> To HIM you shall return.


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


Re: [Tutor] Cal command in python...

2006-11-02 Thread Simon Brunning
On 11/2/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> In the Python standard library. Much of the library is written in Python
> and supplied as source. On Windows it will be something like
> C:\Python25\Lib\calendar.py. On other platforms I don't know the path
> but it will be part of the Python installation.

If you do:

import calendar
print calendar.__file__

That will tell you where it is on your system. Works for any module.

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Dick Moores
At 03:31 AM 11/2/2006, you wrote:
>At 03:13 AM 11/2/2006, Kent Johnson wrote:
> >Luke Paireepinart wrote:
> > > Instead of helping you with your specific problem, I'll give you this
> > > information and see what you can make of it.
> > >
> > >  >>> print 'a'.ljust(20)+'b'.ljust(20)
> > > a   b
> > >  >>> print 'carrah'.ljust(20)+'foobar'.ljust(20)
> > > carrah  foobar
> >
> >Another way to do this is with string formatting, I think it is a more
> >readable and flexible solution:
> >
> >In [1]: print '%-20s %-20s' % ('a', 'b')
> >ab
> >
> >In [2]: print '%-20s %-20s' % ('carrah', 'foobar')
> >carrah   foobar
> >
> >See this page for details:
> >http://docs.python.org/lib/typesseq-strings.html
>
>Thanks, Kent. I agree. So now that function has become
>
>def printListOfAllUnitsAndAbbreviations():
>  """
>  Prints a 3-column list of all units and their abbreviations,
>but not their categories.
>  """
>  lstAll = allUnitsAndTheirAbbreviationsAndCategories()
>  for i in range(0, len(lstAll)-1 ,3):
>  print '%-27s %-27s %-27s' % (lstAll[i][2:],
>lstAll[i+1][2:], lstAll[i+2][2:])
>  print

Oops! Got overconfident. Didn't check to see if it actually printed 
the whole list. It didn't. Left off "rad: radian", because there are 
46 items in the list (46%3 is 1, not 0). So now the only way I could 
see to print all 46 was to add 2 empty dummies to make 48, which is 
divisible by 3, and also modify the range in the second function. Is 
there a better way, which is also a general solution that will work 
when I subtract or add to the list? See the two  modified functions below.

Dick


def allUnitsAndTheirAbbreviationsAndCategories():
 """
 A list of all units, their abbreviations and categories.
 """
 abbs = [
 'l mi: mile',
 'l km: kilometer',
 'l m: meter',
 'l yd: yard',
 'l ft: foot',
 'l in: inch',
 'l cm: centimeter',
 'l mm: millimeter',
 'l fur: furlong',
 'l lea: league',
 'l nm: nautical mile',
 'a ha: hectare',
 'a ac: acre',
 'a mi2: square mile',
 'a km2: square kilometer',
 'a m2: square meter',
 'a yd2: square yard',
 'a ft2: square foot',
 'a in2: square inch',
 'a cm2: square centimeter',
 'w kg: kilogram',
 'w lb: pound',
 'w gm: gram',
 'w oz: ounce',
 'v qt: quart',
 'v oz: ounce',
 'v l: liter',
 'v ml: milliliter',
 'v gal: gallon',
 'v tbsp: tablespoon',
 'v tsp: teaspoon',
 'v impgal: Imperial Gallon',
 'v yd3: cubic yard',
 'v m3: cubic meter',
 'v ft3: cubic foot',
 'v mi3: cubic mile',
 'v km3: cubic kilometer',
 't F: Fahrenheit',
 't C: Celsius',
 't K: Kelvin',
 's mph: miles per hour',
 's knots: knots',
 's mps: miles per second',
 's fps: feet per second',
 'd deg: degree',
 'd rad: radian',
 '   ',
 '   '
 ]
 return abbs

def printListOfAllUnitsAndAbbreviations():
 """
 Prints a 3-column list of all units and their abbreviations, 
but not their categories.
 """
 lstAll = allUnitsAndTheirAbbreviationsAndCategories()
 for i in range(0, len(lstAll), 3):
 print '%-27s %-27s %-27s' % (lstAll[i][2:], 
lstAll[i+1][2:], lstAll[i+2][2:])
 print

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


[Tutor] Performing arithmetic operations with date

2006-11-02 Thread Asrarahmed Kadri
 
Hello Guys...
 
I want to perform arithmetic operations on date supplied by the user on the command line.
 
Is there any built-in utility for this..??
 
TIA.
 
Regards,
Asrarahmed
 
 
 
-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Performing arithmetic operations with date

2006-11-02 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
[question about dates and times]
Asrarahmed, please check google.com and other resources before asking on 
the list.

A google of 'python date module'
brought the page
http://pleac.sourceforge.net/pleac_python/datesandtimes.html
as the first link,
which has examples on usage.
The second link down is http://docs.python.org/lib/module-datetime.html
which is the module definition from Python.org.

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


Re: [Tutor] str.strip() help

2006-11-02 Thread Christopher Arndt
John Fouhy schrieb:
> On 02/11/06, Chris Hengge <[EMAIL PROTECTED]> wrote:
> myStr = "I want to strip my words."
> print myStr.strip("my")
> 'I want to strip words.'
> 
> .strip() only removes text from the beginning and end of the string.

It is generally used to remove whitespace from the start/end of a string, e.g.
removing the newline character from the end of a line of text.

But you can also specify which characters to strip. Note that the argument is
not a string to strip off, but rather a collection of characters, any of which
should be stripped off, e.g.

>>> r = "I want to strip my words."
>>> r.strip('I. ')  # note the space
'want to strip my words'


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


Re: [Tutor] Performing arithmetic operations with date

2006-11-02 Thread Christopher Arndt
Asrarahmed Kadri schrieb:
> I want to perform arithmetic operations on date supplied by the user on the
> command line.
> 
> Is there any built-in utility for this..??

Not built-in, but very useful:

http://labix.org/python-dateutil

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


Re: [Tutor] Print Screen

2006-11-02 Thread Luke Paireepinart
Chris Hengge wrote:
> I posted this in a similar thread a few days ago, and no replies so I 
> think it needs its own listing.
>
> Anyone know of a way to capture special keys like "Print Screen"?
> I have a small script to grab all they keycodes, but it doesn't seem 
> to catch several keys on the keyboard. I've got a utility that I'd 
> like to be able to automagically get a screenshot when something goes 
> wrong so I dont have to hope the user can re-create the error. 
> Universal support would be best, but WinXP is the main OS
Why do you need to capture the keypress 'print screen' if you're 
automatically taking screenshots when something goes wrong?
>
> Thanks.
> 
>
> ___
> 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] Print Screen

2006-11-02 Thread Chris Hengge
I posted this in a similar thread a few days ago, and no replies so I think it needs its own listing. Anyone know of a way to capture special keys like "Print Screen"?I
have a small script to grab all they keycodes, but it doesn't seem to
catch several keys on the keyboard. I've got a utility that I'd like to
be able to automagically get a screenshot when something goes wrong so
I dont have to hope the user can re-create the error. Universal support
would be best, but WinXP is the main OSThanks.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Markus Rosenstihl


Am 02.11.2006 um 15:14 schrieb Dick Moores:

> At 03:31 AM 11/2/2006, you wrote:
>> At 03:13 AM 11/2/2006, Kent Johnson wrote:
>>> Luke Paireepinart wrote:
 Instead of helping you with your specific problem, I'll give you 
 this
 information and see what you can make of it.

>>> print 'a'.ljust(20)+'b'.ljust(20)
 a   b
>>> print 'carrah'.ljust(20)+'foobar'.ljust(20)
 carrah  foobar
>>>
>>> Another way to do this is with string formatting, I think it is a 
>>> more
>>> readable and flexible solution:
>>>
>>> In [1]: print '%-20s %-20s' % ('a', 'b')
>>> ab
>>>
>>> In [2]: print '%-20s %-20s' % ('carrah', 'foobar')
>>> carrah   foobar
>>>
>>> See this page for details:
>>> http://docs.python.org/lib/typesseq-strings.html
>>
>> Thanks, Kent. I agree. So now that function has become
>>
>> def printListOfAllUnitsAndAbbreviations():
>>  """
>>  Prints a 3-column list of all units and their abbreviations,
>> but not their categories.
>>  """
>>  lstAll = allUnitsAndTheirAbbreviationsAndCategories()
>>  for i in range(0, len(lstAll)-1 ,3):
>>  print '%-27s %-27s %-27s' % (lstAll[i][2:],
>> lstAll[i+1][2:], lstAll[i+2][2:])
>>  print
>
> Oops! Got overconfident. Didn't check to see if it actually printed
> the whole list. It didn't. Left off "rad: radian", because there are
> 46 items in the list (46%3 is 1, not 0). So now the only way I could
> see to print all 46 was to add 2 empty dummies to make 48, which is
> divisible by 3, and also modify the range in the second function. Is
> there a better way, which is also a general solution that will work
> when I subtract or add to the list? See the two  modified functions 
> below.
>
> Dick
>
>
> def allUnitsAndTheirAbbreviationsAndCategories():
>  """
>  A list of all units, their abbreviations and categories.
>  """
>  abbs = [
>  'l mi: mile',
>  'l km: kilometer',
>  'l m: meter',
>  'l yd: yard',
>  'l ft: foot',
>  'l in: inch',
>  'l cm: centimeter',
>  'l mm: millimeter',
>  'l fur: furlong',
>  'l lea: league',
>  'l nm: nautical mile',
>  'a ha: hectare',
>  'a ac: acre',
>  'a mi2: square mile',
>  'a km2: square kilometer',
>  'a m2: square meter',
>  'a yd2: square yard',
>  'a ft2: square foot',
>  'a in2: square inch',
>  'a cm2: square centimeter',
>  'w kg: kilogram',
>  'w lb: pound',
>  'w gm: gram',
>  'w oz: ounce',
>  'v qt: quart',
>  'v oz: ounce',
>  'v l: liter',
>  'v ml: milliliter',
>  'v gal: gallon',
>  'v tbsp: tablespoon',
>  'v tsp: teaspoon',
>  'v impgal: Imperial Gallon',
>  'v yd3: cubic yard',
>  'v m3: cubic meter',
>  'v ft3: cubic foot',
>  'v mi3: cubic mile',
>  'v km3: cubic kilometer',
>  't F: Fahrenheit',
>  't C: Celsius',
>  't K: Kelvin',
>  's mph: miles per hour',
>  's knots: knots',
>  's mps: miles per second',
>  's fps: feet per second',
>  'd deg: degree',
>  'd rad: radian',
>  '   ',
>  '   '
>  ]
>  return abbs
>
> def printListOfAllUnitsAndAbbreviations():
>  """
>  Prints a 3-column list of all units and their abbreviations,
> but not their categories.
>  """
>  lstAll = allUnitsAndTheirAbbreviationsAndCategories()
>  for i in range(0, len(lstAll), 3):
>  print '%-27s %-27s %-27s' % (lstAll[i][2:],
> lstAll[i+1][2:], lstAll[i+2][2:])
>  print
>


Try somthing like this:

In [32]: a=range(100)
In [33]: for i in range(0,len(a)):
: print '%-27s'%a[i],
: if (i+1)%3 == 0: print "\n"

0   1   2

3   4   5
...
93  94  95

96  97  98

99


Note the comma after the first print statement

Regards
Markus

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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Kent Johnson
Dick Moores wrote:
> Oops! Got overconfident. Didn't check to see if it actually printed 
> the whole list. It didn't. Left off "rad: radian", because there are 
> 46 items in the list (46%3 is 1, not 0). So now the only way I could 
> see to print all 46 was to add 2 empty dummies to make 48, which is 
> divisible by 3, and also modify the range in the second function. Is 
> there a better way, which is also a general solution that will work 
> when I subtract or add to the list? See the two  modified functions below.

There are almost enough grouping recipes in the cookbook to give them 
their own category. They tend to be fairly obscure. There is one in the 
comment on this page that would work for you:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496958

Or you could make a new list and pad it with spaces when you print, or 
use Markus' solution which is simple and clear.

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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Dick Moores
At 11:33 AM 11/2/2006, Markus Rosenstihl wrote:
>Try somthing like this:
>
>In [32]: a=range(100)
>In [33]: for i in range(0,len(a)):
> : print '%-27s'%a[i],
> : if (i+1)%3 == 0: print "\n"
>
>0   1   2
>
>3   4   5
>...
>93  94  95
>
>96  97  98
>
>99
>
>
>Note the comma after the first print statement

Yes, thanks, but the reason I wanted 3 columns was to compress the 
height of the list printout for the user, so I don't want all those 
blank lines.

Dick



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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Dick Moores
At 11:51 AM 11/2/2006, Kent Johnson wrote:
>Dick Moores wrote:
>>Oops! Got overconfident. Didn't check to see if it actually printed 
>>the whole list. It didn't. Left off "rad: radian", because there 
>>are 46 items in the list (46%3 is 1, not 0). So now the only way I 
>>could see to print all 46 was to add 2 empty dummies to make 48, 
>>which is divisible by 3, and also modify the range in the second 
>>function. Is there a better way, which is also a general solution 
>>that will work when I subtract or add to the list? See the 
>>two  modified functions below.
>
>There are almost enough grouping recipes in the cookbook to give 
>them their own category. They tend to be fairly obscure. There is 
>one in the comment on this page that would work for you:
>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496958

Thanks for digging that out, Kent. If you think that one in the 
comment is obscure, imagine how it looks to me. It'll take a lot of 
study. I may ask some questions..

Dick

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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Kent Johnson
Dick Moores wrote:
> At 11:33 AM 11/2/2006, Markus Rosenstihl wrote:
>> Try somthing like this:
>>
>> In [32]: a=range(100)
>> In [33]: for i in range(0,len(a)):
>> : print '%-27s'%a[i],
>> : if (i+1)%3 == 0: print "\n"
>>
>> 0   1   2
>>
>> 3   4   5
>> ...
>> 93  94  95
>>
>> 96  97  98
>>
>> 99
>>
>>
>> Note the comma after the first print statement
> 
> Yes, thanks, but the reason I wanted 3 columns was to compress the 
> height of the list printout for the user, so I don't want all those 
> blank lines.

Just change 'print "\n"' to 'print'

Kent

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


Re: [Tutor] Need to be taught a trick or two about printing in neat columns

2006-11-02 Thread Dick Moores
At 12:35 PM 11/2/2006, Kent Johnson wrote:
>Dick Moores wrote:
>>At 11:33 AM 11/2/2006, Markus Rosenstihl wrote:
>>>Try somthing like this:
>>>
>>>In [32]: a=range(100)
>>>In [33]: for i in range(0,len(a)):
>>> : print '%-27s'%a[i],
>>> : if (i+1)%3 == 0: print "\n"
>>>
>>>0   1   2
>>>
>>>3   4   5
>>>...
>>>93  94  95
>>>
>>>96  97  98
>>>
>>>99
>>>
>>>
>>>Note the comma after the first print statement
>>Yes, thanks, but the reason I wanted 3 columns was to compress the 
>>height of the list printout for the user, so I don't want all those 
>>blank lines.
>
>Just change 'print "\n"' to 'print'
>
>Kent

Of course! Don't know why I didn't see that.

Thanks again, Kent and Markus.

Dick



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


Re: [Tutor] Print Screen

2006-11-02 Thread Chris Hengge
Because I dont know any other way to capture the screen? (In my mind using print screen would be universal) =POn 11/2/06, Luke Paireepinart <
[EMAIL PROTECTED]> wrote:Chris Hengge wrote:> I posted this in a similar thread a few days ago, and no replies so I
> think it needs its own listing.>> Anyone know of a way to capture special keys like "Print Screen"?> I have a small script to grab all they keycodes, but it doesn't seem> to catch several keys on the keyboard. I've got a utility that I'd
> like to be able to automagically get a screenshot when something goes> wrong so I dont have to hope the user can re-create the error.> Universal support would be best, but WinXP is the main OSWhy do you need to capture the keypress 'print screen' if you're
automatically taking screenshots when something goes wrong?>> Thanks.> >> ___
> 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] Print Screen

2006-11-02 Thread Luke Paireepinart
Chris Hengge wrote:
> Because I dont know any other way to capture the screen? (In my mind 
> using print screen would be universal) =P
The print screen button doesn't do anything.
It generates a keycode just like any other button on the keyboard.
Windows captures this keypress and interprets it as you wanting a 
screenshot.
There is no inherent operation tied to this specific button that creates 
a screenshot.
So yeah, you could probably go the route of generating a printscreen 
keypress, but
there are much easier ways to do that.
For example,
Install PIL,
then do
 >>> import ImageGrab
 >>> ImageGrab.grab().save('temp.jpg')
That's all there is to it.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print Screen

2006-11-02 Thread Luke Paireepinart
Chris Hengge wrote:
> Awesome! Thanks again Luke
>
> How do I capture the keycode for print screen? (now I'm just curious, 
> because like I said, I've got a script that grabs all but maybe half a 
> dozen keys)
Well, how are you doing it now?
That's the important part.
>
> On 11/2/06, *Luke Paireepinart* <[EMAIL PROTECTED] 
> > wrote:
>
> Chris Hengge wrote:
> > Because I dont know any other way to capture the screen? (In my mind
> > using print screen would be universal) =P
> The print screen button doesn't do anything.
> It generates a keycode just like any other button on the keyboard.
> Windows captures this keypress and interprets it as you wanting a
> screenshot.
> There is no inherent operation tied to this specific button that
> creates
> a screenshot.
> So yeah, you could probably go the route of generating a printscreen
> keypress, but
> there are much easier ways to do that.
> For example,
> Install PIL,
> then do
> >>> import ImageGrab
> >>> ImageGrab.grab().save('temp.jpg')
> That's all there is to it.
>
>

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


Re: [Tutor] Print Screen

2006-11-02 Thread Terry Carroll
On Thu, 2 Nov 2006, Luke Paireepinart wrote:

>  >>> import ImageGrab
>  >>> ImageGrab.grab().save('temp.jpg')

I never knew about that.  Thanks, that's pretty cool.

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


Re: [Tutor] Using sys.exit()

2006-11-02 Thread Alan Gauld

"Dick Moores" <[EMAIL PROTECTED]> wrote
>>You can use an argument if you want to pass an error value
>>back to the OS. This is good practice if your script might be
>>used in a batch file or shell script
>
> So what should that value be?

Zero means no errors and is the default value.

But you can define any non zero values that you like and so
long as you document them users of tyour script can tell why
the script stopped.

Thus in MSDOS you could write a batch file:

PYTHON MYSCRIPT.PY
IF ERRORLEVEL == 1 ECHO 'NO INPUT'
IF ERRORLEVEL == 2 ECHO 'INVALID INPUTS'

etc etc.

> don't, because I don't (yet) use python to write either batch files
> or shell scripts.

Its not about using Python to write the scripts itcs about
*using* a python script inside a batch file/shell script

This also applies if you use a script from within an
os.system() call since os.system() returns the exit
value of the command that you execute. Thus

err = os.system("python myscript.py")
print err

err will contain the value passed out by myscript.py as
an exit code. The default will be zero which implies that
myscript ran successfully. But if you provide meaningful
exit codes you can test for those when using os.system().

>>break is not intended to quit programs, break is intended
>>to quit loops. To exit a program you should use sys.exit()
>>and if its an abnormal exit provide an argument.
>
> Of course, I've been using break to exit only when it works. Why is
> it wrong to do so?

Only in that there will be no error value passed back.

break sdoesn't really exit the program it just forces execution
to fall off the end of your script.

for n in range(10):
pass

Will execute silently and end

n = 0
while True:
if n > 9: break

will do exactly the same

Both programs exit when they run out of code to execute.

sys.exit() just provides a bit more control over how the script exits
and this makes it slightly easier to use the script within a batch
file etc..

-- 
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] How to capture 'Ctrl+c' in Python

2006-11-02 Thread Alan Gauld

"Chris Hengge" <[EMAIL PROTECTED]> wrote
> Do you by chance know of a way to capture special keys like "Print 
> Screen"?

Try the key capture code in my Event Driven topic.

So far as I know it works for all keys including the special ones.
It also points out that those keys have a two part code...

-- 
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


[Tutor] setlocale on windows

2006-11-02 Thread frank h.
Hello all,I wrote a script on UNIX that uses the following statements:import locale, datetimelocale.setlocale(locale.LC_ALL, 'sv_Se')with that, I can get localized dates like this> datetime.datetime.today
().strftime('%A')'Fredag'problem is, this doesnt work on windows!I get:locale.Error: unsupported locale settinghow can I set the locale to Swedish on a windows box?thanks for any insight you might have
-frank
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print Screen

2006-11-02 Thread Bill Burns
Chris Hengge wrote:
> I posted this in a similar thread a few days ago, and no replies so I 
> think it needs its own listing.
> 
> Anyone know of a way to capture special keys like "Print Screen"?
> I have a small script to grab all they keycodes, but it doesn't seem to 
> catch several keys on the keyboard. I've got a utility that I'd like to 
> be able to automagically get a screenshot when something goes wrong so I 
> dont have to hope the user can re-create the error. Universal support 
> would be best, but WinXP is the main OS
> 

I'm not exactly sure what you want here :-) but if you want to capture
when the 'Print Screen' key (or any other key) has actually been
pressed, try pyHook. Note: pyHook only works on Windows!

Here's some sample code:



"""
Captures a press of the 'Print Screen' key.
The following requires ctypes and pyHook.
ctypes is standard in Python2.5.

ctypes -> http://sourceforge.net/projects/ctypes/
pyHook -> http://www.cs.unc.edu/Research/assist/developer.shtml
"""
from ctypes import windll, byref
from ctypes.wintypes import MSG

import pyHook

user32 = windll.user32

def keyboardEvent(event):
 if event.KeyID == 44: print "You hit 'Print Screen'!"
 return True

hm = pyHook.HookManager()
hm.KeyDown = keyboardEvent
hm.HookKeyboard()
msg = MSG()
while user32.GetMessageA(byref(msg), None, 0, 0):
 user32.TranslateMessage(byref(msg))
 user32.DispatchMessageA(byref(msg))



HTH,

Bill




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


Re: [Tutor] One million and counting

2006-11-02 Thread Daniel McQuay
I second Jorge, I also learned from your site. well done,On 10/31/06, Glenn T Norton <[EMAIL PROTECTED]
> wrote:Alan Gauld wrote:>Hi folks,>>In just thought I'd mention that my web tutor has now passed
>the million visitors mark. Thanks to all those on the tutor>list who have paid a visit.>>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>>>Congratulations Alan! I visited your site many times when first learningPython.Keep up the good work.Glenn--"Ketchup. For the good times... " - Ketchup Advisory Board
Glenn NortonApplication DeveloperNebraska.gov1-402-471-2777[EMAIL PROTECTED]___
Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor
-- Daniel McQuayboxster.homelinux.orgH: 814.825.0847M: 814-341-9013
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Print Screen

2006-11-02 Thread Luke Paireepinart

>> Anyone know of a way to capture special keys like "Print Screen"?
>> I have a small script to grab all they keycodes, but it doesn't seem to 
>> catch several keys on the keyboard. I've got a utility that I'd like to 
>> be able to automagically get a screenshot when something goes wrong so I 
>> dont have to hope the user can re-create the error. Universal support 
>> would be best, but WinXP is the main OS
>>
>> 
>
> I'm not exactly sure what you want here :-) but if you want to capture
> when the 'Print Screen' key (or any other key) has actually been
> pressed, try pyHook. Note: pyHook only works on Windows!
>   
Also note that if you want all of the keypresses, but you _don't_ care 
about the application with focus
receiving the input, you can do a complete key grab using TKInter or 
Pygame, and probably the other GUI packages too.
But, like I said, if you were, for example, typing an e-mail and you 
started a script that did a complete grab like this, you'd no longer be 
able to type
into the e-mail window.  Using pyHook, your program could see all the 
keypresses, but they'd also still be sent to the e-mail program.
Actually, I've never tried it, but I'm pretty sure that's how the GUI 
packages' key capturing works.
You may be asking 'well, it sounds like pyHook does a better job of this 
anyway!'
Yeah, you're right.
However, as Alan exclaimed, pyHook works only on Windows!
So the solution I offered would be more portable.
Hope that helps,
-Luke

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


[Tutor] Syntax Error? Variable Scope?

2006-11-02 Thread Chuck Coker
Hi Folks,

I am new to Python, but I have many years experience in software
development. I have a question about variable scope. I'm having a
problem that I suspect is merely a syntax error or something of that
nature.

I'm not real clear on variable scoping rules, either. I can't figure
out how to declare a variable containing a file pointer outside a
class and then access the variable from inside a method inside the
class. I could be creating errors when trying to use the "global"
keyword due to not fully understanding the scope rules. The examples
I found so far in books and on the web are to simplistic for what I
want to do.

I am using a load-testing app named The Grinder (version 3, beta 30)
and Python 2.5.

I want my script to open an external CSV (comma-separated values) file
containing x number of records with people's names, addresses, etc. I
want the file opened outside the TestRunner class (the main class for
The Grinder) when the script is first started.

Then I want each instance of the TestRunner class to read one line
from the external CSV file. After it gets the line from the file, I
want to split the line at the commas into components and do the
processing stuff.

After the last instance of TestRunner finishes, I want the script to
close the file and exit nicely.

My reasoning for opening and closing the CSV file outside the class is
that I want the file to stay open and have the file cursor maintain
its location after each read. For example, if I am running 2,000
threads, the file gets opened, whatever thread gets there first reads
line 1, the next thread that gets there reads line 2, and so on until
all 2,000 threads have had a chance to get a different line from the
file. Then I want the file to close.

Here are some code snippets:

--
from net.grinder.script import Test
from net.grinder.script.Grinder import grinder
from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest
from HTTPClient import NVPair
connectionDefaults = HTTPPluginControl.getConnectionDefaults()
httpUtilities = HTTPPluginControl.getHTTPUtilities()

[... snip ...]

fileNewUserInfo = 'new-user-info.csv'
fileNewUserInfoIsOpen = 0

[... snip ...]

class TestRunner:
  """A TestRunner instance is created for each worker thread."""

  # The instance initialization method.
  def __init__(self):
print 'We are in TestRunner.__init__()'
global infile
global fileNewUserInfoIsOpen
if (fileNewUserInfoIsOpen == 0):
  infile = open(fileNewUserInfo, "r")
  fileNewUserInfoIsOpen += 1;
  print 'We are inside the open if statement'
#global infile
self._userTokenCtx = ''
self._userTokenRi = ''
self._userInfo = []

for line in infile.readlines():
  self._userInfo.append(string.split((line),','))
  print line

print self._userInfo

  def nextMethod(self):

[... snip ...]
--

The script blows up at this line inside the for loop:

  self._userInfo.append(string.split((line),','))

with this error message in my error log:

11/2/06 7:12:20 PM (thread 0): Aborting thread due to Jython exception
"NameError: string" whilst creating per-thread test runner object

NameError: string
File "new-user-registration.py", line 356, in __init__

I've tried using "import string" and it doesn't like that. I'm sure
I'm missing something very basic here due to my newness with Python.
Can anyone offer any insights?

Thanks,
Chuck

-- 
==
Chuck Coker, Software Developer[EMAIL PROTECTED]
Tyrell Software Corporation  http://www.tyrell.com
Office: +1 949 458 1911 x 203Cell: +1 714 326 5939
==

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


Re: [Tutor] How to capture 'Ctrl+c' in Python

2006-11-02 Thread Chris Hengge
I've got your code at home, and I know it picks up shift and ctrl modified items, but it wont register print screen (among a few others). I can post the code I have at home later if you want to verify it. I've been given a few methods to try in my other thread I just started on here which are more practical, but I'm still interested in this. 
On 11/2/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
"Chris Hengge" <[EMAIL PROTECTED]> wrote> Do you by chance know of a way to capture special keys like "Print> Screen"?Try the key capture code in my Event Driven topic.
So far as I know it works for all keys including the special ones.It also points out that those keys have a two part code...--Alan GauldAuthor 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
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to capture 'Ctrl+c' in Python

2006-11-02 Thread Luke Paireepinart
Chris Hengge wrote:
> I've got your code at home, and I know it picks up shift and ctrl 
> modified items, but it wont register print screen (among a few 
> others). I can post the code I have at home later if you want to 
> verify it. I've been given a few methods to try in my other thread I 
> just started on here which are more practical, but I'm still 
> interested in this.
Pygame can capture it just fine. 
import pygame
from pygame.locals import *
pygame.init()
scr = pygame.display.set_mode((640,480))
while 1:
pygame.display.update()
for event in pygame.event.get():
if event.type == KEYDOWN:
print event
if event.key == K_ESCAPE:
pygame.quit()
raise SystemExit

when you hit print screen you will see that the keycode is 311,
so just do a
if event.key == 311:
if you want to check if they hit print screen.
But this doesn't really help you probably because I don't think you're 
using Pygame.
Just thought i'd mention that.
>
> On 11/2/06, *Alan Gauld* <[EMAIL PROTECTED] 
> > wrote:
>
>
> "Chris Hengge" <[EMAIL PROTECTED] > wrote
> > Do you by chance know of a way to capture special keys like "Print
> > Screen"?
>
> Try the key capture code in my Event Driven topic.
>
> So far as I know it works for all keys including the special ones.
> It also points out that those keys have a two part code...
>
> --
> 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
>
>
> 
>
> ___
> 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] Syntax Error? Variable Scope?

2006-11-02 Thread Dustin J. Mitchell
Chuck Coker wrote:
> from net.grinder.script import Test
> from net.grinder.script.Grinder import grinder
> from net.grinder.plugin.http import HTTPPluginControl, HTTPRequest
> from HTTPClient import NVPair
> connectionDefaults = HTTPPluginControl.getConnectionDefaults()
> httpUtilities = HTTPPluginControl.getHTTPUtilities()
> 
> [... snip ...]
> 
> fileNewUserInfo = 'new-user-info.csv'
> fileNewUserInfoIsOpen = 0
> 
> [... snip ...]
> 
> class TestRunner:
>   """A TestRunner instance is created for each worker thread."""
> 
>   # The instance initialization method.
>   def __init__(self):
> print 'We are in TestRunner.__init__()'
> global infile
> global fileNewUserInfoIsOpen
> if (fileNewUserInfoIsOpen == 0):
>   infile = open(fileNewUserInfo, "r")
>   fileNewUserInfoIsOpen += 1;
>   print 'We are inside the open if statement'
> #global infile
> self._userTokenCtx = ''
> self._userTokenRi = ''
> self._userInfo = []
> 
> for line in infile.readlines():
>   self._userInfo.append(string.split((line),','))
>   print line
> 
> print self._userInfo
> 
>   def nextMethod(self):
> 
> [... snip ...]
> --
> 
> The script blows up at this line inside the for loop:
> 
>   self._userInfo.append(string.split((line),','))
> 
> with this error message in my error log:
> 
> 11/2/06 7:12:20 PM (thread 0): Aborting thread due to Jython exception
> "NameError: string" whilst creating per-thread test runner object
> 
> NameError: string
> File "new-user-registration.py", line 356, in __init__
> 
> I've tried using "import string" and it doesn't like that. I'm sure
> I'm missing something very basic here due to my newness with Python.
> Can anyone offer any insights?

Python's scoping is a little weird, but you're actually using it right.
Adding 'import string' to the top of your module should have fixed this
problem, but that's old (like Py 2.1, I think) behavior.  Nowadays, you can
write e.g., self._userInfo.append(",".split(line)).

Also, there's a CSV module that will take care of reading and splitting CSV
files for you.  Personally, I would write this all out a little differently,
taking advantage of the fact that performing operations in the global context
is allowed:

...
import csv
...

userInfo = csv.reader(file('new-user-info.csv', 'rb'))

class TestRunner:
def __init__(self):
for row in userInfo:
# row is a tuple of cells
print row

hopefully that helps.

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


Re: [Tutor] How to capture 'Ctrl+c' in Python

2006-11-02 Thread Chris Hengge
I'm not sure where I got this from, but I think its from your site.. import msvcrtdef doKeyEvent(key):    if key == '\x00' or key == '\xe0': # non ASCII   key = msvcrt.getch() # fetch second character
    print ord(key)def doQuitEvent(key):    raise SystemExit# First, clear the screen of clutter then warn the user # of what to do to quitlines = 25 # set to number of lines in console
for line in range(lines): printprint "Hit space to end..."print# Now mainloop runs "forever"while True:   ky = msvcrt.getch()   length = len(ky)   if length != 0:
  # send events to event handling functions  if ky == " ": # check for quit event doQuitEvent(ky)  else:  doKeyEvent(ky)On 11/2/06, 
Alan Gauld <[EMAIL PROTECTED]> wrote:
"Chris Hengge" <[EMAIL PROTECTED]> wrote> Do you by chance know of a way to capture special keys like "Print> Screen"?Try the key capture code in my Event Driven topic.
So far as I know it works for all keys including the special ones.It also points out that those keys have a two part code...--Alan GauldAuthor 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
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to capture 'Ctrl+c' in Python

2006-11-02 Thread Chris Hengge
Nevermind, I just realised my problem with the script I just sent. I'm using a laptop right now and the print screen key is FN+ Insert FN isn't mappable. Works fine on an external keyboard, so I guess I'll try one of the other recommendations. 
Thanks alot for the time guys. On 11/2/06, Chris Hengge <[EMAIL PROTECTED]> wrote:
I'm not sure where I got this from, but I think its from your site.. import msvcrtdef doKeyEvent(key):    if key == '\x00' or key == '\xe0': # non ASCII   key = msvcrt.getch() # fetch second character
    print ord(key)def doQuitEvent(key):    raise SystemExit# First, clear the screen of clutter then warn the user # of what to do to quitlines = 25 # set to number of lines in console

for line in range(lines): printprint "Hit space to end..."print# Now mainloop runs "forever"while True:   ky = msvcrt.getch()   length = len(ky)   if length != 0:

  # send events to event handling functions  if ky == " ": # check for quit event doQuitEvent(ky)  else:  doKeyEvent(ky)
On 11/2/06, 
Alan Gauld <[EMAIL PROTECTED]> wrote:

"Chris Hengge" <[EMAIL PROTECTED]> wrote> Do you by chance know of a way to capture special keys like "Print
> Screen"?Try the key capture code in my Event Driven topic.
So far as I know it works for all keys including the special ones.It also points out that those keys have a two part code...--Alan GauldAuthor 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


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