简体   繁体   中英

How to get function value from txt file with exec Python

I want to execute python code from txt file and store it.

In txt file I have this code:

def func(a):
    return a

In python:

def random_file_input(file_name):
    ran_number = random.randint(0, 100)
    with open(file_name, 'r+') as f:
        data = f.read()
        f.write(f"\nfunc({ran_number})")
        a = exec(data)  #-----> i want to store like this  :( 

random_file_input('python_code.txt') ```

.txt file example:

def hello():
    print("Hello")

first you need to read needed part of python code from.txt file

>>> with open("better.txt", 'r+') as f:
...     data = f.read()

and then execute it as python code

>>> exec(data)

now if you know name of function you are able to call function from.txt file and store results in variable

>>> b = hello()
>>> print(b)
Hello

exec()

Documentation says: 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). If it is a code object, it is simply executed.

But as it's mentioned in this answer it's not safe

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM