gpt4 book ai didi

Python:使用 lineno 引发 SyntaxError

转载 作者:太空宇宙 更新时间:2023-11-03 12:38:31 24 4
gpt4 key购买 nike

我正在为领域特定语言实现解析器,并希望能够引发 SyntaxError。引发此异常时如何设置文件名、行号和偏移量?

exception SyntaxError

Raised when the parser encounters a syntax error. This may occur in an import statement, in an exec statement, in a call to the built-in function eval() or input(), or when reading the initial script or standard input (also interactively).

Instances of this class have attributes filename, lineno, offset and text for easier access to the details. str() of the exception instance returns only the message.

来源:https://docs.python.org/3.2/library/exceptions.html#SyntaxError

最佳答案

答案是:

>>> raise SyntaxError('End quote missing', ("test.py", 1000, 11, "print 'bar"))                                                                             
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "test.py", line 1000
print 'bar
^
SyntaxError: End quote missing

第二个参数需要是一个 4 元组。

关于Python:使用 lineno 引发 SyntaxError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33717804/

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