首页 > 解决方案 > 我有插座和泡菜的问题。值不保存到 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()

标签: pythonsocketsipcpickle

解决方案


你使用了错误的方法。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

推荐阅读