简体   繁体   English

如何找到过时的python模块?

[英]How do I find obsolete python modules?

I have written a program in python 3.3 and I am using WinPython and Inno to make a portable python installation. 我已经用python 3.3编写了一个程序,并且正在使用WinPython和Inno进行便携式python安装。 However, there are a lot of modules in the WinPython installation that I do not really need in my program. 但是,WinPython安装中有很多我的程序中实际上并不需要的模块。 Is there a way to find all modules of a python installation that are not used by a random script? 有没有办法找到随机脚本使用的python安装的所有模块?

Example: Lets say I have installed numpy and matplotlib and my program does this: 示例:假设我已经安装了numpy和matplotlib,并且我的程序执行了以下操作:

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0,2*np.pi,100)
y = np.sin(x)

plt.plot(x,y)
plt.show()

I want to delete all files in the python installation, that are not needed to run this program. 我想删除python安装中运行该程序不需要的所有文件。

A cheat's way might be to leverage the creation of pyc files at runtime. 作弊的方法可能是在运行时利用pyc文件的创建。

  1. remove all .pyc files from WinPython 从WinPython中删除所有.pyc文件
  2. ensure you have permission to make .pyc files in the WinPython folder when the program runs 确保您有权在程序运行时在WinPython文件夹中制作.pyc文件
  3. run the program 运行程序

At the end, pyc files should only have been generated for modules (.py files) that were used at runtime. 最后,仅应为运行时使用的模块(.py文件)生成pyc文件。 So any file which does not have a corresponding .pyc can be excluded. 因此,任何没有相应.pyc的文件都可以被排除。

Note however, that this will not catch compiled (.so) modules. 但是请注意,这不会捕获编译的(.so)模块。

Alternatively, and a slightly more robust method, would be to use a PathFinder or more generic Finder . 或者,一种更健壮的方法是使用PathFinder或更通用的Finder By hooking into the import mechanism, you can intercept calls Python makes to find modules that are being imported. 通过使用导入机制,您可以拦截Python进行的调用以查找要导入的模块。 You can use this to log information about the modules (and so .py files) used. 您可以使用它来记录有关所使用的模块(以及.py文件)的信息。

class MyFinder(importlib.machinery.PathFinder):
    @classmethod
    def find_module(self, fullname, path=None):
        # do some logging of the module being imported, and where it is coming from.

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

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