Pylint on StringIO or buffered text

572 views Asked by At

I need to analyze some code generated "magically" in a function. The example I'm using is very simple. Here is what I intend to do:

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)

The result I get: TypeError: cannot concatenate 'str' and 'instance' objects

I want to avoid writing to an actual file

Edit: I also tried with 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():'

The result is not the same as calling against a file:

a.py

def test():
    b = 5
    return 1

running from file

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

There are 2 answers

0
sobolevn On BEST ANSWER

I am afraid it's impossible to run analize on a code-string. The pylint docs say:

pylint [options] module_or_package

Also, 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.

But I see a workaroud. You can save your string to a temporary file and run pylint over it.

1
ron rothman On

Good news--I think you're just missing the call to getvalue:

epylint.py_run(source.getvalue())

source is a StringIO object (instance). What you want is to extract its string representation.