python - 我有插座和泡菜的问题。值不保存到 txt
问题描述
我的 Python 代码的想法是从网络套接字读取值,并用 pickles 将值保存在 txt 文件中,以供以后在另一个应用程序中使用。
它不一定必须是 txt 文件,但它是我正在尝试使用的。
通信工作得很好,他创建了 txt 文件,但遗憾的是没有记录任何内容。
有人可以帮助我。谢谢。
服务器代码:
import socket
import pickle
HOST = ''
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
orig = (HOST, PORT)
tcp.bind(orig)
tcp.listen(10)
filename = 'data.txt'
while True:
con, cliente = tcp.accept()
print('connector by', cliente)
while True:
msg = con.recv(4096)
if not msg: break
print(msg)
with open(filename, 'wb') as f:
pickle.dumps(msg, f)
print('Ending client connection', cliente)
con.close()
客户代码:
import socket
HOST = '10.0.0.120'
PORT = 5000
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dest = (HOST, PORT)
tcp.connect(dest)
print('to exit press CTRL+C\n')
msg = input()
while msg != '\x18':
msg = input()
tcp.sendall(msg.encode('utf8'))
tcp.close()
解决方案
你使用了错误的方法。pickle.dumps
产生一个字符串并且不接受文件参数。实际上,您应该从该代码中得到一个异常:
TypeError: an integer is required (got type _io.BufferedWriter)
如果您更改代码以使用pickle.dump
它,它可以正常工作,因为这是转储到文件的正确方法。这是一个演示它工作的示例(不需要套接字,因为这是关于如何pickle
工作,而不是关于网络)。
import pickle
foo = b'Some test string'
print("Pickling string '{}'".format(foo))
with open("/tmp/test.pickle", "wb") as tfile:
pickle.dump(foo, tfile)
with open("/tmp/test.pickle", "rb") as tfile:
bar = pickle.load(tfile)
print("Reloaded string '{}'".format(bar))
# Confirm they're identical
assert foo == bar
推荐阅读
- gensim - 使用 Gensim 4.0 微调预训练的 Word2Vec 模型
- node.js - Node JS https 检查下载的图像是否 100% 完成
- windows - JFrog 安装在 Windows 10 上一直失败
- c# - AADSTS50020 来自身份提供商“live.com”的用户帐户“xxx@zbc.com”在租户“xx-xx-xx-xx”中不存在 C# Winforms 中的错误
- ios - 如何在 UITableView 中动态调整自定义 UITableViewCells 的大小?
- shopware - 购物软件:PayPal 未出现
- python - 如何将文本数据转换为 DataFrame
- r - 带引号和不带引号有什么区别
- angular - 从组件更改模型时未调用 ngModelChange
- java - createCriteria() 函数会影响 Mysql 数据库吗?