nep*_*eph 0 python string exception multiline
我试图修改引发异常时构造的消息,但令我惊讶的是,传递的实际 arg 是捕获的内容except,而不是异常内部的任何值。
这就是我想做的:
class ScriptError(Exception):
"""This is our special exception class so we can catch it &
nicely print it in a popup message.
"""
def ___init___(self, message):
self.message = self.clean(message)
def clean(message):
"""This clears whitespace at the start of each line for multiline strings.
Required for the big triple-quote strings to both be formatted nicely in the
code and also render properly in the tkinter popups.
"""
return '\n'.join([line.lstrip() for line in str(message).split('\n')])
Run Code Online (Sandbox Code Playgroud)
我尝试这样做是因为这种类型的异常往往是多行生物:
if not any([status.getCurrentUser() in groups[group] for group in groups]):
raise ScriptError("""You do not have permission to continue.
You must be in one of the following permitted groups:
{}""".format(config['permitted_groups']))
Run Code Online (Sandbox Code Playgroud)
遗憾的是,这包含了一堆在三引号语法中缩进写入的前导空格。
现在,这可能是一个经典的 XY 问题,我确实需要为我的字符串使用不同的格式,例如("" "" ""). 然而,这感觉不太Pythonic;clean将上述函数从命名空间中取出并放入主命名空间中也不会ScriptError,只是为了在显示或引发函数时使用它。
当然有一种很好、优雅的方法来做到这一点吗?
标准库就是textwrap.dedent为此目的提供的。
>>> import text wrap
>>> help(textwrap.dedent)
Help on function dedent in module textwrap:
dedent(text)
Remove any common leading whitespace from every line in `text`.
This can be used to make triple-quoted strings line up with the left
edge of the display, while still presenting them in the source code
in indented form.
Note that tabs and spaces are both treated as whitespace, but they
are not equal: the lines " hello" and "\thello" are
considered to have no common leading whitespace.
Entirely blank lines are normalized to a newline character.
Run Code Online (Sandbox Code Playgroud)
就我个人而言,我会让调用者ScriptError负责提供正确的缩进字符串。
class ScriptError(Exception):
def ___init___(self, message):
self.message = message
if not any([status.getCurrentUser() in groups[group] for group in groups]):
msg = textwrap.dedent(
"""You do not have permission to continue.
You must be in one of the following permitted groups:
{}""".format(config['permitted_groups']
)
raise ScriptError(msg)
Run Code Online (Sandbox Code Playgroud)
但你可以用它textwrap.dedent来代替你的clean功能。
| 归档时间: |
|
| 查看次数: |
337 次 |
| 最近记录: |