StringIO上的Pylint或缓冲文本

时间:2015-06-15 23:47:55

标签: python io pylint

我需要分析一些生成的代码"神奇地"在一个功能。我使用的例子非常简单。以下是我打算做的事情:

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'

2 个答案:

答案 0 :(得分:2)

我担心在代码字符串上运行analize是不可能的。 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。

答案 1 :(得分:1)

好消息 - 我认为你错过了对getvalue的电话:

epylint.py_run(source.getvalue())

source是一个StringIO对象(实例)。你想要的是提取它的字符串表示。