Skip to main content
 首页 » 编程设计

python之使用 py_compile 时未捕获语法错误

2025年05月04日7mfryf

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

self._check_code_for_errors(source_file) 

它不执行 except block ,我在其中捕获 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 

感谢任何帮助。

请您参考如下方法:

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

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

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