【问题标题】:Can't pickle local object 'ArgumentParser.__init__.<locals>.identity无法腌制本地对象 'ArgumentParser.__init__.<locals>.identity
【发布时间】:2021-12-22 02:05:56
【问题描述】:
import argparse
import pickle

parser = argparse.ArgumentParser(description='Process some integers.')
_ = pickle.dumps(parser)

在我的代码中,ArgumentParser 对象是序列化的。但在运行时我收到错误Can't pickle local object 'ArgumentParser.__init__.&lt;locals&gt;.identity。 在Lib/argparse.py 中,identity 是在__init__ 方法中本地定义的函数,这可以防止序列化。如果将此函数转换为方法,则序列化成功。但我认为这种方式不是最好的解决方案,因为 python 库文件正在被更改。如何序列化解析器对象的最佳方式?

【问题讨论】:

  • 我从来没有听说过有人试图腌制这个,所以很可能存在未经测试的问题。为什么需要这样做?运行脚本时使用解析器。

标签: python serialization pickle argparse


【解决方案1】:

我有一个程序使用子解析器并初始化 ArgumentParser 明显延迟启动,即使是 -help。我试验了几件事,遇到了这个。我发现这行得通。

from argparse import ArgumentParser
from pickle import dumps

def identity(string):
    return string

p = ArgumentParser()
p.register('type', None, identity)
x = dumps(p)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-16
    • 1970-01-01
    • 2020-09-22
    • 2022-01-02
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    相关资源
    最近更新 更多