Re: [Tutor] Why does using "window.addchr()" to place a character at the lower right corner raise an exception?

2019-02-28 Thread Malcolm Herbert
yes - usually that was the prompt for the terminal to insert a new line ... on 
some terminals this is a behaviour you can't control as it's implemented in 
hardware, so curses fakes things by moving the cursor back to where it "should" 
be afterward.

If you try and to something when the cursor is at the extreme bottom right of 
the window/region and the terminal is hard-coded to do $magic immediately 
after, then your screen will be all messed up.

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


Re: [Tutor] ANSI / VT100 Escape Codes in Windows 7 Environment

2019-02-28 Thread Chip Wachob
Wow!  What a treasure of information.

>From the looks of it, I'm going to give colorama a try.  It seems like it
will do what I want to do, and, if I'm reading the documentation correctly,
it will work cross platform.  Ie: if I am in Linux, it will simply be
ignored.  And, it appears to interpret the ANSI codes (\033[xxxm) when it
comes to Windows...

As an aside, I enjoyed the trip down memory lane.  I still have my Hercules
graphics card and my AMBER monitor for my 286 machine.  You know, the
machine that has two full-height HDD with an MFM interface and provides a
combined 20Mbyte of storage space! And of course a math co-processor...  I
no longer recall how many Kbytes of onboard memory I had, maybe 1024...   :)

Thank you so much for sharing your insights.

Best,


On Wed, Feb 27, 2019 at 9:40 PM boB Stepp  wrote:

> On Wed, Feb 27, 2019 at 6:50 PM Chip Wachob  wrote:
> >
> > Hello again,
> >
> > As always, this list has been very helpful, and thank you.
> >
> > So, I thought I was good to go until I attempted to run my code on a
> > Windows 7 vintage machine this morning.  The application is intended to
> be
> > run in the command window in Windows, from the terminal in Linux...
> >
> > In the code I had included the ANSI escape characters so I could invert
> the
> > text and change the color.  Basically, I wanted to make the warning /
> error
> > messages stand out from the crowd.
>
> As I have been on a "curses" kick lately, I wonder if it would work
> for you?  Of course this means another module, but it is in the
> standard lib on all non-Windows Python versions.  For Windows I found
> this thread on stackoverflow:
>
>
> https://stackoverflow.com/questions/32417379/what-is-needed-for-curses-in-python-3-4-on-windows7
>
> The checked answer gives a link to binaries for Windows, which seems
> to support all Python versions through 3.7, including 2.7.
>
> Just a thought...
>
> --
> boB
> ___
> 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] Remove soft line break

2019-02-28 Thread Valerio Pachera


- Messaggio originale -
> Da: "Valerio Pachera" 
> A: "Tutor Python" 
> Inviato: Giovedì, 28 febbraio 2019 13:05:27
> Oggetto: Re: [Tutor] Remove soft line break
>...
> It works as expected but there's a thing I've to understand about the end of
> line in general.
> ...
> I noticed that the end of file doesn't get preserve if I create a copy of the
> file by simply
> 
> f = open('file.ics')
> content=f.read()
> f.close()
> 
> f = open('file_copy.ics', 'w')
> write('content')
> f.close()

Got it!
Python automatically convert new line to \n when it opens the file

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, 
closefd=True, opener=None)

This is my final script that overrides the original file.

---
import sys

f = open(sys.argv[1], newline='\r\n')
content = f.read().replace('\r\n ', '')
f.close()

f = open(sys.argv[1], 'w')
f.write(content)
f.close()
---

Valerio P.
___
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-02-28 Thread Valerio Pachera

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

  s.replace('\n ', '')

In other words removing a new line followed by a space.
In such case, the approach is not by line.

f = open('file.ics')
content=f.read().replace('\n ', '')
f.close()

The real use case is an .ics file.
It works as expected but there's a thing I've to understand about the end of 
line in general.

The original file line break is CR CF

cat --show-all file.ics
METHOD:PUBLISH^M$
BEGIN:VTIMEZONE^M$

I noticed that the end of file doesn't get preserve if I create a copy of the 
file by simply

f = open('file.ics')
content=f.read()
f.close()

f = open('file_copy.ics', 'w')
write('content')
f.close()

cat --show-all file_copy.ics
METHOD:PUBLISH$
BEGIN:VTIMEZONE$

What am I missing?


- Messaggio originale -
Da: "Peter Otten" <__pete...@web.de>
A: "Tutor Python" 
Inviato: Lunedì, 4 febbraio 2019 20:23:59
Oggetto: Re: [Tutor] Remove soft line break

Valerio Pachera wrote:

> 
> I have a file with row that split at the 80th character.
> The next row start with a blank space, meaning that i part of the previous
> row.
> 
> Example:
> 
> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam non justo
> enim. Viv
>  amus dapibus quis neque vitae ornare. Pellentesque at pharetra sapien, id
>  eleif end lacus. Nullam ut semper enim, vulputate venenatis justo.
>  Vestibulum vehicul a dolor sit amet ultricies vulputate. Aenean lobortis,
>  nulla eu scelerisque hen
> 
> What do you suggest to get the text on a single line?

Neglecting the corner cases:

$ cat mergelines.py 
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"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] schedulers

2019-02-28 Thread nathan tech
Hi there,

I recently started working on a backup program, and the one big feature 
everyone wants in backup programs is the ability to schedule backups, right?

but I'm thinking, should I do this?

def do_backup

  # backup code here, without prints to screen or anything so it just 
does it in the background...


