簡體   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