简体   繁体   中英

Remove specific text from a string python3

I have a server and a client that communicate using sockets. The server needs to be able to download a file from the client using the command "grab" (eg, grab text.txt). But when the client sends back the file name and data to download the server interprets the name of the file as the name + the data.

Server

try:
    conn.send(cmd.encode(ENCODING))
    resp = conn.recv(BUFFER).decode(ENCODING)
except (BrokenPipeError, IOError, TypeError):
    print('The connection is no longer available')

resp_split = resp.split(' ')
if resp_split[0] == 'grab':
    filename1 = resp_split[1:]
    filename = ' '.join([str(elem) for elem in filename1])  #Converts list to str
    filedata1 = resp_split[2:] 
    filedata = ' '.join([str(elem) for elem in filedata1])  #Converts list to str
    f = open(filename,"w+")
    f.write(filedata)
    time.sleep(2)
    f.close()
    print(filename.removesuffix(filedata))

else:
    resp = resp[2:-1]
    print(resp)

Client

command = sock.recv(COMMMAND_SIZE).decode('utf-8') # Receive command from server.
command_output = 'Invalid command.'
cmd_split = command.split(' ')
if cmd_split[0] == 'grab':
    args1 = cmd_split[1:]
    args = ' '.join([str(elem) for elem in args1])
    try:
        with open(args,'r') as file:
            file_data = "grab " + args + ' ' + file.read()
        command_output = file_data
    except Exception as e:
        print(e)
else:
    command_output = self.exec_windows_cmd(command)
    sock.send(bytes(str(command_output), 'utf-8'))

What happens is the server sends "grab text.txt" and the client responds with "grab text.txt example text 1234" and the server receives this and needs to take out text.txt for the file name and "example text 1234" for the file data. instead it names the file "text.txt example text 1234" and correctly puts "example text 1234" inside of the file.

It should be:

filename = resp_split[1]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM