首页 > 解决方案 > 如何创建当前导入模块的列表?

问题描述

我在同一个目录中有两个不同的 .py 文件 - Setup.py& Main.py。在Setup.py我有以下函数定义。

def imported_modules(send_to_reqs = False,append_mod = True) :
    '''
    inputs: 
    - send_to_reqs, boolean, optional, default true:
        - If true, function will return a dictionary keys = modules, values = version that has been imported
        - If false, function will write to requirements text, 
    - append_mod, boolean, optional, default False:
        - If True, function will append to requirements
        - If False, fucntion will overwrite requirements    
    '''
    import sys 
    # gets list of modules imported
    modules = list(set(sys.modules) & set(globals()))
    modules_dict = {}
    #iterates through the list of modules and appends a dictionary with the verison 
    for module_name in modules:
        module = sys.modules[module_name]
        modules_dict[module_name] =  getattr(module, '__version__','unknown')
    #writes to the reqs document 
    if send_to_reqs == True:
        if append_mod == True:
            # opens the requirements text as append only and appends the modules to it 
            f = open("Requirements.txt","a+")
            for key, value in modules_dict.items() :
                f.writelines(str(key + ":" + value + "\n" ))
            f.close()
            return "Requirements.txt has been updated with latest modules."
        else:
            # opens requirements an removes existing modules and attaches new ones.
            # opens as read only and saves the previous data. 
            f = open('Requirements.txt', 'r')
            data = f.read()
            f.close()
            import re, datetime
            # substitutes the last updated entry with currents date and time 
            data = re.sub("(Last updated:) (\d*-\d*-\d* \d*:\d*:\d*.\d*)","Last updated: " + str(datetime.datetime.now()), data)
            #searchs for the position of --END and gets location
            a = re.search(r'(.*?)(?=--END)',data)
            # uses location to get 
            updated_header = data[:int(a.end()+6)]
            for key ,value in modules_dict.items() :
                updated_header = updated_header  + key + ":" + value + "\n" 
            f = open('Requirements.txt', 'w')
            f.write(updated_header)
            f.close()
            return "Requirements file has been replaced."
    else :
        return modules_dict

我的函数经过一些逻辑,但本质上是获取导入模块的字典并将其写入文件。

在我的Main.py工作中,我基本上只是导入了一堆模块来测试功能。然后我尝试导入该函数并查看结果。每次我执行时,我都会得到一个空白列表,我希望得到一个列表(numpy,win32com,bs4,scipy,Setup),因为我做的第一件事就是导入这些模块。

import numpy, win32com , bs4, scipy, Setup
send_to_reqs = True
append_mod = True
a = Setup.imported_modules(send_to_reqs, append_mod)
print(a)

当我创建代码时,我在里面定义了函数Main.py,一旦我让它工作,我就搬出去了,Setup.py但现在它总是打印出一个空白字典。谁能帮我解决我的代码问题?为什么它在同一个 .py 文件中定义但当我将它写入另一个 .py 文件但在同一个目录中并导入函数时它不起作用?这是创建字典的函数的一部分

import sys 
# gets list of modules imported
modules = list(set(sys.modules) & set(globals()))
modules_dict = {}
#iterates through the list of modules and appends a dictionary with the version 
for module_name in modules:
     module = sys.modules[module_name]
     modules_dict[module_name] =  getattr(module, '__version__','unknown')

标签: pythonpython-3.x

解决方案


推荐阅读