Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flag "print" statements in Python code

I don't want "print" statements in our Python modules, because we will be using a logger.

I'm trying to generate a script to check modules with pylint. However, pylint currently does not detect this as a warning or error.

I want to detect "print" invocations as an error or a warning in accordance with our internal Python programming standard.

How can I achieve this?

like image 359
moylop260 Avatar asked Aug 11 '14 18:08

moylop260


2 Answers

flake8 has a flake8-print plugin specifically for the task:

flake8-print

Check for Print statements in python files.

DEMO:

$ cat test.py
s = "test"
print s

$ flake8 test.py
test.py:2:1: T001 print statement found.
like image 63
alecxe Avatar answered Oct 19 '22 17:10

alecxe


If for some reason you don't want to use flake8-print as suggested by @alecxe you can roll your own using the ast module - which makes use of Python's compiler to parse the file so you can reliably find print (instead of lines just starting with print):

Code:

import ast

with open('blah.py') as fin:
    parsed = ast.parse(fin.read())

for node in ast.walk(parsed):
    if isinstance(node, ast.Print):
        print 'print at line {} col {}'.format(node.lineno, node.col_offset)

blah.py:

def print_test():
    print 'hello'

print 'goodbye'

Output:

print at line 4 col 0
print at line 2 col 1

You can use os.walk or os.listdir or whatever's most suitable if you wish to navigate a folder or subfolder.

like image 25
Jon Clements Avatar answered Oct 19 '22 19:10

Jon Clements