Re: [Tutor] schedulers

2019-03-01 Thread nathan tech
Hopefully I am doing this right, wanted to reply to the tutor list, not 
a specific person... Anyway.

Thanks Steven and Alan for your help.

I'll look into the windows scheduler and go from there.


The code given in the original email was just an example, but none the 
less I appreciate you guys pointing out the floors. :)

Thanks again.

Nathan

On 28/02/2019 23:23, Alan Gauld via Tutor wrote:
> On 28/02/2019 14:45, nathan tech wrote:
>
>> but I'm thinking, should I do this?
> No. fOr several reasons...
>
>> def do_backup
>>    # backup code here,
>> def scheduler():
>>    global tus # tus=time until schedule
>>
>>    while(time.time()>tus):
>>     time.sleep(5)
>>    scheduler()
> scheduler doesn't actually do anything except
> spin waiting for the time up. But you know the
> current time and the due time so you can just
> sleep until the due time, no need for the loop.
>
> Also you exit the loop and then call scheduler
> again - that will immediately exit the loop
> and call scheduler again which will repeat
> "forever". I suspect you meant to call do_backup?
>
> However, if you really want to delay execution
> of do_backup you can probably do it via the OS
> Nearly every OS has a means of scheduling tasks.
> So, by splitting your app into two parts - one
> to create the scheduled task and the
> other to actually do the backup.
>
> That way the OS does all the heavy lifting,
> including restoring the schedule after an OS
> restart etc. And you only have the relatively
> easy task of telling the os to schedule a task
> and writing the backup function.
>
>> This is a program for windows.
> OK, I cant recall the Windows schedule
> program - I think it was "at" or somesuch?
>
> Then again you could just use the native Windows
> backup program which doe it all for you...
>
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Remove soft line break

2019-03-01 Thread Peter Otten
Valerio Pachera wrote:

[Me:]

>> def merge_lines(lines):
>> lines = (line.rstrip("\n") for line in lines)
>> accu = [next(lines)]
>> for line in lines:
>> if line.startswith(" "):
>> accu.append(line[1:])
>> else:
>> yield "".join(accu) + "\n"
>> accu = [line]
>> yield "".join(accu) + "\n"

> I think it could be solved in a much easier way.

> content=f.read().replace('\n ', '')

That is indeed much simpler than my suggestion.

> What am I missing?

Nothing. My attempt to keep memory usage low led to a solution which is more 
complex than your slurp-it-in, fix it, spit-it-out.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception not working as expected?

2019-03-01 Thread Alan Gauld via Tutor
   I don't have python2 on my win10 PC and it works as expected on python 3.
   I suspect study of Eryk's post is your best bet. When it comes to the
   innards of Windows he is our local guru.
   On 1 Mar 2019 2:24 pm, Chip Wachob  wrote:

 Alan,
 Thanks.** Once again, a case of not finding a tree in the forest...**
 One of these days I'll remember to KISS and try some SIMPLE
 experimentation...
 So I did your experiment with just the single line raw_input('>'), ran
 it, and used Ctrl-C to exit.** Traceback shown below.**
 C:\Temp_Python\Exception>python rawsimple.py
 >Traceback (most recent call last):
 ** File "rawsimple.py", line 1, in 
 ** raw_input('>')

 C:\Temp_Python\Exception>
 Note that I ran the same code on a Linux machine and did get the name of
 the exception as you expected (KeyboardInterrupt).** And I was able to
 make a slightly longer script (again, as suggested) and got the desired
 results..
 Open to suggestions on how to capture the exception who's name isn't
 displayed...
 I'm still attempting to get my head around Eryk's post and perhaps that
 explains why there's no exception listed.
 On Thu, Feb 28, 2019 at 8:34 PM Alan Gauld via Tutor
 <[1]tutor@python.org> wrote:

   On 28/02/2019 21:03, Chip Wachob wrote:

   > it does work properly in Linux.** So I'm guessing I need to test for
   a
   > different exception along with the KeyboardInterrupt??

   Don't guess, test.

   Write a single line script

   raw_input('> ')

   Run it in a console.
   Hit Ctrl-C while it waits for input.
   See what the stack trace says is the exception
   Edit your script

   try:
   ** raw_input('> ')
   except :
   ** print "I got it that time!"

   run the new script.
   Did it work? Hooray! Transfer to the main script.
   If not come back here armed with tracebacks...

   --
   Alan G
   Author of the Learn to Program web site
   [2]http://www.alan-g.me.uk/
   [3]http://www.amazon.com/author/alan_gauld
   Follow my photo-blog on Flickr at:
   [4]http://www.flickr.com/photos/alangauldphotos

   ___
   Tutor maillist** -** [5]Tutor@python.org
   To unsubscribe or change subscription options:
   [6]https://mail.python.org/mailman/listinfo/tutor

