Send the output of os.system () to a variable

1

I'm doing a program that uses a socket to send a string from the client to the server and that string is saved in a variable and the following happens:

cmd = sock.recv(1024).decode()
os.system(cmd)

The thing is that I want to send the output to the client, something like this:

output = os.system(cmd)
sock.send(output.encode())

It is not necessary to be with os.system () as long as you can put the output in a variable, thanks.

    
asked by binario_newbie 26.07.2018 в 07:22
source

1 answer

1

os.system() does not return any value, so if you want to get the response of the command you should use:

  • os.popen()

    cmd = sock.recv(1024).decode()
    output = os.popen(cmd).read()
    sock.send(output.encode())
    
  • subprocess.Popen()

    cmd = sock.recv(1024).decode()
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    (output, err) = proc.communicate()
    sock.send(output.encode())
    

Credits: link

    
answered by 26.07.2018 / 08:09
source