Ошибка ввода-вывода при выполнении операции ввода-вывода сокета Python в закрытом файле

#python #sockets #makefile #ioerror

#python #сокеты #makefile #ошибка ioerror

Вопрос:

Я хочу использовать сокет.метод makefile вместо сокета.отправить или сокет.recv но я сталкиваюсь с этой ошибкой операции ввода-вывода при закрытом файле.

 from socket import *

s = socket(AF_INET,SOCK_STREAM)
s.connect(('localhost',4321))
read = s.makefile('r',)
write = s.makefile('w')

def send(cmd):
    # print(cmd)
    write.write(cmd   'n')
    write.flush()

with s,read,write:
    send('TEST')
    send('LIST')
    while True:
        send("DONE")
        data = read.readline()
        if not data: break
        item = data.strip()
        if item == 'DONE':
            break
        elif item.startswith("--player-"):
            print(f"player{item.split('--player-')[1]}")
        print(f'item: {item}')
    send('OTHER') 
send("GGGGGGGG")  #I want to send this part in another place .I dont want to in with s,read,write:
print(read.readline().strip())
 

Заранее спасибо за помощь.

Ответ №1:

with заявление имеет такое поведение:

 with s,read,write:
    # smth to do
# <--------------- s, read and write are closed here
 

Поэтому последующая отправка вызывается для закрытого объекта.

Вам не нужно использовать with оператор:

 # ...
send('TEST')
send('LIST')
while True:
    send("DONE")
    data = read.readline()
    if not data: break
    item = data.strip()
    if item == 'DONE':
        break
    elif item.startswith("--player-"):
        print(f"player{item.split('--player-')[1]}")
    print(f'item: {item}')
send('OTHER')
send("GGGGGGGG")  # write is open here
print(read.readline().strip())
 

Или воссоздайте write и read храните файлы в другом месте. Но в то же время исключите сокет s из первого with , чтобы сокет не закрывался.

 with read, write:  # <-- s excluded
    send('TEST')
    send('LIST')
    while True:
        send("DONE")
        data = read.readline()
        if not data: break
        item = data.strip()
        if item == 'DONE':
            break
        elif item.startswith("--player-"):
            print(f"player{item.split('--player-')[1]}")
        print(f'item: {item}')
    send('OTHER')
# ...
read = s.makefile('r', )  # <-- recreate files
write = s.makefile('w')
send("GGGGGGGG")
 

Комментарии:

1. Большое вам спасибо