Python how to execute code from a txt file

前端 未结 2 1820
盖世英雄少女心
盖世英雄少女心 2021-01-15 19:39

I want to keep a piece of code in a txt file and execute it from my Python script.

For example in the txt file there is

print(\"ok\")

I

2条回答
  •  温柔的废话
    2021-01-15 20:07

    You are looking for eval function

    eval is a function that takes arbitrary python code represented as a string and execute it at run time.

    Example

    >>> x = 1
    >>> y = eval('x+1')
    >>> print(y)
    2
    

    It works in both Python 2.x and 3.x

    Check the documentation : https://docs.python.org/2.7/library/functions.html#eval

提交回复
热议问题