【问题标题】:print help text in try-exception in python在python中的try-exception中打印帮助文本
【发布时间】:2019-09-10 07:04:28
【问题描述】:

在 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()

所以,比如说,当这个代码在没有参数的情况下被调用时,我想得到“生成 POSCAR:一些错误消息”而不是 python 的 Traceback(最近一次调用最后一次):

  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'

【问题讨论】:

标签: python error-handling try-except


【解决方案1】:

你可以define a new exception:

class CustomError(Exception): pass

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

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

【讨论】:

  • 正确。当我遇到这种不匹配时,我正在尝试打印该文档字符串。我可以这样做吗?
  • 你可以提出任何你想要的消息
猜你喜欢
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-12
  • 2022-11-30
  • 2022-01-04
  • 2011-07-03
  • 1970-01-01
相关资源
最近更新 更多