Run string as python code

How to Execute a String Containing Code in Python

In this quick tutorial, we’ll show how to execute string containing Python code in Python and Jupyter.

In other words we will run Python code dynamically from another Python code. We’ll first look into executing code with statements, then code with expressions, and finally we will cover Jupyter Notebooks.

Step 1: Execute a String statements in Python

We can use method exec to execute statement stored as a string in Python code.

Below we can find simple example of executing string as code in Python with exec() :

some_code = 'print ("Hello World!")' exec(some_code) 

The result is printing the:

More information about method exec() can be found in the official documentation: exec — Built-in Functions

The method is described as:

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).

The parameters of the method exec :

  • object — Either a string or a code object
  • globals (optional) — a dictionary
  • locals (optional)- a mapping object

The parameters globals and locals allow a user to specify what global and local functions / variables are available.

Executing or evaluating could be dangerous in some cases. Use it only if you are sure what you are doing.

Step 2: Execute a String expression in Python

To execute strings containing Python expressions we can use method — eval . Method eval takes string containing expression and evaluate it as Python code:

The official documentation can be found on this link: eval — Built-in Functions.

The method is described as:

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.

Difference between `eval` and `exec` is that — `eval(‘x=2’)` — is returning an error while `exec(‘x=2’)` works fine.

Step 3: Execute a String code in Jupyter Notebook

If you need to execute dynamically Python code which is evaluated from a string in Jupyter Notebook we can use the same methods:

Both can read code from another file or Jupyter Notebook and execute it:

Step 4: Execute a Multiline String code in Python

Finally let’s see how we can execute multiline string as a Python code with method exec in simple example:

some_code = """ x = 0 if x == False : print("x Is False") else : print("x Is True") """ exec(some_code) 

the result is printed on the Python console:

Conclusion

In this article, we looked at different solutions for executing and evaluating string expressions or statements as Python code.

We focused on executing in these code examples, but evaluating is very similar and simpler.

By using SoftHints — Python, Linux, Pandas , you agree to our Cookie Policy.

Источник

How to Execute a String Containing Code in Python

In this quick tutorial, we’ll show how to execute string containing Python code in Python and Jupyter.

In other words we will run Python code dynamically from another Python code. We’ll first look into executing code with statements, then code with expressions, and finally we will cover Jupyter Notebooks.

Step 1: Execute a String statements in Python

We can use method exec to execute statement stored as a string in Python code.

Below we can find simple example of executing string as code in Python with exec() :

some_code = 'print ("Hello World!")' exec(some_code) 

The result is printing the:

More information about method exec() can be found in the official documentation: exec — Built-in Functions

The method is described as:

This function supports dynamic execution of Python code. object must be either a string or a code object. If it is a string, the string is parsed as a suite of Python statements which is then executed (unless a syntax error occurs).

The parameters of the method exec :

  • object — Either a string or a code object
  • globals (optional) — a dictionary
  • locals (optional)- a mapping object

The parameters globals and locals allow a user to specify what global and local functions / variables are available.

Executing or evaluating could be dangerous in some cases. Use it only if you are sure what you are doing.

Step 2: Execute a String expression in Python

To execute strings containing Python expressions we can use method — eval . Method eval takes string containing expression and evaluate it as Python code:

The official documentation can be found on this link: eval — Built-in Functions.

The method is described as:

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace.

Difference between `eval` and `exec` is that — `eval(‘x=2’)` — is returning an error while `exec(‘x=2’)` works fine.

Step 3: Execute a String code in Jupyter Notebook

If you need to execute dynamically Python code which is evaluated from a string in Jupyter Notebook we can use the same methods:

Both can read code from another file or Jupyter Notebook and execute it:

Step 4: Execute a Multiline String code in Python

Finally let’s see how we can execute multiline string as a Python code with method exec in simple example:

some_code = """ x = 0 if x == False : print("x Is False") else : print("x Is True") """ exec(some_code) 

the result is printed on the Python console:

Conclusion

In this article, we looked at different solutions for executing and evaluating string expressions or statements as Python code.

We focused on executing in these code examples, but evaluating is very similar and simpler.

By using SoftHints — Python, Linux, Pandas , you agree to our Cookie Policy.

Источник

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

To execute a string containing Python code we should take the input string as multi-line input using triple quotes, then we will use the inbuilt function exec(). This will take a string as input and returns the output of the code that is present inside the string.

The exec() function is used to execute Python programmes dynamically. These programmes can be either strings or object code. If it’s a string, it’s translated into a series of Python statements that are then performed, barring any syntax errors; if it’s object code, it’s just executed.

We must be careful not to utilise return statements anywhere other than within the declaration of a function, not even in the context of code that is passed to the exec() method.

Example

In the program given below, we are taking a multi-line coded string as input and we are finding out the output of that using the exec() method −

str1 = """ a = 3 b = 6 res = a + b print(res) """ print("The output of the code present in the string is ") print(exec(str1))

Output

The output of the above example is as shown below −

The output of the code present in the string is 9 None

Using eval() function

To execute an expression that is present inside a string, we will use the inbuilt function eval() and pass the string to the function and the output of the code present inside the string is returned.

Example

In the example given below, we are taking an expression as a string as an input and we are evaluating it using eval() method −

str1 = "3 + 5" print("The output of the code present in the string is ") print(eval(str1))

Output

The output of the above example is given below −

The output of the code present in the string is 8

Источник

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

To execute a string containing Python code we should take the input string as multi-line input using triple quotes, then we will use the inbuilt function exec(). This will take a string as input and returns the output of the code that is present inside the string.

The exec() function is used to execute Python programmes dynamically. These programmes can be either strings or object code. If it’s a string, it’s translated into a series of Python statements that are then performed, barring any syntax errors; if it’s object code, it’s just executed.

We must be careful not to utilise return statements anywhere other than within the declaration of a function, not even in the context of code that is passed to the exec() method.

Example

In the program given below, we are taking a multi-line coded string as input and we are finding out the output of that using the exec() method −

str1 = """ a = 3 b = 6 res = a + b print(res) """ print("The output of the code present in the string is ") print(exec(str1))

Output

The output of the above example is as shown below −

The output of the code present in the string is 9 None

Using eval() function

To execute an expression that is present inside a string, we will use the inbuilt function eval() and pass the string to the function and the output of the code present inside the string is returned.

Example

In the example given below, we are taking an expression as a string as an input and we are evaluating it using eval() method −

str1 = "3 + 5" print("The output of the code present in the string is ") print(eval(str1))

Output

The output of the above example is given below −

The output of the code present in the string is 8

Источник

Читайте также:  Html hide link in status bar
Оцените статью