How to Execute Code That Is in a String

How do I execute a string containing Python code in Python?

In the example a string is executed as code using the exec function.

import sys
import StringIO

# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()

code = """
def f(x):
x = x + 1
return x

print 'This is my output.'
"""

# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr

exec code

# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

print f(4)

s = codeErr.getvalue()

print "error:\n%s\n" % s

s = codeOut.getvalue()

print "output:\n%s" % s

codeOut.close()
codeErr.close()

Execute JavaScript code stored as a string

With the eval function, like:

eval("my script here");

Run piece of code contained in a String

As has already been suggested you can compile, save and run code on the fly using the Compiler API.

Another neat alternative would be to use beanshell. Beanshell is no longer actively developed, but I can vouch for it's reliability, I've used it successfully in multiple production projects.

Python: using eval to execute code in the string

You're looking for exec not eval:

code = """
if age > 18:
if salary > 100000:
print('success')
elif salary < 50000:
print('fail')
else:
print('get_more_info')
else:
print('fail')"""

exec(code, {"age": 20, "salary": 60000})
# out: get_more_info

exec takes a code string, or an code object. While eval takes an expression.


Alternatively, you can always evaluate (using eval) code objects by compiling the code string beforehand:

eval(compile(code, '<string>', 'exec'), {"age": 20, "salary": 60000})
# out: get_more_info

Just for the fun of it, you can use eval for your syntax tree without needing to compile your code, but your code has to be a bit different:

code = 'print(("success" if salary > 100000  else "fail" if salary < 50000 else "get_more_info") if age > 18 else "fail")'

eval(code, {"age": 20, "salary": 60000})
# out: get_more_info

This utilizes Python's ternary conditions, which technically is still counted as an expression.

Execute code from a String in Java

You can't do this as easily as I imagine you hope to. The kind of thing you're describing is something you might see in a dynamic language. Java is very much not a dynamic language - this is part of its character.

If you have tools.jar in your classpath, you can compile Java code from within your Java program:

com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
String[] options = new String[] {
"-classpath", classpath, "-d", outputDir, filename
};
javac.compile(options);

From there you could wrestle with the classloader, load the class you have compiled, and run it.

However this is not an easy or mainstream way to use Java, and generally people don't do it because it's neither good practice nor necessary. It is a security feature that you can't run code supplied by the user after compilation.


If you want a more dynamic language, in the Java ecosystem, you could look at Groovy.


Alternatively, you can run user-supplied Javascript, giving it controlled access to your Java program's data, using the Java Scripting API.

Execute a string as a command

You can use eval.eval() is used to evaluate expression, If you want to execute a statement, use exec()

See example for eval:

def fun():
print "in fun"

eval("fun()")

x="fun()"
eval(x)

See example for exec.

exec("print 'hi'")

Execute a string as a piece of HTML/javascript code

You can use eval, and yes multiple statements will be executed. BUT, it is generally a bad idea to use eval. In most cases you can probably accomplish whatever you are trying to do without eval.

eval can be quite dangerous if used with user supplied code, such as something from a form or URL. It opens you up to Cross-Site Scripting (XSS) attacks. Just avoiding it is the best course of action, as this answer mentions, sanitizing input before putting it through eval is not at all straight forward and very error prone.

A couple of other less important problems with using eval are that it makes code hard to debug and it is slow. It makes it hard if not impossible for browsers to optimize and/or cache it like they do other code.

Update

I'm surprised I neglected to mention this when I originally answered this, but explicitly using the eval statement is not the only way eval can be invoked in JavaScript. Passing code instead of a function reference to setTimeout or setInterval will implicitly eval that code.

// This evals:
setTimeout("doSomething()", 1000);
// This does not eval:
setTimeout(doSomething, 1000); // also shorter :)

Although not exactly the same as eval, the Function constructor also has similar security concerns associated with it.

let xss = 'alert("XSS")';

// whatever is in the string passed to Function

// becomes the body of the function

let doSomething = new Function(xss);

document.querySelector('button').addEventListener('click', doSomething, false);
<button>Do Something</button>

Executing a string as python code and storing output + errors

Try surrounding the execution code in a try/except block.

try:
exec(my_code)
except:
print("Unexpected error:", sys.exc_info()[0])
raise


Related Topics



Leave a reply



Submit