如何将二进制字符串的文字字符串表示形式转换为二进制字符串?

时间:2021-01-19 18:50:30

标签: python dill

我正在尝试将函数保存到一个带有其他描述字段的 csv 文件中。我目前正在使用 dill dumps 保存一个函数,然后将其转换为文字字符串并存储在文件中。当我加载 csv 文件时,我在将此文字字符串转换回函数时遇到问题。有没有办法将二进制字符串的字符串表示形式转换为二进制字符串?目前我使用 exec 来这样做,但我认为这不是一个好习惯。

或者有其他更好的方法将函数或二进制字符串存储到 csv 文件中吗?

import dill
def add_one(a):
    return a + 1

output_to_csv_file = str(dill.dumps(add_one)) # output_to_csv_file is the string representation of binary string of add_one
exec("tmp = " + output_to_csv_file) # Now I have tmp storing the binary string
loaded_add_one = dill.loads(tmp)
print(loaded_add_one(2))

1 个答案:

答案 0 :(得分:0)

我建议将其保存为十六进制字符串(以下实现假设 python 3.5+)

import dill

tmp = dill.dumps(lambda a: a + 1).hex()
loaded = dill.loads(bytes.fromhex(tmp))
print(loaded(2))
相关问题