References

   Visible links
   1. mailto:tutor@python.org
   2. http://www.alan-g.me.uk/
   3. http://www.amazon.com/author/alan_gauld
   4. http://www.flickr.com/photos/alangauldphotos
   5. mailto:Tutor@python.org
   6. https://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception not working as expected?

2019-03-01 Thread Chip Wachob
Alan,

Thanks.  Once again, a case of not finding a tree in the forest...  One of
these days I'll remember to KISS and try some SIMPLE experimentation...


So I did your experiment with just the single line raw_input('>'), ran it,
and used Ctrl-C to exit.  Traceback shown below.


C:\Temp_Python\Exception>python rawsimple.py
>Traceback (most recent call last):
  File "rawsimple.py", line 1, in 
raw_input('>')


C:\Temp_Python\Exception>



Note that I ran the same code on a Linux machine and did get the name of
the exception as you expected (KeyboardInterrupt).  And I was able to make
a slightly longer script (again, as suggested) and got the desired results..

Open to suggestions on how to capture the exception who's name isn't
displayed...

I'm still attempting to get my head around Eryk's post and perhaps that
explains why there's no exception listed.


On Thu, Feb 28, 2019 at 8:34 PM Alan Gauld via Tutor 
wrote:

> On 28/02/2019 21:03, Chip Wachob wrote:
>
> > it does work properly in Linux.  So I'm guessing I need to test for a
> > different exception along with the KeyboardInterrupt??
>
> Don't guess, test.
>
> Write a single line script
>
> raw_input('> ')
>
> Run it in a console.
> Hit Ctrl-C while it waits for input.
> See what the stack trace says is the exception
> Edit your script
>
> try:
>   raw_input('> ')
> except :
>   print "I got it that time!"
>
> run the new script.
> Did it work? Hooray! Transfer to the main script.
> If not come back here armed with tracebacks...
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception not working as expected?

2019-03-01 Thread Chip Wachob
Eryk

Thank you for the in-depth explanation and code sample.

I was able to use the sample code to create a functional script.

Now, I'm still not completely following what you mean in the last couple of
paragraphs about the except ValueError.

I realized that I am never actually trapping on the else statement in my
original code.  When I enter inappropriate values, the exception is always
trapping, not the else statement.  Which seems sort of odd to me.

I'm not sure what you mean by putting the except close to the int().

Generally, I feel like I'm getting a handle on this, but that actually
leads me to a related question.

As you can tell, this is just the top of a whole bunch of menu tree paths
that the user can take.  Below is a very rough textual representation of
the layout of the menus.  I understand how the sys.exit() works in the case
of the initial menu, but I don't follow how I can use that same approach to
navigate 'back' up the menu tree.  Each major Test (Type A, Type B, etc) is
a .py file unto itself.

Something about this is feeling like maybe it should be a class, or some
other function that I call throughout my program.

How can I best handle this situation and, how do I trap those invalid
entries and, as you say, "continue" the try statements?


Main Menu
|
|-- Test Type A Items
||-- 1. Test A1
||-- 2. Test A2
||-- 3. Test A3
||-- 0. Back to Main
|
|-- Test Type B Items
||-- 1. Test B1
||-- 2. Test B2
||-- 3. Test B3
||-- 0. Back to Main
|
|-- Test Individual Item
||-- 1. Test I1
||-- 2. Test I2
||-- 3. Test I3
||-- 0. Back to Main
|
|-- Quit

Thank you,


On Thu, Feb 28, 2019 at 9:31 PM eryk sun  wrote:

> On 2/28/19, Chip Wachob  wrote:
> >
> > Python 2.7 & Windows and also Linux are the platforms being used.
> Running
> > the code from the command line / terminal as   python except.py.  Note
> that
> > it does work properly in Linux.  So I'm guessing I need to test for a
> > different exception along with the KeyboardInterrupt??
>
> When reading from the console, we depend on a particular error being
> set in order to distinguish an interrupted read from end-of-file
> (EOF), but this error doesn't get set in Windows 8+ due to a bug in
> the Windows API. I created an issue with Microsoft's console team, but
> thus far they've ignored it.
>
> Due to this bug, Python 2 code that calls raw_input() or input() also
> needs to handle EOFError, which should probably be handled anyway.
> However, it's not enough to separately handle KeyboardInterrupt and
> EOFError, since the KeyboardInterrupt may get raised while handling
> EOFError. This can happen because Windows calls the console control
> handler asynchronously in a new thread. We need a bit of a kludge that
> checks for a delayed KeyboardInterrupt. For example, the following
> shows a case that uses a common handler for EOF and Ctrl+C:
>
> import os
> import sys
> import time
>
> def main():
> try:
> os.system('cls' if os.name == 'nt' else 'clear')
> print "\n\n\n\n Welcome to Test.\n"
> time.sleep(DISPLAY_TIME)
> start_menu()
> except (KeyboardInterrupt, EOFError):
> try:
> time.sleep(0.1)
> except KeyboardInterrupt:
> pass
> # provides a clean exit
> print "\n\n Keyboard Interrupt or EOF - Exiting \n\n"
> time.sleep(5)
> print "End of Script\n"
> return 0
>
> if __name__ == "__main__":
> sys.exit(main())
>
> > # trap no choice, just Enter key cases
> > except ValueError:
> > # handles non-entry selections like 'Enter'
> > print "Invalid selection please try again"
> > time.sleep(DISPLAY_TIME / 2)
> > start_menu()
>
> ValueError should be handled near the int() conversion that raises it,
> and the exception handler should `continue` the loop instead of
> recursively calling start_menu().
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception not working as expected?

