Flag "print" statements in Python code
Asked Answered
B

4

16

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?

Barbour answered 11/8, 2014 at 18:2 Comment(0)
A
17

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.
Ase answered 11/8, 2014 at 18:8 Comment(1)
Shameless plug, but flake8-print has some dependencies that made it unusable in one of projects I was working on. I found this thread though and created my own package that detects print statements: NoPrint. No dependencies outside of what's already included with basic Python installation. Should be working on Linux, Mac and Windows with Py >= 3.7.Uncleanly
S
10

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.

Stillborn answered 11/8, 2014 at 18:18 Comment(9)
Nice alternative! FYI, flake8-print uses regex-approach.Ase
My 20 cents I make for detects a "import pdb" setence too: gist.github.com/moylop260/10f3e5c7e1c3acfa0ffbBarbour
Cool, I wrote flake8-print mostly because we needed something at work. I didn't know about ast. I'm going to take a look at this when I have time.Runion
@JosephKahn, the problem with regex in flake8-print is with setence print but not print. Example: "comment with word print bad for flake8-print". Can you give me your repository and I can make a PRBarbour
@JosephKahn, Oh cool, I saw this commit change: github.com/JBKahn/flake8-print/commit/…Barbour
@Barbour Ya, I'll take a look at making a non-regex change to flake8-debugger as well, just got pretty busy with classes.Runion
FYI now pylint add support to detect print sentence with enable E1601Barbour
@Barbour the question is about disabling print in favour to logging for example. E1601 is about disabling print statements in favour to print function. It doesn't warn when you use print function.Damicke
Checking for isinstance(node, ast.Print) won't work with newer versions. For Python 3 use node.__dict__.get("id") == "print" instead.Upstage
Q
2

There is also Ruff, which implements the same flake8-print rules.

Using this simple one line file.

print("Hello print!")

Can be quickly checked for print statements with ruff by selecting the T rules.

(venv) PS G:\Testing> ruff test.py --select T
test.py:1:1: T201 `print` found
Found 1 error.

For a more permanent way to enable the rules, you can check the different to configure ruff.

Quanta answered 20/8, 2023 at 11:2 Comment(0)
P
0

Not perfect: lines like 'print_something()' would be detected, too. But most cases should be catched with this:

import os
import sys

for root, dirs, files in os.walk(sys.argv[1]):
    dirs.sort()
    for file in files:
        file=os.path.join(root, file)
        for i, line in enumerate(open(file)):
            line=line.strip()
            if line.startswith('print'):
                print file, i, line
Piggin answered 11/8, 2014 at 18:8 Comment(1)
FYI now pylint support print sentence with error: E1601Barbour

© 2022 - 2024 — McMap. All rights reserved.