tags:

views:

89

answers:

4

how do i run a python program that is received by a client from server without writing it into a new python file?

+3  A: 
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.

BatchyX
code = "for a in range(10):\n\tprint 'lol'\n"eval(compile(code, 'downloaded_code_fake_filename', 'exec'))didn't understand it. could you explain a bit?
Ani Sunny
@Ani: In his answer @BatchyX has given an example of how to execute the code you'd receive from a client. `code` is a sample code snippet; copy it to IDLE and `print` it to see what it looks like. `eval` is a built in function that evaluates the code snippet assigned to the `code` variable. See the docs: http://docs.python.org/library/functions.html#eval
Manoj Govindan
is the exec function deprecated? Couldn't he just `exec(code)`?
Manux
Do we have to do something extra in case there are functions in the program that we are trying to execute through eval() ?
Ani Sunny
A: 

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' ] )
flow
+1  A: 

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
shiny! and an interesting and useful way to do distributed/agent processing in python.
A: 

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.