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()

Dani AI

Generated

exec() itself does not return a value; it executes code and returns None. If you want the textual output produced by that code (e.g., print() calls), capture it by temporarily redirecting stdout around the exec call. Also remember that recvfrom() returns bytes in Python 3, so decode first.

import io, contextlib

data, addr = sock.recvfrom(1024)
cmd = data.decode("utf-8", errors="replace")

buf = io.StringIO()
try:
    with contextlib.redirect_stdout(buf):
        exec(cmd, {})  # optionally provide a restricted globals dict
    output = buf.getvalue()
except Exception as e:
    output = f"error: {e}"

print("results:", output)

If the intent is to run external system commands rather than Python code, prefer subprocess.run() with output capture instead of Popen boilerplate:

import shlex, subprocess

completed = subprocess.run(shlex.split(cmd), capture_output=True, text=True)
print("stdout:", completed.stdout)
print("stderr:", completed.stderr)
print("returncode:", completed.returncode)

Be extremely careful: executing arbitrary code or commands received over UDP is a major security risk. Consider a whitelist protocol (e.g., JSON commands) instead of exec, and avoid shell=True with untrusted input. See the docs for exec, contextlib.redirect_stdout, and subprocess.run.

Recommended Answers

All 5 Replies

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.