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

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

Thank you Beat_Slayer for advanced info!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.