在python中打印tryexception中的帮助文本

2024-05-03 11:15:30 发布

您现在位置:Python中文网/ 问答频道 /正文

在python的try-exception块中,如下图所示,我希望打印我的帮助消息,而不是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()

所以,比方说,当在没有参数的情况下调用此代码时,我希望得到“Generate POSCAR:Some error message”,而不是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'

Tags: pytrue消息messagecellerrorsomegenerate
1条回答
网友
1楼 · 发布于 2024-05-03 11:15:30

你可以define a new exception:

class CustomError(Exception): pass

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

不过,您收到的错误与try-except语句无关。相反,gen_pos()函数缺少一个参数。你知道吗

相关问题 更多 >