如何在txt-fi中执行函数

2024-09-30 06:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数

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

所以如果我做这样的代码

 output5()
 output6() 
 output7()

它会说 好 啊 不 是的

我有一份档案输出.txt下面是一些信息:

output5() 
output6() 
output7()

我想用python实现一个函数,比如:

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

这样就可以打印ok no yes了

但它只说:

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

不好不好

如何执行txt文件中包含的函数?你知道吗


Tags: 函数no代码txt信息outputdefok
1条回答
网友
1楼 · 发布于 2024-09-30 06:19:37

警告:使用execexecfile通常被认为是不好的做法,可能是不安全的(Why should exec() and eval() be avoided?)。虽然这是你问题的答案,但你可能应该使用另一种解决方案。你知道吗

如果我正确地解释了这个问题,您可以执行以下操作之一,具体取决于您的python版本:

  • python2:您可以使用execfile('output.txt')
  • Python 3:exec(open('output.txt').read())

请注意,这不是python中通常的处理方式。您可能应该使用模块(https://docs.python.org/2/tutorial/modules.html),除非您有充分的理由不这样做。你知道吗

相关问题 更多 >

    热门问题