How can I get results from exec()?
Any suggestions appreciated!!!

#!/usr/bin/python
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = socket.gethostname()
port = 1234
sock.bind((host,port))

while True:
    cmd, addr = sock.recvfrom(1024)
    if len(cmd) > 0:
        print("Received ", cmd, " command from ", addr)
        exec(cmd) # here how I can get results?
        print( "results:", <for example results printed here> )

sock.close()
cmd = 'a = 1'
code = compile(cmd, "script", "exec")
ns = {}
exec code in ns
print ns['a']   # should get 1

Like this I believe...

#!/usr/bin/python
import socket
import subprocess

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
host = socket.gethostname()
port = 1234
sock.bind((host,port))

while True:
    command, addr = sock.recvfrom(1024)
    if len(command) > 0:
        print("Received ", command, " command from ", addr)
        exec_command = subprocess.Popen(command, stdout=subprocess.PIPE)
        print(exec_command.stdout.read())

sock.close()

Cheers and Happy coding

Edited 6 Years Ago by Beat_Slayer: n/a

Thank you Beat_Slayer. I use your solution. Thank you cghtkh for your answer too.

You can also tweak it to don't show the process window.

If on windows it would get like this.

exec_command = subprocess.Popen(command, stdout=subprocess.PIPE, creationflags=0x08000000)

Cheers and Happy coding

This question has already been answered. Start a new discussion instead.