naiminp
naiminp

Reputation: 181

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.'
    quit()
if os.path.isfile(os.path.join(FolderPath,GILTS)) == False:
    print os.path.join(FolderPath,GILTS), ' file does not exist, ending script.'
    quit()    
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?

Thanks

Upvotes: 0

Views: 2621

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295706

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)
try:
    df_gilts = pd.read_csv(path)
except IOError:
    print('I/O error reading CSV at %s' % (path,), file=sys.stderr)
    sys.exit(1)

Upvotes: 5

Related Questions