繁体   English   中英

Python2:从多个文件导入相同的功能

[英]Python2: Importing same function from multiple files

我正在使用Python 2.7,正在用Python做一个简单的评分器。 该平地机的工作如下:

  1. 遍历所有文件夹,并通过添加init .py将文件夹作为模块导入
  2. 运行其中一种方法,并将输出与预定义的输出进行比较
  3. 如果输出相同,则将True指定为结果,否则为False
  4. 移至下一个学生并再次导入他/她的代码

现在,所有学生都具有相同的文件名“ test.py”和相同的函数名-假设添加

我的问题-似乎当Python从第一个学生的代码中从该方法导入时,其他学生也将使用相同的方法。

样例代码

## get the output of the function
output = 5

subdirectories = "contains the directory where all student codes are"

# find python files inside each directory
# copy the init file and run the code
c = 0
for student in subdirectories:
    copyfile(src, os.path.join(student,'__init__.py')) # to make the folder a package
    os.chdir(student)

    from test import * # test is the file name

    # this line below evaluates the same function again and again instead of importing the new method from a different student file
    output_student = eval( functionName + '('+functionArguments+')')

问题-每次覆盖函数定义时,如何从多个Python文件中导入具有相同名称的方法。

我认为import_module()会做您想要的。

from importlib import import_module
...
module = import_module(<module_to_import>)
output_student = module.functionName(functionArguments)

暂无
暂无

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

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