如何从Python程序中调用存储在另一个文件中的函数?

Hic*_*ick 4 python

如果我有一个包含python函数定义的文本文件,我如何从另一个Python程序调用函数.Ps:该函数将在执行调用的Python程序中定义.

可以做的方式:

  1. 将python函数视为一个模块并调用它.这里的约束是我必须将python bare函数转换为一个会产生错误的模块.

  2. 将代码(功能代码)插入调用该函数的程序中.

哪个是更好的方法呢?

编辑:感谢您的所有回复.对我自己最初的困惑已经有很多了解.另一个疑问是,如果这个人(显然不是我)写了一个os.system("rm -rf")会怎么样.我最终执行它.这对我来说意味着世界末日,对吗?

Edit2:由于很多人要求我使用exec,我想指出这个线程,尤其是命名空间问题.它为用户提供了很多"绕过"python的机会.你们都不觉得?

Sav*_*era 5

您正在寻找exec关键字.

>>> mycode = 'print "hello world"'
>>> exec mycode
Hello world
Run Code Online (Sandbox Code Playgroud)

因此,如果您将文本文件作为文本读取(假设它只包含该函数),例如:

的test.txt:

def a():
    print "a()"
Run Code Online (Sandbox Code Playgroud)

test.py:

mycode = open('test.txt').read()
exec mycode # this will execute the code in your textfile, thus define the a() function
a() # now you can call the function from your python file
Run Code Online (Sandbox Code Playgroud)

链接到doc:http://docs.python.org/reference/simple_stmts.html#grammar-token-exec%5Fstmt

您也可以查看编译语句:此处.