Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

Exiting Python?


shadowboy1505's Avatar
Member
0 0

Okay so I have a program that I've written in Python 3. It creates a file log and writes it to a file. If there are no logs, the file doesn't get created. Later in the program it calls the file, but the file doesn't exist. I want it to catch the exception when it can't open the file and just exit the script and do nothing else but I can't figure out how. The exit and quit commands don't do what I want. I've tried to Google it but I can't find anything on it. Can someone lead me in the right direction please?


ghost's Avatar
0 0

os.path.isfile(\path\to\file)

os.path.exists(\path\to\file)


ynori7's Avatar
Future Emperor of Earth
0 0

Try this:

import sys
for x in range(1, 300):
        print x
        if(x==20):
                sys.exit(0)```

ghost's Avatar
0 0
try:
        open('File that doesnt exist', 'r')
except IOError:
        print "Can't open file."
        exit(1)

and a quick google


try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise```

From http://docs.python.org/tutorial/errors.html