Using signal module without pylint's warnings

2019-07-08 10:19发布

问题:

I am discovering python's signal module and I wrote this script for my first implementation:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" First implementation of signal module """
import time
import signal
import os
import sys


def cls():
    """ console clearing """
    os.system('clear')
    return


def handler(signal, frame):
    """ Catch <ctrl+c> signal for clean stop"""
    print("{}, script stops".format(time.strftime('%H:%M:%S')))
    sys.exit(0)


signal.signal(signal.SIGINT, handler)

START_TIME = time.strftime('%H:%M:%S')
PROGRESSION = str()


while True:
    time.sleep(2)
    PROGRESSION += "."
    cls()
    print("{}, script starts\n{}".format(START_TIME, PROGRESSION))

Except the annoying ^C string appearing after interrupt, the script work as expected:

14:38:01, script starts
......
^C14:38:14, script stops

However pylint3 checking gives me this return:

testsignal.py:16: [W0621(redefined-outer-name), handler] Redefining name 'signal' from outer scope (line 5)
testsignal.py:16: [W0613(unused-argument), handler] Unused argument 'signal'
testsignal.py:16: [W0613(unused-argument), handler] Unused argument 'frame'

According to the signal documentation I did it right.

If I change line 16, with a trailing underscore in signal argument (as mentioned in PEP8, I solve the warning W0621.

Is it a side effect of pylint or did I miss something?

By the way, if someone knows how to avoid the ^C string, I'll be glad too.

pylint3 --version
pylint3 1.5.2, 
astroid 1.4.4
Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1]

回答1:

pylint warns you that you have a function with two parameters you are not using inside the function, which is true and is a smell for common errors.

It also warns about using a local function name that is equal to an outer scope name, which can sometimes lead to errors, because you might be inadvertently hiding the outer name. Sometimes you do it on purpose, so pylint just annoys a bit, but you can also rename the local, as you did and get rid of the danger.

Those are just warnings not errors. Usually it is good to be warned about possible problems, even if they don't exist.

The static checker does not know how will your handler be called by the signals library. But the warning hasn't to do with that. The static tool just noticed you claim to receive two parameters but you are not using them in the handler body. Usually when you receive a parameter you want to use it right? Except that as you are registering a handler in a library for callback, you have to respect the library "protocol", or you'll get a runtime error when the callback is done from there. The static tool does not know you don't care about the signals received info, and are just printing something else; It is just saying to you: that looks strange, are you sure?