2019-03-01 Thread Alan Gauld via Tutor
On 01/03/2019 19:23, Chip Wachob wrote:

> I'm not sure what you mean by putting the except close to the int().

He means you should have a try/except for the int conversion,
typically something like:


  # wait for it...
  try: num_items = int(raw_input(": "))
  except ValueError:
 # try a second time.

  if num_items == 0: # individual testing
 print "\nIndividual testing requested"

That means the user has a chance of continuing without errors
and you don;t need to use recursion to restart the menu system.

Part of the problem is that your design does not cleanly
separate the presentation of the menus and collection of
user input from the logic behind processing the values.
That usually leads to complicated code that's hard to
debug(and test)

You want to catch the error as soon as possibly after
it happens not at the end of the while loop.
Put the try inside the loop where you read the input
and then when things go wrong you can catch it, fix
it and continue with the program.and it simplifies
the overall structure.

> the layout of the menus.  I understand how the sys.exit() works in the case
> of the initial menu, but I don't follow how I can use that same approach to
> navigate 'back' up the menu tree.  Each major Test (Type A, Type B, etc) is
> a .py file unto itself.

So you make them modules and import them into your main
program. That way you can call any of them as needed.

And put the menu code in a separate function(or set of
functions) that simply displays the menu and gets a
valid response. Use the return value from that function(s)
to drive an if/elif ladder to determine how to process
the menu selections.

Or you could construct a dictionary that maps menu
choice to a function but, while that's a more flexibly
and extensible approach its also much harder to code
up correctly initially. if/elif is usually good enough.

> Something about this is feeling like maybe it should be a class, or some
> other function that I call throughout my program.

You could create a menu class but I doubt if its needed
here. A simple function (possibly taking a menu string
as input, or just storing the menu internally) that
returns some kind of unique identifies for the users
choice is all you should need.

> How can I best handle this situation and, how do I trap those invalid
> entries and, as you say, "continue" the try statements?

continue the while loop not the try.
Put the try inside the loop and use "continue" once
you fix the error. "continue" jumps you back to the
top of the loop.

So your code might look something like:

while True:
choice = get_menu_option()

if choice == 0;
   # do something
elif choice == 1:
   # etc
else: break   # exit the while loop

And inside get_menu_option() you have something like

def get_menu_option(menu_string)
   while True:
  print menu_string
  try: val = int(raw_input(': '))
  except 
 # fix error here
  if value_is_valid(val)  #is it in range, non negative etc?
 return val
  # implicit else returns to top of loop

That way your top level code always gets a valid
user choice to process and the error handling is
located beside the place it occurred.

With a multi tiered menu structure you might have
two menu functions, one per level. You might also
have some way of mapping the menu values to a
single unique command ID. But those are just details.
The structure should be broadly the same.

-- 


Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Exception not working as expected?

2019-03-01 Thread Cameron Simpson

On 02Mar2019 00:05, Alan Gauld  wrote:

On 01/03/2019 19:23, Chip Wachob wrote:

I'm not sure what you mean by putting the except close to the int().


He means you should have a try/except for the int conversion,
typically something like:


 # wait for it...
 try: num_items = int(raw_input(": "))
 except ValueError:
# try a second time.

 if num_items == 0: # individual testing
print "\nIndividual testing requested"

That means the user has a chance of continuing without errors
and you don;t need to use recursion to restart the menu system.


Just further to this remark of Alan's: you should make try/except 
clauses as small as is reasonable i.e. containing as little code as 
possible between "try" and "except".


Not only does this have the advantage Alan mentioned, of making it 
possible to offset the user the chance to continue after an error, it 
_also_ means you have more confidence about what caused the exception.


In you programme, you have a try/except around the entire main body of 
your loop. This means that the "except ValueError" clause will intercept 
_any_ ValueError issued by the code, not just the one from the int() 
call, so it needn't indicate bad user input, it could as easily indicate 
some subsequent bug in your code, as many functions can raise ValueError 
if they are handed something unsatisfactory.


Cheers,
Cameron Simpson 
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor