简体   繁体   English

猴子修补datetime.datetime时,Python“ atexit._run_exitfuncs错误”

[英]Python “Error in atexit._run_exitfuncs” when monkey patching datetime.datetime

I have a program that's working fine, then I added this code for testing purposes: 我有一个运行良好的程序,然后出于测试目的添加了以下代码:

class datetimeMock(datetime.datetime): 
    def utcnow():
        return datetime.datetime (2013, 12, 17, 12)

if __name__=="__main__":

    #testing:
    datetime.datetime = datetimeMock        

    # start processing ...

Now the program seems to be working fine, but I'm getting this error on exit: 现在程序似乎运行良好,但是退出时出现此错误:

Error in atexit._run_exitfuncs:                                                              
Traceback (most recent call last):                                                           
  File "C:\Python33\lib\site-packages\IPython\core\history.py", line 508, in end_session     
    len(self.input_hist_parsed)-1, self.session_number))                                     
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.               

Can anyone make sense of this error? 任何人都可以理解这个错误吗?

Replacing a builtin type is begging for trouble ;-) Try restoring datetime.datetime to its original value before your program exits. 替换内置类型很麻烦;-)在程序退出之前,尝试将datetime.datetime还原为其原始值。 atexit is run when the program is shutting down (see the docs - it's a standard Python module). 当程序关闭时,将运行atexit (请参阅文档-这是一个标准的Python模块)。 Presumably IPython is using sqlite3 when the program ends to store some history, and your bogus datetime.datetime class is confusing the heck out of it. 大概在程序结束存储某些历史记录时, IPython正在使用sqlite3 ,而您虚假的datetime.datetime类使它混乱了。

orig_datetime = datetime.datetime  # new
datetime.datetime = datetimeMock   # the same

try:
    # start processing
    ...
finally:
    datetime.datetime = orig_datetime

Or run your program from a vanilla shell, instead of via IPython. 或从普通外壳运行程序,而不是通过IPython运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM