python atexit错误:第一个参数必须是可调用的

时间:2018-02-22 01:32:52

标签: python python-2.7 python-3.6 atexit

使用Python 3.6,我试图在程序终止但是得到一个" TypeError时自定义我的错误:第一个参数必须是可调用的"。我见过类似的问题,但它们与我没有尝试的日程安排有关。这就是我在这里提高它的原因。 我正在尝试的代码:

import atexit
def greet_me(*arg, **kwargs):
    new_json = {}
    new_json['person'] = kwargs
    print('new_json = ', new_json)
    print('passed **kwargs = ', kwargs)
    print("*arg = ", arg)
    print('arg[0] = ', arg[0])
    if kwargs is not None:
       for key, value in kwargs.items():
           print ("%s == %s" %(key,value))

def do_some_tasks():
    print("some tasks are done")

if __name__ == '__main__':
    do_some_tasks()
    text1 = 'hello1'
    atexit.register(greet_me(text1, name='peter', age= 32, gender = 'male'))

以上代码产生以下内容:

some tasks are done
new_json =  {'person': {'name': 'peter', 'age': 32, 'gender': 'male'}}
passed **kwargs =  {'name': 'peter', 'age': 32, 'gender': 'male'}
*arg =  ('hello1',)
arg[0] =  hello1
name == peter
age == 32
gender == male
TypeError                           Traceback (most recent call last)
<ipython-input-72-f01f4a5e6c64> in <module>()
       3     do_some_tasks()
       4     text1 = 'hello1'
 ----> 5     atexit.register(greet_me(text1, name='peter', age= 32, gender = 'male'))
TypeError: the first argument must be callable

在Python2.7中,错误看起来略有不同:

File "/usr/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
func(*targs, **kargs)
TypeError: 'NoneType' object is not callable

知道如何避免这种错误吗?

1 个答案:

答案 0 :(得分:1)

不要调用<body onload="main()"> <div id="max"></div> <div id="avg"></div> <div id="min"></div>,传递函数和参数。

目前你greet_me返回值,而不是函数,python 2.7识别为None,根据python 3不可调用。

您可以将第5行(从追溯)更改为

register