我已经在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)


我提出的要求是:
python - 使用py_compile时未捕获SyntaxError-LMLPHP

追溯

  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


任何帮助表示赞赏。

最佳答案

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

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

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

关于python - 使用py_compile时未捕获SyntaxError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35310402/

10-12 23:10