0

I have a backup script that simply runs every day and backs up files to a directory if they exist in source dir but not in destination dir.

Sometimes (rarely) the script will fall over if a file isn't permissioned properly.

I've got around this using a try/except block.

However what I want to do now is to display the error message from the except block and then to say

>>> Press Enter to re-run backup

and then for the script to re-run the copying process which is a defined function.

So to summarise:

  1. Script runs
  2. Script throws error
  3. User follows instructions from error message
  4. User presses "Enter" key to re-run the copying function

I am running windows if that makes a difference (when I was googling this problem a lot of the results were to do with python on windows)

Joe Smart
  • 751
  • 3
  • 10
  • 28
  • possible duplicate of [Python read a single character from the user](http://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user) – ivan_pozdeev Sep 09 '14 at 11:24
  • Not a duplicate. The keystroke isn't the main part of my question. Moreso the recognition of that keystroke to re-run a function once an error message is shown.Although people reading this question might find that question useful as well, so thank you. – Joe Smart Sep 09 '14 at 12:22

2 Answers2

1

You can use raw_input() (or simply input() if using Python 3) to wait for Enter and a condition variable to control looping through the copying process until successful.

from sys import stderr

def run_backup():
    print "running backup"
    raise  # this simulates an error


backup_completed = False

while not backup_completed:
    try:
        run_backup()
        backup_completed = True
    except:
        print >> stderr, "Error message..."
        raw_input(">>> Press Enter to re-run backup")
Roberto Reale
  • 4,247
  • 1
  • 17
  • 21
  • Will this re-run the script though. I think I understand what you've written in terms of the error etc. but on the enter keystroke does this repeat `run_backup` – Joe Smart Sep 09 '14 at 08:46
  • It will call again `run_backup()`. Is this not the expected behaviour? – Roberto Reale Sep 09 '14 at 08:48
  • That's exactly what I wanted. I'm just a bit new to python and still learning some stuff so wasn't 100% sure it'd do this. – Joe Smart Sep 09 '14 at 08:57
  • That's great :) As you can see, the `raise` in the `run_backup()` function is just there to simulate an error condition. Also, an this answer be correct, please accept it, so that it may be useful for others as well. – Roberto Reale Sep 09 '14 at 09:01
0

Seems pretty simple to me. You can just use raw_input to make the script wait an Enter key-press:

while True:
    try:
        # run the script
    except SomeException as e:
        # print the error message and recovery instructions

        raw_input('Press Enter to re-run backup.')
Bakuriu
  • 98,325
  • 22
  • 197
  • 231