Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

If you write resp_split[1:] python grabs all items from the list, after and including index 1.

But you only want the item at index 1, so it should be:

filename = resp_split[1]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading