简体   繁体   English

如何使用 exec Python 从 txt 文件中获取 function 值

[英]How to get function value from txt file with exec Python

I want to execute python code from txt file and store it.我想从 txt 文件执行 python 代码并存储它。

In txt file I have this code:在 txt 文件中,我有以下代码:

def func(a):
    return a

In python:在 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: .txt 文件示例:

def hello():
    print("Hello")

first you need to read needed part of python code from.txt file首先,您需要从.txt 文件中读取 python 代码所需的部分

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

and then execute it as python code然后将其作为 python 代码执行

>>> exec(data)

now if you know name of function you are able to call function from.txt file and store results in variable现在,如果您知道 function 的名称,您就可以从.txt 文件中调用 function 并将结果存储在变量中

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

exec()执行()

Documentation says: This function supports dynamic execution of Python code.文档说:这个 function 支持 Python 代码的动态执行。 object must be either a string or a code object. object必须是字符串或代码 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).如果它是一个字符串,则该字符串被解析为一组 Python 语句,然后执行(除非出现语法错误)。 If it is a code object, it is simply executed.如果是代码object,则简单执行。

But as it's mentioned in this answer it's not safe但是正如这个答案中提到的那样,它不安全

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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