how do i run a python program that is received by a client from server without writing it into a new python file?
code = "for a in range(10):\n\tprint 'lol'\n"
eval(compile(code, 'downloaded_code_fake_filename', 'exec'))
but Beware of Security Issues ! The source code should be cryptographically signed and not transmitted in plaintext.
see http://docs.python.org/py3k/library/functions.html#exec for the exec()
function. it is not deprecated in py3.1. i recommend doing simply exec(code)
. values can be passed by inspecting variables in either the globals or locals dictionary:
code = """
def f(): return 42
R = f()
"""
d = {}
exec( code, d )
print( d[ 'R' ] )
I'd recommend using execnet. It's well supported and from what I've read much safer than a raw exec or eval. For what you're trying to do check out the basic examples.
Dcolish's answer is good. I'm not sure the idea of executing code that comes in on a network interface is good in itself, though - you will need to take care to verify that you can trust the sending party, especially if this interface is going to be exposed to the Internet or really any production network.