def scheduler():

  global tus # tus=time until schedule

  while(time.time()>tus):

   time.sleep(5)

  scheduler()


Is that wise? Is that how it should be done?

This is a program for windows.

Thanks!

Nathan

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


[Tutor] Exception not working as expected?

2019-02-28 Thread Chip Wachob
Hello,

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

So, the code below is my example.

When I run it, everything is fine until I attempt to test the
KeyboardInterrupt exception.

When I do this, the traceback is as follows:
Traceback (most recent call last):
  File "except.py", line 71, in 
start_menu()


What I was expecting was the message in the exception to be displayed ("
Keyboard Interrupt - Exiting "), then for the program to exit gracefully.

I'm sure that this is a NOOB mistake, but I can't seem to figure out why
the exception isn't being trapped and handled the way I had hoped.

Can someone shed some light on this for me?

Thank you,




# import standard libraries
import os
import time
import sys

DISPLAY_TIME = 5
g_user_num_items = -1

def start_menu():

start_quit = False

os.system('cls' if os.name == 'nt' else 'clear')

print "\n\n\n\n Welcome to Test.\n"
time.sleep(DISPLAY_TIME)

try:
while not start_quit:

os.system('cls' if os.name == 'nt' else 'clear')

print "\n +++ Test Start Menu +++"
print "Enter the number of items to test,"
print "or, 0 for individual testing."
print "Then press \n"

# wait for it...
num_items = int(raw_input(": "))

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

elif(num_items >= 1 and num_items <= 512):   # multi testing
g_user_num_items = num_items
print "\nItem count of ", g_user_num_items, ", accepted!"
start_quit = True

else:   # unexpected input eg A, >, ? etc
print " Invalid number of items, please re-enter"

time.sleep(DISPLAY_TIME / 2)

# end item count input

# detect ctrl-c
except KeyboardInterrupt:
# provides a clean exit
print "\n\n Keyboard Interrupt - Exiting \n\n"
time.sleep(5)

# 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()

return
# end main menu


##
# Main entry point into program
#

if __name__ == "__main__":

start_menu()

print "End of Script\n"
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] schedulers

2019-02-28 Thread Steven D'Aprano
On Thu, Feb 28, 2019 at 02:45:59PM +, nathan tech wrote:
> Hi there,
> 
> I recently started working on a backup program, and the one big feature 
> everyone wants in backup programs is the ability to schedule backups, right?
> 
> but I'm thinking, should I do this?
[...]
> Is that wise? Is that how it should be done?

No. You should write your backup program to do backups, and then 
register that program with your operating system's scheduler. I don't 
know what that's called on Windows, but on Linux that would be "cron".

Basically, you have three problems:

1. Perform the backup.

2. Let the user decide when to do the backup.

3. Actually trigger the program to run at the correct time.


Parts 1 and 2 are your job. Number 3 is up to the OS. It will handle all 
the complex problems of clocks changing between jobs, computer reboots 
(what if the computer is off when the job is supposed to run?) etc.

If for some reason you need to write your own scheduler, using a "busy 
loop" where you run a loop continually checking the time is not the 
right answer. (I don't know what the right answer is, I just know that 
the OS has already solved that.)



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


Re: [Tutor] schedulers

2019-02-28 Thread Steven D'Aprano
Sorry, I hit send too quick...

I realise you haven't written a busy loop, but the way you wrote your 
scheduler, you can only schedule jobs to the nearest 5 seconds. That's 
probably okay for a backup process that might take a few hours to run, 
but it is hardly a good solution to things that might need to be 
schedules 1 or 2 seconds apart.

And while you aren't *continuously* checking the time, you're still 
checking it pretty often. In the course of a day, you check the 
time 17280 times to see if you should run your backup program. That's 
pretty busy for something running once a day :-)

There's also the problem that you have to remember to launch your 
scheduler program every time you log in. Again, registering your backup 
program with the OS once means you don't have to think about it.

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


Re: [Tutor] schedulers

2019-02-28 Thread Alan Gauld via Tutor
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...


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

2019-02-28 Thread David Rock

> On Feb 28, 2019, at 17:23, Alan Gauld via Tutor  wrote:
> 
> On 28/02/2019 14:45, nathan tech wrote:
> 
>> but I'm thinking, should I do this?

Honestly, scheduling is the last thing to figure out.  As mentioned, it’s 
probably better to focus on backups and leave the scheduling to the OS tools 
that already exist. You need to write a solid backup routine, and an even more 
solid _restore_ routine.  Ultimately, the goal of backup software is to recover 
data.

Out of curiosity, what’s the driver behind doing this project in the first 
place?  
Do existing backup tools not do what you need (FOSS or otherwise)? 
Is this an academic exercise (i.e., for fun because you are curious)?
How complicated do you expect to get with the implementation?

If you are going to play with the scheduler, every 5 seconds is really 
overkill.  The reality is checking once a minute (even once every 5 minutes) is 
more than sufficient for even the most aggressive environments.  If you really 
need sub-minute starts, this is probably not something for a casual project.

have you thought about backup windows?  Defining the start time is one thing, 
but will you have an end time?  How long of a delay before you don’t try to 
start anymore?  What about media resources? How long will you wait if you have 
tape devices all in use?  Is this just a disk-based backup system?

Good backup software is not trivial to write.  Maybe if we better understood 
your goals, we could better direct you.


— 
David Rock
da...@graniteweb.com




___
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-02-28 Thread Alan Gauld via Tutor
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


Re: [Tutor] Exception not working as expected?

2019-02-28 Thread eryk sun
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