search
HomeBackend DevelopmentPython TutorialDetailed explanation of how to package and publish Python modules

Preface

Yesterday I packaged my VASP file processing library and uploaded it to PyPI. Now you can install VASPy directly through pip and easy_install (at the same time, children who use VASP to do computational chemistry are welcome to add stars) and get involved),

VASPy’s GotHub address: https://github.com/PytLab/VASPy
VASPy’s PyPI address: https://pypi.python.org/pypi/vaspy/

Since my memory is really bad and I am afraid that I will forget it after a long time, I will use my VASPy program as an example to summarize the packaging and uploading of python.

VASPy package file structure

First write and paste the entire file structure of the VASPy package. The following content will be explained using this example:

VASPy/
├── LICENSE
├── MANIFEST
├── MANIFEST.in
├── README.rst
├── requirements.txt
├── scripts
│  ├── change_incar_parameters.py
│  ├── create_inputs.py
│  └── ...
├── setup.cfg
├── setup.py
├── tests
│  ├── incar_test.py
│  ├── __init__.py
│  ├── oszicar_test.py
│  ├── outcar_test.py
│  ├── testdata
│  │  ├── CONTCAR
│  │  ├── DOS_SUM
│  │  ├── ELFCAR
│  │  └── ...
│  └── ...
└── vaspy
  ├── __init__.py
  ├── iter.py
  ├── matstudio.py
  └── ...
  
4 directories, 54 files

Packaging and installation chapter Third-party package tools

Here we need to use tools such as setuptools and pip to package, publish and install our own packages. If we need to build a wheel, we also need to install the wheel module. If the python version >=2.7.9 or >=3.4, setuptools and pip are already installed, and you may need to update to the latest version

pip install -U pip setuptools

You can use package management tools, such as

yum install pip
sudo apt-get install pip

to install through the get-pip.py script. If it is detected that wheel and setuptools are not installed, they will be automatically installed

python get-pip.py

I won’t go into details about the specific tool installation and introduction. You can refer to the requirements for installing packages

The functions of different files in the package

setup.py

This file is the most important file for packaging the entire project. It provides two main functions:

setup() function. The parameters of this function specify how to configure your own project.
Command line tools, including packaging, testing, publishing, etc. You can view it through the following command;

python setup.py --help-commands

setup.cfg

This file contains some default parameters during build, such as building bdist_wheel The --universal parameter

[bdist_wheel]
universal=1

will be used by default every time when packaging. The effect is similar:

python setup.py bdist_wheel --universal

README.rst

I originally wrote this in markdown. After packaging and publishing it to PyPI, I found that PyPI did not support markdown rendering. The page was really confusing, so I re-written it using the syntax of reStrutruedText. Wrote it again. After all, markup language syntax can basically be learned in seconds. If it is really not possible, just find a template and draw the gourd.
The syntax rules of reStructureText can refer to the official document: Quick reStructuredText

In fact, another way is to use pandoc to convert markdown into rst format. A trouble-free way is to use the pyandoc module to automatically convert when publishing. .
For specific methods, please refer to: Use Markdown README's in Python modules

MANIFEST.in

This file tells setuptools when packaging that additional files need to be packaged, such as the units in my VASPy I will use this file to include the test data file for the test. Of course, README and LICENSE can also be packaged together through it.
The following is the content of my own MANIFEST.in:

include README.rst
include requirements.txt
include LICENSE
recursive-include scripts *
recursive-include tests *

For specific grammar rules, please refer to: The MANIFEST.in template

vaspy/

This folder It is the package where the vaspy source code is located.

tests/

This folder is also a sub-package and contains unit test scripts. In order to use python setup.py test for unit testing, __init__.pys is specially added to make it A bag.

Parameters of setup()

Here I only introduce a few parameters I use. For the specific use of other parameters, please refer to: https://docs.python.org/3/distutils/setupscript .html

name

versions = "vaspy"

is the name of the entire project. This name and version number will be used after packaging.

version

from vaspy import __version__
version = __version__

description

is a short description of the project, usually just one sentence, and will be displayed at the bottom of the name on pypi.

long_description

is a long description, which is equivalent to a concise description of the project. If this string is in rst format, PyPI will automatically render it into HTML for display. The contents in README.rst can be read directly here.

url

The link to the package, usually a link on GitHub or a link to readthedocs.

packages

A list of subpackages that need to be included. Setuptools provides find_packages() to help us find packages in the root path. This function distutil does not have.

setup_requires

This parameter defines other dependencies (the most basic) required for VASPy installation and smooth operation. These dependencies will be installed when using pip to install.
For the difference between this parameter and requirements.txt, please refer to: install_requires vs Requirements files

classifier

This parameter provides a series of classifications, which will be put into different categories on PyPI The items are categorized in the directory.
Reference for specific category names and rules: https://pypi.python.org/pypi?%3Aaction=list_classifiers

test_suite

This parameter can help us use

python setup.py test

to run unit tests, you no longer need to write a separate script such as run_tests.py to run unit tests.
Official explanation of this parameter:

A string naming a unittest.TestCase subclass (or a package or module containing one or more of them, or a method of such a subclass), or naming a function that can be called with no arguments and returns a unittest.TestSuite. If the named suite is a module, and the module has an additional_tests() function, it is called and the results are added to the tests to be run. If the named suite is a package, any submodules and subpackages are recursively added to the overall test suite.

