要自己写一个Python库并安装到Python库中调用,可以按照以下步骤进行:
1. 创建项目结构首先,创建一个项目目录,并在其中创建必要的文件和文件夹。例如:
mylib/ ├── mylib/ │ ├── __init__.py │ └── mymodule.py ├── tests/ │ └── test_mymodule.py ├── setup.py └── README.md2. 编写模块代码
在mylib/mymodule.py中编写你的模块代码。例如:
# mylib/mymodule.py
def greet(name):
return f"Hello, {name}!" 3. 初始化包在mylib/__init__.py中初始化你的包。例如:
# mylib/__init__.py from .mymodule import greet4. 编写setup.py
在项目根目录下创建setup.py文件,用于描述你的包。例如:
# setup.py
from setuptools import setup, find_packages
setup(
name='mylib',
version='0.1',
packages=find_packages(),
description='My custom Python library',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
author='Your Name',
author_email='your.email@example.com',
url='https://github.com/yourusername/mylib',
classifiers=[
'Programming Language :: Python :: 3',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
],
python_requires='>=3.6',
) 5. 编写测试在tests/test_mymodule.py中编写测试代码。例如:
# tests/test_mymodule.py
import unittest
from mylib.mymodule import greet
class TestMyModule(unittest.TestCase):
def test_greet(self):
self.assertEqual(greet("World"), "Hello, World!")
if __name__ == '__main__':
unittest.main() 6. 安装包在项目根目录下运行以下命令来安装你的包:
pip install .7. 调用库
安装完成后,你可以在其他Python脚本中调用你的库。例如:
# main.py
from mylib import greet
print(greet("World")) 8. 发布包(可选)如果你想将你的包发布到PyPI,可以按照以下步骤进行:
注册一个PyPI账号。在项目根目录下运行以下命令:python setup.py sdist bdist_wheel twine upload dist/*
这样,其他人就可以通过pip install mylib来安装你的包了。
通过以上步骤,你就可以自己写一个Python库并安装到Python库中调用了。
网友回复


