【发布时间】:2016-05-31 05:31:55
【问题描述】:
我有一个大型 python 程序,需要在新的虚拟环境中运行(在另一台机器上)。该程序导入了几个外部模块(需要先在新环境中安装)。
例如,我的一个模块具有以下导入:
import matplotlib
import os
from kivy.uix.label import Label
import my_file.my_module_5 as my_mod_5
另一个模块有:
import my_module_7
import django
在这种情况下,我需要创建一个这样的列表:
['matplotlib', 'kivy', 'django']
请注意,我自己的模块不包括在内,因为它们是将迁移到新环境的程序的一部分,并且不必安装。像os 这样的python 模块也不是。
我创建了一个函数来查找我项目中所有导入的模块并过滤掉那些属于项目本身的模块。但是,它也会返回标准的 Python 模块,例如 os、sys 等。
def all_modules_in_project():
"""
Finds all modules imported in the current working directory tree.
:return: Set of module names.
"""
project_directories = set()
project_files = set()
modules_imported = set()
for path, dirs_names, files_names_in_dir in os.walk(os.getcwd()):
project_directories |= set(dirs_names)
for file_name in files_names_in_dir:
if file_name.endswith('.py'):
project_files.add(file_name[:-3])
with open(path + '/' + file_name, 'r') as opened_file:
file_lines = opened_file.readlines()
for line in file_lines:
# import XXX
match = re.match(r'import\s([\w\.]+)', line)
if match:
modules_imported.add(match.groups()[0])
# from XXX
match = re.match(r'from\s([\w\.]+)', line)
if match:
modules_imported.add(match.groups()[0])
# Removes XXX that were matched as follows `import proj_dir. .. .XXX`
for module in modules_imported.copy():
matched = re.match(r'(\w+)\.', module)
if matched:
pre_dot = matched.groups()[0]
if pre_dot in project_directories:
modules_imported.remove(module)
else:
# Replaces `xxx.yyy` with `xxx`
modules_imported.remove(module)
modules_imported.add(pre_dot)
return modules_imported - project_files - project_directories
- 如何过滤掉不需要的标准python库 安装?
- 或者,是否有其他更简单的方法来确定我的程序使用了哪些外部库?
(我不需要all installed packages;我只需要程序导入的那些)
【问题讨论】:
-
pip freeze > requirements.txt -
@BobDylan 我只需要 我在项目中使用的包。您的建议将包括所有已安装的软件包。
-
所以你想忽略未使用的导入?
-
@JoshJ 我只需要导入的外部模块,未导入的应该忽略。被使用与否无关紧要(无论如何它们都被使用了)。这让我意识到我的编辑使我的问题不清楚。对不起,我会回复/改进这个问题。
标签: python pycharm python-3.4