StringIO 或缓冲文本上的 Pylint

Pylint on StringIO or buffered text

我需要分析函数中生成的一些代码 "magically"。我使用的示例非常简单。这是我打算做的:

from pylint import epylint
from StringIO import StringIO

source = StringIO()
source.write('def test():\n')
source.write('    b = 5\n')
source.write('    return\n')

source.seek(0)
epylint.py_run(source)

我得到的结果:TypeError: cannot concatenate 'str' and 'instance' objects

我想避免写入实际文件

编辑:我也尝试过 StringIO.getvalue()

epylint.py_run(source.getvalue())
/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `epylint def test():'

结果与针对文件调用不同:

a.py

def test():
    b = 5
    return 1

运行 来自文件

epylint.py_run('a.py')
No config file found, using default configuration
************* Module a
a.py:2: warning (W0612, unused-variable, test) Unused variable 'b'

好消息——我想您只是错过了对 getvalue 的呼叫:

epylint.py_run(source.getvalue())

source 是一个 StringIO 对象(实例)。您想要的是提取其字符串表示形式。

恐怕无法运行分析代码串。 pylint docs say:

pylint [options] module_or_package

此外,epylint.py

def py_run(command_options='', return_std=False, stdout=None, stderr=None,
           script='epylint'):
    """Run pylint from python

    ``command_options`` is a string containing ``pylint`` command line options;
    ``return_std`` (boolean) indicates return of created standard output
    and error (see below);
    ``stdout`` and ``stderr`` are 'file-like' objects in which standard output
    could be written.

但我看到了解决方法。您可以将字符串保存到一个临时文件中,然后 运行 pylint 覆盖它。