3 回答
![?](http://img1.sycdn.imooc.com/545868190001d52602200220-100-100.jpg)
TA贡献1871条经验 获得超13个赞
因为main是一个函数,你可能return会出错:
def main(filename):
try:
x, y = getData(filename)
except FileNotFoundError:
print("file not found")
return
# calculations here
![?](http://img1.sycdn.imooc.com/533e4d2600013fe202000200-100-100.jpg)
TA贡献1797条经验 获得超6个赞
以下
def getData(fileName):
file = open(fileName,"r")
data = file.readlines()
file.close()
x = []
y = []
for i in data:
noNewline = i.rstrip('\n')
x.append(float(noNewline.split("\t")[0]))
y.append(float(noNewline.split("\t")[1]))
return x,y
def main(fileName):
# if you only want to handle exception coming from 'getData'
try:
x,y = getData(fileName)
except Exception as e:
print(f'could not get data using file {filename}. Reason: {str(e)}')
return
# do something with x,y
if __name__ == "__main__":
main('get_the_file_name_from_somewhere.txt')
![?](http://img1.sycdn.imooc.com/533e50ed0001cc5b02000200-100-100.jpg)
TA贡献1864条经验 获得超6个赞
解决方案
sys.exit
并SystemExit
采用可选参数 - 0 被视为成功终止。
例子
sys.exit(0) raise SystemExit(0)
参考
Python sys.exit:https://docs.python.org/3/library/sys.html#sys.exit
添加回答
举报