How to pass a variable in Python sockets?

Viewed 603

I have the python client application with the following code and it works fine:

import socket
sock = socket.socket()
sock.connect(('127.0.0.1', 55555))
sock.send(b'mkdir test') # windows command
data = sock.recv(1024)
sock.close()
print(data)

I need to input commands with input operator, e.g.:

comm = input('Input the system command: ') # mkdir test
sock.send(b'f{comm}')

But it doesn't work. I tried to change b to byte, wrote b'\f and like that. Any ideas?

1 Answers

The way you are trying it, if I'm right, you are trying to use f strings in an binary (b) string, but it can't be done. So instead, try this,

comm = input('Input the system command: ') # mkdir test
sock.send(b'{}'.format(comm, encoding='utf-8'))

This will help you achieve what you wanna do.

if that doesn't work, you can do this,

comm = input('Input the system command: ') # mkdir test
sock.send(bytes(comm, encoding='utf-8'))
Related