也就是说这个参数可以接受多种类型的参数:

接收unittest.TestCase子类,我们可以讲所有单元测试写入一个测试用例中,然后import进来,再传你给test_suite
接收函数对象,此函数对象没有任何参数,且返回一个unittest.TestSuite.这样我们就可以单独写一个函数,将多个测试用例合并成一个suite然后返回,然后再将函数import进来传给test_suite。

模块和包名称,我就是使用这种方式,之前自己的测试都是分开的多个脚本,这样我添加一个__init__.py就可以将其变成一个包,将包名传给test_suite,setuptools就会神奇的将此包下的所有测试全部跑一边,这样我以后再加测试脚本的时候直接就添加新的脚本就好了,其他的都不需要改动了。

运行效果:

zjshao@SHAO-PC:/mnt/d/Dropbox/Code/CentOS_code/VASPy$ python setup.py test
running test
running egg_info
creating vaspy.egg-info
writing vaspy.egg-info/PKG-INFO
writing top-level names to vaspy.egg-info/top_level.txt
writing dependency_links to vaspy.egg-info/dependency_links.txt
writing manifest file 'vaspy.egg-info/SOURCES.txt'
reading manifest file 'vaspy.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'vaspy.egg-info/SOURCES.txt'
running build_ext
test_compare (tests.incar_test.InCarTest)
Make sure we can compare two InCar objects correctly. ... ok
test_eq (tests.incar_test.InCarTest)
Test __eq__() function. ... ok
...
此处省略若干输出
  
----------------------------------------------------------------------
Ran 22 tests in 3.574s
  
OK

发布自己的python包

1. 首先先去PyPI注册帐号

2. 配置~/.pypirc如下:

[distutils]
index-servers =
  pypi
  pypitest
  
[pypi]
username:ShaoZhengjiang
password:mypassword
  
[pypitest]
username:ShaoZhengjiang
password:mypassword

3. 然后注册并上传自己的包到测试服务器

pypi提供了一个测试服务器,我们可以在这个测试服务器上做测试。

python setup.py register -r pypitest

然后

python setup.py sdist upload -r pypitest

若没有问题我们应该不会得到任何错误。

4. 上传至PyPI

若上面的测试成功,我们就可以按照相同的步骤将包注册并上传。

python setup.py register -r pypi
python setup.py sdist upload -r pypi

Ok,之后我们就可以在PyPI(https://pypi.python.org/pypi/vaspy/)上看到我们自己的包了。

更多打包发布Python模块的方法详解相关文章请关注PHP中文网!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python vs. C  : Memory Management and ControlPython vs. C : Memory Management and ControlApr 19, 2025 am 12:17 AM

Python and C have significant differences in memory management and control. 1. Python uses automatic memory management, based on reference counting and garbage collection, simplifying the work of programmers. 2.C requires manual management of memory, providing more control but increasing complexity and error risk. Which language to choose should be based on project requirements and team technology stack.

Python for Scientific Computing: A Detailed LookPython for Scientific Computing: A Detailed LookApr 19, 2025 am 12:15 AM

Python's applications in scientific computing include data analysis, machine learning, numerical simulation and visualization. 1.Numpy provides efficient multi-dimensional arrays and mathematical functions. 2. SciPy extends Numpy functionality and provides optimization and linear algebra tools. 3. Pandas is used for data processing and analysis. 4.Matplotlib is used to generate various graphs and visual results.

Python and C  : Finding the Right ToolPython and C : Finding the Right ToolApr 19, 2025 am 12:04 AM

Whether to choose Python or C depends on project requirements: 1) Python is suitable for rapid development, data science, and scripting because of its concise syntax and rich libraries; 2) C is suitable for scenarios that require high performance and underlying control, such as system programming and game development, because of its compilation and manual memory management.

Python for Data Science and Machine LearningPython for Data Science and Machine LearningApr 19, 2025 am 12:02 AM

Python is widely used in data science and machine learning, mainly relying on its simplicity and a powerful library ecosystem. 1) Pandas is used for data processing and analysis, 2) Numpy provides efficient numerical calculations, and 3) Scikit-learn is used for machine learning model construction and optimization, these libraries make Python an ideal tool for data science and machine learning.

Learning Python: Is 2 Hours of Daily Study Sufficient?Learning Python: Is 2 Hours of Daily Study Sufficient?Apr 18, 2025 am 12:22 AM

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.

Python for Web Development: Key ApplicationsPython for Web Development: Key ApplicationsApr 18, 2025 am 12:20 AM

Key applications of Python in web development include the use of Django and Flask frameworks, API development, data analysis and visualization, machine learning and AI, and performance optimization. 1. Django and Flask framework: Django is suitable for rapid development of complex applications, and Flask is suitable for small or highly customized projects. 2. API development: Use Flask or DjangoRESTFramework to build RESTfulAPI. 3. Data analysis and visualization: Use Python to process data and display it through the web interface. 4. Machine Learning and AI: Python is used to build intelligent web applications. 5. Performance optimization: optimized through asynchronous programming, caching and code

Python vs. C  : Exploring Performance and EfficiencyPython vs. C : Exploring Performance and EfficiencyApr 18, 2025 am 12:20 AM

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.