views:

51

answers:

2

Well, I have made a module that allows you to copy a file to a directory easier. Now, I also have some "try's" and "except's" in there to make sure it doesn't fail in the big messy way and doesn't close the terminal, but I also want it to display different error messages when a wrong string or variable is put in, and end the module, but not the...if I may say, Terminal running it, so I did this:

def copy():
    import shutil
    import os
    try:
        cpy = input("CMD>>> Name of file(with extension): ")
        open(cpy, "r")
    except:
        print("ERROR>>> 02x00 No such file")
    try:
        dri = input("CMD>>> Name of Directory: ")
        os.chdir(dri)
        os.chdir("..")
    except:
        print("ERROR>>> 03x00 No such directory")
    try:
        shutil.copy(cpy, dri)
    except:
        print("ERROR>>> 04x00 Command Failure")

Problem is that it doesn't end the module if there is no file or directory, only at the finish.

+2  A: 

You may be thinking that when an exception is raised, Python just stops what it's doing, but that's not quite true. The except: block actually catches the exception raised, and is supposed to handle it. After an except: block finishes, Python will continue on executing the rest of the code in the file.

In your case, I'd put a return after each print(...). That way, after Python prints out an error message, it will also return from the copy() function rather than continuing to ask for more input.

David Zaslavsky
A: 

If you did want to make the module exit on error...

Here's how you'd do it.

def copy():
    import shutil
    import os
    import sys
    try:
        cpy = input("CMD>>> Name of file(with extension): ")
        open(cpy, "r")
    except:
        sys.exit("ERROR>>> 02x00 No such file")
    try:
        dri = input("CMD>>> Name of Directory: ")
        os.chdir(dri)
        os.chdir("..")
    except:
        sys.exit("ERROR>>> 03x00 No such directory")
    try:
        shutil.copy(cpy, dri)
    except:
        sys.exit("ERROR>>> 04x00 Command Failure")

sys.exit(0) (for success) and sys.exit(1) (for failure) are usually used but, since you want to output the error, the above example will output the error string to stderr.

Here's a link for more info on sys.exit().

Evan Plaice