Search code examples
pythonpython-2.7keystroke

Using a keystroke to repeat a function


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)


Solution

  • 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")