简体   繁体   English

从字符串python3中删除特定文本

[英]Remove specific text from a string python3

I have a server and a client that communicate using sockets.我有一个使用 sockets 进行通信的服务器和一个客户端。 The server needs to be able to download a file from the client using the command "grab" (eg, grab text.txt).服务器需要能够使用命令“grab”(例如,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.发生的情况是服务器发送“grab text.txt”,客户端以“grab text.txt example text 1234”响应,服务器收到此消息,需要取出文件名的 text.txt 和“example text 1234”文件数据。 instead it names the file "text.txt example text 1234" and correctly puts "example text 1234" inside of the file.而是将文件命名为“text.txt 示例文本 1234”,并正确地将“示例文本 1234”放入文件中。

It should be:它应该是:

filename = resp_split[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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