gpt4 book ai didi

python - 在 python 中打印 try-exception 中的帮助文本

转载 作者:太空宇宙 更新时间:2023-11-03 21:00:02 25 4
gpt4 key购买 nike

在 python 的 try-exception block 中,如下所示,我希望打印我的帮助消息,而不是 python 自己的错误消息。这可能吗?

 def genpos(a):
''' Generate POSCAR :
Some error message'''
try:
tposcar = aio.read(os.path.join(root,"nPOSCAR"))
cell = (tposcar.get_cell())
cell[0][0] = a
cell[1][1] = math.sqrt(3)*float(a)
tposcar.set_cell(cell, scale_atoms=True)
aio.write("POSCAR", tposcar, direct=True)
except:
help(genpos)
sys.exit()

所以,比如说,当不带参数调用此代码时,我想得到“生成 POSCAR :一些错误消息”,而不是 python 的回溯(最近一次调用最后一次):

  File "submit.py", line 41, in <module>
main()
File "submit.py", line 36, in __init__
ase_mod.genpos()
TypeError: genpos() missing 1 required positional argument: 'a'

最佳答案

您可以define a new exception:

class CustomError(Exception): pass

raise CustomError('Generate POSCAR : Some error message')

尽管如此,您收到的错误与 try- except 语句无关。相反,您的 gen_pos() 函数缺少参数。

关于python - 在 python 中打印 try-exception 中的帮助文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55771502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com