簡體   English   中英

如何從也存儲為變量的 python 文件中調用存儲為變量的 function?

[英]How can I call a function that is stored as a variable from a python file that is also stored as a variable?

我可以使用 import_module 導入 python 腳本。 但是,如何從該腳本調用存儲為變量的 function? 我以前使用 getattr 來處理存儲為變量的字典,但我認為這種方法不適用於函數。 這是一個當前不起作用的示例:

from importlib import import_module

file_list = ['file1','file2']
func_list = ['func1','func2']

for file in file_list:
  test_file = import_module(file)
  for func in func_list:
    from test_file import func

文件1:

def func1():
  ...

def func2():
  ...

文件2:

def func1():
  ...

def func2():
  ...

我可以使用 import_module 導入 python 腳本。

執行此操作時,結果是模塊 object - 與import語句提供的相同。

從 test_file 導入函數

這不起作用的原因是因為它正在尋找一個test_file模塊 - 它關心模塊名稱,因為它們出現在sys.path中,而不是你的局部變量名稱。

幸運的是,由於您已經擁有模塊 object,您大概意識到您可以正常訪問內容,作為屬性,例如test_file.func

我以前使用 getattr 來處理存儲為變量的字典,但我認為同樣的方法不適用於函數

我不太清楚你在這里的意思。 屬性就是屬性,無論它們是普通數據、函數、類還是其他任何東西。 test_file是具有func屬性的東西,因此getattr(test_file, 'func')獲取該屬性。

剩下的問題是變量變量問題——你真的不想動態地為這個結果創建一個名字。 所以是的,如果你願意,你可以將它存儲在一個字典中。 但坦率地說,只使用module object會更容易。 除非可能出於某種原因您需要/想要“修剪”內容並且只公開有限的界面(對於其他一些客戶端); 但你不能避免加載整個模塊。 from X import Y無論如何都會這樣做

您從動態導入中獲得的module object 已經作為命名空間工作,無論如何您都需要它,因為您正在導入具有重疊屬性名稱的多個模塊。

tl;博士:如果您想從該導入的模塊中調用 function,只需按照與正常導入模塊( from該模塊的名稱)相同的方式進行操作。 例如,我們可以將導入的模塊放在一個列表中:

modules = [import_module(f) for f in filenames]

然后通過在適當的模塊 object 中查找來調用適當的方法:

modules[desired_module_id].desired_func()

基本上,您將在一個單獨的文件中運行此代碼,並在其中顯示the_file_where_this_is_needed.py您將在您希望這些導入語句所在的位置插入文件。 (也可能您可以在非常文件中運行此代碼)。 這將有點像硬編碼但自動

file_list = ['file1', 'file2']
func_list = ['func1', 'func2']


with open('the_file_where_this_is_needed.py', 'r') as file:
    data = file.read()

string = ''
for file in file_list:
    for func in func_list:
        string += f'from {file} import {func}\n'

data = string + data

with open('the_file_where_this_is_needed.py', 'w') as file:
    file.write(data)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM