naiminp naiminp - 2 years ago 121
Python Question

python quit function not working

I am using the following check in one of my scripts:

if os.path.exists(FolderPath) == False:
print FolderPath, 'Path does not exist, ending script.'
if os.path.isfile(os.path.join(FolderPath,GILTS)) == False:
print os.path.join(FolderPath,GILTS), ' file does not exist, ending script.'
df_gilts = pd.read_csv(os.path.join(FolderPath,GILTS))

Stangely enough, when the path/file doesn't exist, I obtain the following print:

IOError: File G:\On-shoring Project\mCPPI\Reconciliation Tool\Reconciliation Tool Project\3. Python\BootStrap\BBG\2017-07-16\RAW_gilts.csv does not exist

Tells me that it's continuing on with the script even though I've added a quit(). Can anyone tell me why?


Answer Source

Per the documentation, quit() (like other functions added by the site module) is intended only for interactive use.

Thus, the solution is twofold:

  • Check whether os.path.exists(os.path.join(FolderPath, GILTS)), not just os.path.exists(FolderPath), to ensure that the code attempting to exit the interpreter is actually reached.

  • Use sys.exit(1) (after import sys in your module header, of course) to halt the interpreter with an exit status indicating an error from a script.

That said, you might consider just using exception handling:

from __future__ import print_function

path = os.path.join(FolderPath, GILTS)
    df_gilts = pd.read_csv(path)
except IOError:
    print('I/O error reading CSV at %s' % (path,), file=sys.stderr)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download