簡體   English   中英

從字符串python3中刪除特定文本

[英]Remove specific text from a string python3

我有一個使用 sockets 進行通信的服務器和一個客戶端。 服務器需要能夠使用命令“grab”(例如,grab text.txt)從客戶端下載文件。 但是當客戶端發回文件名和數據下載時,服務器將文件名解釋為名稱+數據。

服務器

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)

客戶

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'))

發生的情況是服務器發送“grab text.txt”,客戶端以“grab text.txt example text 1234”響應,服務器收到此消息,需要取出文件名的 text.txt 和“example text 1234”文件數據。 而是將文件命名為“text.txt 示例文本 1234”,並正確地將“示例文本 1234”放入文件中。

它應該是:

filename = resp_split[1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM