0

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') ```
Zakoo Koo
  • 1
  • 1

1 Answers1

0

.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

Aqamarine
  • 19
  • 1
  • 7
  • I tried it in editor but it returned error. ``` 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"\ntinki({ran_number})") exec(data) a = hello() random_file_input('python_code.txt') ``` NameError: name 'hello' is not defined. Did you mean: 'help'? – Zakoo Koo Feb 05 '22 at 12:07
  • Have you defined hello() function in your .txt file? – Aqamarine Feb 05 '22 at 14:24
  • yeah but editor doesn't like it. NameError: name 'hello' is not defined. – Zakoo Koo Feb 05 '22 at 16:46
  • Error only in editor, not while execution ? Because if so editor doesn't have any information about hello() function declaration, so it will mark it as NameError but will run well. – Aqamarine Feb 05 '22 at 17:07
  • No while execution it returned error. Let me explain what I am trying to do. The task is to create a function which will read another function from the txt file. The first function should pass the parameter to the second and check if the result is more then 50. – Zakoo Koo Feb 06 '22 at 14:52
  • LOL I changed .txt files on .py and its very easy why I choose txt really don't know :( – Zakoo Koo Feb 06 '22 at 15:54
  • Definitely the best solution) Anyway why have you chosen such complex way to import functions? And it's really weird that you get error, can you pleas paste somewhere your code and share the link? – Aqamarine Feb 06 '22 at 20:38