Lisa Lisa - 3 months ago 32
Python Question

python sys.exit :an integer is required (got type str)?

New to python.
I want to stop my code in main for debugging purpose. I use logging module to print the variable value I would like to inspect.

However, it raises error. Not sure how to solve it.
I also wonder using sys.exit instead of set up debugging point is the right way to run only small portion of the code. My main is long and I don't want to run the whole thing every time.

import linecache
import logging
import sys

import pandas as pd


def print_exception():
exc_type, exc_obj, tb = sys.exc_info()
f = tb.tb_frame
lineno = tb.tb_lineno
filename = f.f_code.co_filename
linecache.checkcache(filename)
line = linecache.getline(filename, lineno, f.f_globals)
print('EXCEPTION IN ({}, LINE {} "{}"): {}'.format(filename, lineno, line.strip(), exc_obj))


if __name__ == "__main__":
try:
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
df = pd.DataFrame({'A': [0, -1, 3, 5, 4, 2, 1],
'B': [12, 12, 14, 15, 14, 16, 200]})

sys.exit('error')



except:
print_exception()

EXCEPTION IN (<ipython-input-9-f42a2adee11e>, LINE 49 "sys.exit('error')"): an integer is required (got type str)


Updates: I've updated the full code. I'm on python3 with Pycharm.

Answer

From the comment discussion, I suspect your issue is that PyCharm is trying to handle the sys.exit() internally and it doesn't like the fact you are using a custom error message. There are similar issues in other IDEs like Python logging not working properly in Spyder (May or may not have been resolved by now).

Your usage itself seems valid and is consistent with the documentation for Python3 and I had no trouble running your code on my system and it performed as expected.

I suggest you try running the code with Python directly and not using PyCharm and see if that clears up the issue. If Python3 is your default python installation, you should only have to open a BASH Terminal or Command Prompt in the file's directory and type:

python file-name.py 

To run the program in the terminal. I suspect this will work fine and what you've really done here is not debugged your program but found a bug (or feature) in pycharm.