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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With