-3

I have a function

def output5() :
    print("OK")
def output5() :
    print("no")
def output5() :
    print("yes")

So If I make code like this

 output5()
 output6() 
 output7()

it will say ok no yes

And I have a file output.txt and there are messages follow:

output5() 
output6() 
output7()

I wanted to implement a function in python like:

a=open('output.txt').readlines()
a

so that ok no yes would be printed

but it only says:

'output5()\n', 'output6()\n', 'output7()\n'

not ok no yes

how can I execute functions included in txt file?

1 Answers1

1

Warning: Using exec or execfile is generally considered bad practice and possibly unsafe (Why should exec() and eval() be avoided?). While it is the answer to your question, you should probably use another solution.

If I interpret the question correctly, you could do one of these, depending on your python version:

  • Python 2: you can use execfile('output.txt')
  • Python 3: exec(open('output.txt').read())

Note that this is not the usual way to do things in python. You should probably use a module (https://docs.python.org/2/tutorial/modules.html), unless you have strong reasons not to.

Keldorn
  • 1,980
  • 15
  • 25
  • My hypothesis is that `output.txt` contains a list of functions to be called, and that these functions are already defined in the steering script (the one "reading" `output.txt`). But I can be wrong. – Keldorn Feb 17 '19 at 18:18
  • Another issue is that python3 seems to have dropped execfile() – John Coleman Feb 17 '19 at 18:28
  • @frankpaek I'm still confused. If I had to guess again what you want to do, I would give the same answer. – Keldorn Feb 17 '19 at 19:34
  • it says NameError: name 'execfile' is not defined – frank paek Feb 17 '19 at 19:54
  • I have output1 to output10 txt files, they include certain senteces. and I've made the code to arrange them in permutation order. so in def output() , it would be like output1() output3() output7() output4() like this. – frank paek Feb 17 '19 at 20:04
  • Thanks a lot mate! You're awesome and sorry for my English skill and poor python skill :( I really appreciate it !!! Have a good day :D – frank paek Feb 17 '19 at 20:19
  • 1
    This might be good for OP's use-case, but it might be good to give the customary warning about the security dangers of things like `eval()` and `exce()`. Is OP 100% sure that these text files will never contain malicious code? – John Coleman Feb 17 '19 at 20:38
  • @JohnColeman Added. How is it worth than importing and using a module though? One still needs to be 100% sure that these module never contain malicious code. – Keldorn Feb 18 '19 at 16:29