【问题标题】:SyntaxError uncaught while using py_compile使用 py_compile 时未捕获 SyntaxError
【发布时间】:2016-05-20 12:30:58
【问题描述】:

我在 python 的一个类中定义了以下函数,我试图从外部源编译 python 代码。 python代码进来,被写入一个文件,然后文件被发送到下面的函数。 当我尝试将函数调用为:

self._check_code_for_errors(source_file)

它不执行 except 块,我正在捕获 SyntaxError 异常。

def _check_code_for_errors(self, source_file):
    try:
        file_ = open(source_file.name, 'r')
        py_compile.compile(file_.name)
    except SyntaxError:
        return {'errors': 'You have a problem in your syntax'}
    except (OSError, IOError):
        return {'errors': 'Some error has occurred, please try again'}

更新:

class ValidatePythonCodeViewSet(generics.CreateAPIView):
    parser_classes = (PlainTextParser, )
    """
    The view set below accepts code from post request, executes it and then
    returns the appropriate results (error or output)
    """

    def _write_code_to_file(self, source):
        # file is a reserved word in python 2.x, so using file_
        with open('tempPythonCode.py', 'w') as file_:
            file_.write(source)

        return file_

    def _check_code_for_errors(self, source_file):
        try:
            file_ = open(source_file.name, 'r')
            py_compile.compile(file_.name, doraise=True)
        except py_compile.PyCompileError:
            return {'errors': 'You have a problem in your syntax'}

    def post(self, request, *args, **kwargs):
        source = request.data

        if not source:
            raise InformationMissingInRequestError()
        else:
            source_file = self._write_code_to_file(source)
            response = self._check_code_for_errors(source_file)

        if response.get('errors', None):
            return Response(response, status=status.HTTP_400_BAD_REQUEST)
        else:
            #execute code here and return
            pass

        return Response(response, status=status.HTTP_200_OK)

我提出的要求是:

追溯

  File "tempPythonCode.py", line 1
    import os\nprint 'hi
                       ^
SyntaxError: unexpected character after line continuation character

Internal Server Error: /api/python/
Traceback (most recent call last):
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/rest_framework/views.py", line 466, in dispatch
    response = self.handle_exception(exc)
  File "/home/dhruuv/.virtualenvs/pythoneval/local/lib/python2.7/site-packages/rest_framework/views.py", line 463, in dispatch
    response = handler(request, *args, **kwargs)
  File "/home/dhruuv/projects/PythonEval/api/views.py", line 44, in post
    if response.get('errors', None):
AttributeError: 'NoneType' object has no attribute 'get'
[10/Feb/2016 09:45:44] "POST /api/python/ HTTP/1.1" 500 87401

更新 2

我在ipdb中试了一下,效果很好!

In [5]: try:
    py_compile.compile('testing.py', doraise=True)
except py_compile.PyCompileError:
    print 'dfsssssssssssss'
   ...:     
dfsssssssssssss

感谢任何帮助。

【问题讨论】:

    标签: python python-2.7 api django-rest-framework


    【解决方案1】:

    SyntaxError 不是运行时错误,您无法在代码中捕获它。但是, py_compile 不会引发 SyntaxError;正如the documentation 所示,它引发了py_compile.PyCompileError

    编辑所以这里的代码有一些问题。首先,再次如文档所示,您需要传递 doraise=True 进行编译,以使其引发错误。

    另一个异常正在发生,因为如果成功,您不会从_check_code_for_errors 返回任何内容。您可能应该返回一个空字典。

    【讨论】:

    • 我之前尝试过,通过在该函数中捕获 py_compile.PyCompileError ,但即使这样也不起作用。
    • 你能显示回溯吗?也许你的函数中有一个实际的语法错误。
    • 是的,如果函数成功,我了解返回空字典。之后使用了更多代码,但对其进行了修剪以保持简洁。我将尝试使用 doraise=True,然后发布结果
    • 不幸的是,它仍然不执行 except 块,并从 _check_code_for_errors 方法返回一个空字典。虽然我在 ipdb 中尝试过,但它有效!这里还有什么问题? :(
    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 1970-01-01
    • 2018-06-19
    • 2012-07-26
    • 2017-04-16
    • 1970-01-01
    • 2017-05-02
    • 2017-11-19
    相关资源
    最近更新 更多