Python:使用lineno引发SyntaxError [英] Python: raise SyntaxError with lineno

查看:156
本文介绍了Python:使用lineno引发SyntaxError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为一种特定于域的语言实现解析器,并希望能够引发SyntaxError.引发此异常时,如何设置文件名,lineno和offset?

I am implementing a parser for a domain specific language, and want to be able to raise a SyntaxError. How do I set the filename, lineno and offset when raising this exception?

例外 SyntaxError

在解析器遇到语法时引发 错误.这可能发生在import语句,exec语句, 对内置函数eval()或input()的调用,或者在读取 初始脚本或标准输入(也可以交互).

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).

此类的实例具有属性filename,lineno,offset和 文字,以便更轻松地访问详细信息.异常实例的str() 仅返回消息.

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元组.

The second argument needs to be a 4-tuple.

这篇关于Python:使用lineno引发SyntaxError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