如何将二进制字符串的文字字符串表示形式转换为二进制字符串?
How to convert a literal string representation of binary string to a binary string?
我正在尝试将函数保存到 csv 文件中,其中包含其他描述字段。我目前正在使用莳萝转储保存一个函数,然后将其转换为文字字符串并存储在文件中。当我加载 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))
我建议将其保存为十六进制字符串(下面的实现假定 python 3.5+)
import dill
tmp = dill.dumps(lambda a: a + 1).hex()
loaded = dill.loads(bytes.fromhex(tmp))
print(loaded(2))
我正在尝试将函数保存到 csv 文件中,其中包含其他描述字段。我目前正在使用莳萝转储保存一个函数,然后将其转换为文字字符串并存储在文件中。当我加载 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))
我建议将其保存为十六进制字符串(下面的实现假定 python 3.5+)
import dill
tmp = dill.dumps(lambda a: a + 1).hex()
loaded = dill.loads(bytes.fromhex(tmp))
print(loaded(2))