在Python 3中安装模块 [英] Installing modules in Python 3

查看:85
本文介绍了在Python 3中安装模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含自定义.py文件的目录.该目录称为有用的脚本"和一个名为"tested_scripts"的子目录,该子目录还包含脚本(.py文件).

Suppose I have a directory with custom .py files. The directory is called useful_scripts and a subdirectory called tested_scripts which also contains scripts (.py files).

我在某些文章中看到过导入语句,例如:

I've seen on some articles, import statements like:

from useful_scripts.tested_scripts import sth  

我们如何以一种方便的方式安装自定义目录模块,以便我们可以像上面那样访问它?

How could we install our custom directory modules in such a convienient way so that we could access it like above?

推荐答案

如果目录中有多个模块(带有.py的Python文件),并且想要在另一个模块中导入一个模块,请首先将该目录定义为python目录,或者包装

If you have multiple modules (Python file with .py ) in directory and want to import one module in another module then first define that directory to a python directory or package

包是包含多个包和模块的名称空间.Python中的每个包都是一个目录,必须包含一个名为 __ init __.py

Packages are namespaces which contain multiple packages and modules.Each package in Python is a directory which MUST contain a special file called __init__.py

Python软件包

Python Package

如果要导入模块或软件包,您的目录结构应类似于

Your directory structure should be like this if you want to import modules or package

现在您可以在模块b.py中导入模块a.py或在模块a.py中导入模块b.py

Now you can import module a.py in module b.py or module b.py in module a.py

如果要安装自定义库,请创建 setup.py ,该文件位于coustomlib目录所在的位置(在coustomlib目录外部或沿coustomlib创建setup.py)

If you want to install custom lib then create setup.py the file where coustomlib directory exists ( create setup.py outside the coustomlib directory or along coustomlib )

setup.py

#!/usr/bin/env python

from distutils.core import setup
from setuptools import setup, find_packages

setup(name='coustomlib',
  version='1.0',
  description='Python coustom lib ',
  author='your name',
  author_email='name@mail.in',
  packages=find_packages(),
 )    

用于安装运行

python setup.py install

在安装了coustomlib之后,您可以将其导入任何模块

After install coustomlib you can import it any module

import coustomlib

from coustomlib.module1 import a

有关 setup.py 的更多信息

More info about setup.py

这篇关于在Python 3中安装模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