python pypi_如何将开源Python软件包发布到PyPI

本文档是一份教程,介绍了如何将Python软件包上传到Python包索引(PyPI)。内容包括创建一个名为Real Python Reader的简单Python包,探讨包的结构、配置、版本控制和文档编写,以及使用Flit、Poetry等工具进行打包和发布。通过这个过程,读者将学习到如何将Python项目发布到PyPI,以便他人安装和使用。
摘要由CSDN通过智能技术生成

python pypi

Python is famous for coming with batteries included. Sophisticated capabilities are available in the standard library. You can find modules for working with sockets, parsing CSV, JSON, and XML files, and working with files and file paths.

Python因附带电池而闻名。 标准库中提供了复杂的功能。 您可以找到用于处理套接字 ,解析CSVJSONXML文件以及处理文件文件路径的模块

However great the packages included with Python are, there are many fantastic projects available outside the standard library. These are most often hosted at the Python Packaging Index (PyPI), historically known as the Cheese Shop. At PyPI, you can find everything from Hello World to advanced deep learning libraries.

尽管Python附带的软件包很棒,但标准库之外还有许多出色的项目可用。 这些最常托管在Python打包索引 (PyPI)(历史上被称为Cheese Shop)上 。 在PyPI,您可以找到从Hello World到高级深度学习库的所有内容

In this tutorial, you’ll cover how to upload your own package to PyPI. While getting your project published is easier than it used to be, there are still a few steps involved.

在本教程中,您将介绍如何将自己的包上传到PyPI 。 尽管发布项目比以前要容易,但仍涉及一些步骤。

You’ll learn how to:

您将学习如何:

  • Prepare your Python package for publication
  • Think about versioning
  • Upload your package to PyPI
  • 准备要发布的Python包
  • 考虑版本控制
  • 将您的包上传到PyPI

Throughout this tutorial, we’ll use a simple example project: a reader package that can be used to read Real Python tutorials. The first section introduces this project.

在整个教程中,我们将使用一个简单的示例项目:一个reader包,可用于阅读Real Python教程。 第一部分介绍此项目。

Free Bonus: Click here to get access to a chapter from Python Tricks: The Book that shows you Python’s best practices with simple examples you can apply instantly to write more beautiful + Pythonic code.

免费红利: 单击此处可访问Python技巧的一章:该书通过简单的示例向您展示了Python的最佳实践,您可以立即应用这些示例编写更精美的Pythonic代码。

一个小的Python包 (A Small Python Package)

This section will describe a small Python package that we’ll use as an example that can be published to PyPI. If you already have a package that you want to publish, feel free to skim this section and join up again at the beginning of the next section.

本节将描述一个小的Python包,我们将使用它作为示例来发布到PyPI。 如果您已经有要发布的软件包,请随意浏览本节,然后在下一节开头再次加入。

The package that we’ll use is called reader and is an application that can be used to download and read Real Python articles. If you want to follow along, you can get the full source code from our GitHub repository.

我们将使用的软件包称为reader ,它是一个可用于下载和阅读Real Python文章的应用程序。 如果您想继续,可以从我们的GitHub存储库中获取完整的源代码。

Note: The source code as shown and explained below is a simplified, but fully functional, version of the Real Python feed reader. Compared to the package published on PyPI and GitHub, this version lacks some error handling and extra options.

注意 :如下所示和说明的源代码是Real Python供稿阅读器的简化版本,但功能齐全。 与在PyPIGitHub上发布的软件包相比,此版本缺少一些错误处理和其他选项。

First, have a look at the directory structure of reader. The package lives completely inside a directory that is also named reader:

首先,看一下reader的目录结构。 该软件包完全位于一个也称为reader的目录中:

reader/
│
├── reader/
│   ├── config.txt
│   ├── feed.py
│   ├── __init__.py
│   ├── __main__.py
│   └── viewer.py
│
├── tests/
│   ├── test_feed.py
│   └── test_viewer.py
│
├── MANIFEST.in
├── README.md
└── setup.py
reader/
│
├── reader/
│   ├── config.txt
│   ├── feed.py
│   ├── __init__.py
│   ├── __main__.py
│   └── viewer.py
│
├── tests/
│   ├── test_feed.py
│   └── test_viewer.py
│
├── MANIFEST.in
├── README.md
└── setup.py

The source code of the package is in a reader subdirectory together with a configuration file. There are a few tests in a separate subdirectory. The tests will not be covered here, but you can find them in the GitHub repository. To learn more about testing, see Anthony Shaw’s great tutorial on Getting Started With Testing in Python.

软件包的源代码与配置文件一起位于reader子目录中。 在单独的子目录中有一些测试。 这些测试不会在这里讨论,但是您可以在GitHub存储库中找到它们。 要了解有关测试的更多信息,请参阅Anthony Shaw的精彩教程,《 Python测试入门》

If you’re working with your own package, you may use a different structure or have other files in your package directory. Our Python Application Layouts reference discusses several different options. The instructions in this guide will work independently of the layout you use.

如果您使用自己的软件包,则可以使用其他结构或在软件​​包目录中包含其他文件。 我们的Python应用程序布局参考中讨论了几种不同的选项。 本指南中的说明将独立于您使用的布局工作。

In the rest of this section, you’ll see how the reader package works. In the next section, you’ll get a closer look at the special files, including setup.py, README.md, and MANIFEST.in, that are needed to publish your package.

在本节的其余部分,您将看到reader包的工作方式。 在下一部分中 ,您将仔细研究发布包所需的特殊文件,包括setup.pyREADME.mdMANIFEST.in

使用Real Python Reader (Using the Real Python Reader)

reader is a very basic web feed reader that can download the latest Real Python articles from the Real Python feed.

reader是一个非常基本的Web feed阅读器,可以从Real Python feed中下载最新的Real Python文章。

Here is an example of using the reader to get the list of the latest articles:

这是使用阅读器获取最新文章列表的示例:

Notice that each article is numbered. To read one particular article, you use the same command but include the number of the article as well. For instance, to read How to Publish an Open-Source Python Package to PyPI, you add 0 to the command:

请注意,每篇文章都有编号。 要阅读一篇特定的文章,请使用相同的命令,但也要包括文章的编号。 例如,要阅读如何将开源Python程序包发布到PyPI ,可以在命令中添加0

 $ python -m reader $ python -m reader 0
0
# How to Publish an Open-Source Python Package to PyPI

# How to Publish an Open-Source Python Package to PyPI

Python is famous for coming with batteries included. Sophisticated
Python is famous for coming with batteries included. Sophisticated
capabilities are available in the standard library. You can find modules
capabilities are available in the standard library. You can find modules
for working with sockets, parsing CSV, JSON, and XML files, and
for working with sockets, parsing CSV, JSON, and XML files, and
working with files and file paths.

working with files and file paths.

However great the packages included with Python are, there are many
However great the packages included with Python are, there are many
fantastic projects available outside the standard library. These are
fantastic projects available outside the standard library. These are
most often hosted at the Python Packaging Index (PyPI), historically
most often hosted at the Python Packaging Index (PyPI), historically
known as the Cheese Shop. At PyPI, you can find everything from Hello
known as the Cheese Shop. At PyPI, you can find everything from Hello
World to advanced deep learning libraries.

World to advanced deep learning libraries.

[... The full text of the article ...]
[... The full text of the article ...]

This prints the full article to the console using the Markdown text format.

这将使用Markdown文本格式将完整的文章打印到控制台。

Note: python -m is used to run a library module or package instead of a script. If you run a package, the contents of the file __main__.py will be executed. See Different Ways of Calling a Package for more info.

注意: python -m用于运行库模块或包,而不是脚本 。 如果运行软件包,则将执行文件__main__.py的内容。 有关更多信息,请参见调用包的其他方式。

By changing the article number, you can read any of the available articles.

通过更改文章编号,您可以阅读任何可用的文章。

快速查看代码 (A Quick Look at the Code)

The details of how reader works are not important for the purpose of this tutorial. However, if you are interested in seeing the implementation, you can expand the sections below. The package consists of five files:

对于本教程而言, reader如何工作的细节并不重要。 但是,如果您对实现有兴趣,可以扩展以下部分。 该软件包包含五个文件:

config.txt is a configuration file used to specify the URL of the feed of Real Python tutorials. It’s a text file that can be read by the configparser standard library:

config.txt是一个配置文件,用于指定Real Python教程提要的URL。 这是一个文本文件,可以由configparser标准库读取:

In general, such a config file contains key-value pairs separated into sections. This particular file contains only one section (feed) and one key (url).

通常,这样的配置文件包含分成部分的键/值对。 此特定文件仅包含一个部分( feed )和一个键( url )。

Note: A configuration file is probably overkill for this simple package. We include it here for demonstration purposes.

注意:对于这个简单的程序包,配置文件可能是多余的。 我们将其包括在此处以进行演示。

The first source code file we’ll look at is __main__.py. The double underscores indicate that this file has a special meaning in Python. Indeed, when running a package as a script with -m as above, Python executes the contents of the __main__.py file.

我们将要看的第一个源代码文件是__main__.py 。 双下划线表示该文件在Python中具有特殊含义。 确实,当使用如上所述的-m作为脚本运行程序包时,Python执行__main__.py文件的内容。

In other words, __main__.py acts as the entry point of our program and takes care of the main flow, calling other parts as needed:

换句话说, __main__.py充当程序的入口点并负责主流程,并根据需要调用其他部分:

 # __main__.py

# __main__.py

from from configparser configparser import import ConfigParser
ConfigParser
from from importlib importlib import import resources  resources  # Python 3.7+
# Python 3.7+
import import sys

sys

from from reader reader import import feed
feed
from from reader reader import import viewer

viewer

def def mainmain ():
    ():
    """Read the Real Python article feed"""
    """Read the Real Python article feed"""
    # Read URL of the Real Python feed from config file
    # Read URL of the Real Python feed from config file
    cfg cfg = = ConfigParserConfigParser ()
    ()
    cfgcfg .. read_stringread_string (( resourcesresources .. read_textread_text (( "reader""reader" , , "config.txt""config.txt" ))
    ))
    url url = = cfgcfg .. getget (( "feed""feed" , , "url""url" )

    )

    # If an article ID is given, show the article
    # If an article ID is given, show the article
    if if lenlen (( syssys .. argvargv ) ) > > 11 :
        :
        article article = = feedfeed .. get_articleget_article (( urlurl , , syssys .. argvargv [[ 11 ])
        ])
        viewerviewer .. showshow (( articlearticle )

    )

    # If no ID is given, show a list of all articles
    # If no ID is given, show a list of all articles
    elseelse :
        :
        site site = = feedfeed .. get_siteget_site (( urlurl )
        )
        titles titles = = feedfeed .. get_titlesget_titles (( urlurl )
        )
        viewerviewer .. show_listshow_list (( sitesite , , titlestitles )

)

if if __name__ __name__ == == "__main__""__main__" :
    :
    mainmain ()
()

Notice that main() is called on the last line. If we do not call main(), then our program would not do anything. As you saw earlier, the program can either list all articles or print one specific article. This is handled by the if-else inside main().

注意, main()在最后一行被调​​用。 如果我们不调用main() ,那么我们的程序将什么也不做。 如您先前所见,该程序可以列出所有文章或打印一篇特定文章。 这由main()if-else处理。

To read the URL to the feed from the configuration file, we use configparser and importlib.resources. The latter is used to import non-code (or resource) files from a package without having to worry about the full file path. It is especially helpful when publishing packages to PyPI where resource files might end up inside binary archives.

要从配置文件读取提要的URL,我们使用configparserimportlib.resources 。 后者用于从包中导入非代码(或资源)文件,而不必担心完整的文件路径。 在将程序包发布到PyPI时特别有用,因为资源文件可能最终存储在二进制存档中。

importlib.resources became a part of the standard library in Python 3.7. If you are using an older version of Python, you can use importlib_resources instead. This is a backport compatible with Python 2.7, and 3.4 and above. importlib_resources can be installed from PyPI:

importlib.resources成为Python 3.7中标准库的一部分。 如果您使用的是旧版本的Python,则可以改用importlib_resources 。 这是与Python 2.7和3.4及更高版本兼容的反向端口。 可以从PyPI安装importlib_resources

See Barry Warzaw’s presentation at PyCon 2018 for more information.

有关更多信息,请参见Barry Warzaw在PyCon 2018上的演讲

The next file is __init__.py. Again, the double underscores in the filename tell us that this is a special file. __init__.py represents the root of your package. It should usually be kept quite simple, but it’s a good place to put package constants, documentation, and so on:

下一个文件是__init__.py 。 同样,文件名中的双下划线告诉我们这是一个特殊文件。 __init__.py表示软件包的根目录。 它通常应该保持非常简单,但是这是放置包常量,文档等的好地方:

 # __init__.py

# __init__.py

# Version of the realpython-reader package
# Version of the realpython-reader package
__version__ __version__ = = "1.0.0"
"1.0.0"

The special variable __version__ is a convention in Python for adding version numbers to your package. It was introduced in PEP 396. We’ll talk more about versioning later.

特殊变量__version__是Python中的一种约定,用于在软件包中添加版本号。 它是在PEP 396中引入的。 稍后我们将详细讨论版本控制

Variables defined in __init__.py become available as variables in the package namespace:

__init__.py定义的变量可以在包名称空间中用作变量:

>>>
>>>
 >>>  import reader
>>>  reader . __version__
'1.0.0'

You should define the __version__ variable in your own packages as well.

您还应该在自己的包中定义__version__变量。

Looking at __main__.py, you’ll see that two modules, feed and viewer, are imported and used to read from the feed and show the results. These modules do most of the actual work.

查看__main__.py ,您将看到导入了两个模块feedviewer ,并使用它们读取了feed并显示了结果。 这些模块完成大部分实际工作。

First consider feed.py. This file contains functions for reading from a web feed and parsing the result. Luckily there are already great libraries available to do this. feed.py depends on two modules that are already available on PyPI: feedparser and html2text.

首先考虑feed.py 该文件包含用于从Web订阅源读取和解析结果的功能。 幸运的是,已经有很棒的库可以做到这一点。 feed.py取决于PyPI上已经可用的两个模块: feedparserhtml2text

feed.py contains several functions. We’ll discuss them one at a time.

feed.py包含几个函数。 我们将一次讨论他们。

To avoid reading from the web feed more than necessary, we first create a function that remembers the feed the first time it’s read:

为了避免从Web提要中读取过多信息,我们首先创建一个函数,以在第一次读取提要时记住该提要:

feedparser.parse() reads a feed from the web and returns it in a structure that looks like a dictionary. To avoid downloading the feed more than once, it’s stored in _CACHED_FEEDS and reused for later calls to _feed(). Both _CACHED_FEEDS and _feed() are prefixed by an underscore to indicate that they are support objects not meant to be used directly.

feedparser.parse()从Web读取提要,并以类似于字典的结构将其返回。 为了避免多次下载提要,该提要存储在_CACHED_FEEDS并在以后对_feed()调用中重新使用。 _CACHED_FEEDS_feed()均以下划线作为前缀,以表示它们是不直接使用的支持对象。

We can get some basic information about the feed by looking in the .feed metadata. The following function picks out the title and link to the web site containing the feed:

通过查看.feed元数据,我们可以获得有关feed的一些基本信息。 以下功能挑选标题并链接到包含提要的网站:

 def def get_siteget_site (( urlurl ):
    ):
    """Get name and link to web site of the feed"""
    """Get name and link to web site of the feed"""
    info info = = _feed_feed (( urlurl )) .. feed
    feed
    return return ff "" {info.title}{info.title}  ( ( {info.link}{info.link} )"
)"

In addition to .title and .link, attributes like .subtitle, .updated, and .id are also available.

除了.title.link ,属性,如.subtitle.updated.id还可以

The articles available in the feed can be found inside the .entries list. Article titles can be found with a list comprehension:

供稿中可用的文章可以在.entries列表中找到。 可以通过列表理解找到文章标题:

.entries lists the articles in the feed sorted chronologically, so that the newest article is .entries[0].

.entries列出了提要中按时间顺序排序的文章,因此最新的文章是.entries[0]

In order to get the contents of one article, we use its index in the .entries list as an article ID:

为了获取一篇文章的内容,我们将其在.entries列表中的索引用作文章ID:

 def def get_articleget_article (( urlurl , , article_idarticle_id ):
    ):
    """Get article from feed with the given ID"""
    """Get article from feed with the given ID"""
    articles articles = = _feed_feed (( urlurl )) .. entries
    entries
    article article = = articlesarticles [[ intint (( article_idarticle_id )]
    )]
    html html = = articlearticle .. contentcontent [[ 00 ]] .. value
    value
    text text = = html2texthtml2text .. html2texthtml2text (( htmlhtml )
    )
    return return ff "# "#  {article.title}{article.title} nnnn {text}{text} "
"

After picking the correct article out of the .entries list, we find the text of the article as HTML on line 28. Next, html2text does a decent job of translating the HTML into much more readable text. As the HTML doesn’t contain the title of the article, the title is added before returning.

.entries列表中选择正确的文章之后,我们在第28行找到该文章的文本为HTML。接下来, html2texthtml2text不错,将HTML转换为可读性更高的文本。 由于HTML不包含文章标题,因此标题会在返回之前添加。

The final module is viewer.py. At the moment, it consists of two very simple functions. In practice, we could have used print() directly in __main__.py instead of calling viewer functions. However, having the functionality split off makes it easier to replace it later with something more advanced. Maybe we could add a GUI interface in a later version?

最后一个模块是viewer.py 。 目前,它包含两个非常简单的功能。 实际上,我们可以直接在__main__.py使用print()而不是调用viewer函数。 但是,将功能拆分开可以使以后更轻松地用更高级的功能替换它。 也许我们可以在更高版本中添加GUI界面?

viewer.py contains two functions:

viewer.py包含两个功能:

show() simply prints one article to the console, while show_list() prints a list of titles. The latter also creates article IDs that are used when choosing to read one particular article.

show()仅将一篇文章打印到控制台,而show_list()打印标题列表。 后者还会创建在选择阅读一篇特定文章时使用的文章ID。

调用包裹的不同方式 (Different Ways of Calling a Package)

One challenge when your projects grow in complexity is communicating to the user how to use your project. Since the package consists of four different source code files, how does the user know which file to call to run reader?

当您的项目变得越来越复杂时,挑战之一就是与用户交流如何使用您的项目。 由于该软件包包含四个不同的源代码文件,因此用户如何知道要调用哪个文件来运行reader

The python interpreter program has an -m option that allows you to specify a module name instead of a file name. For instance, if you have a script called hello.py, the following two commands are equivalent:

python解释器程序具有-m选项,该选项允许您指定模块名称而不是文件名称。 例如,如果您有一个名为hello.py的脚本,则以下两个命令是等效的:

 $ python hello.py
$ python hello.py
Hi there!

Hi there!

$ python -m hello
$ python -m hello
Hi there!
Hi there!

One advantage of the latter is that it allows you to call modules that are built into Python as well. One example is calling antigravity:

后者的一个优点是,它还允许您调用Python内置的模块。 一个例子叫antigravity

Another advantage of using -m is that it works for packages as well as modules. As you saw earlier, you can call the reader package with -m:

使用-m另一个优点是,它既可用于包-m用于模块。 如前所述,您可以使用-m调用reader包:

 $ python -m reader
$ python -m reader
[...]
[...]

Since reader is a package, the name only refers to a directory. How does Python decide which code inside that directory to run? It looks for a file named __main__.py. If such a file exists, it is executed. If __main__.py does not exist, then an error message is printed:

由于reader是程序包,因此名称仅指目录。 Python如何确定该目录中要运行的代码? 它寻找一个名为__main__.py的文件。 如果存在这样的文件,则将其执行。 如果__main__.py不存在,则会显示一条错误消息:

In this example, you see that the math standard library has not defined a __main__.py file.

在此示例中,您会看到math标准库尚未定义__main__.py文件。

If you are creating a package that is supposed to be executed, you should include a __main__.py file. Later, you’ll see how you can also create entry points to your package that will behave like regular programs.

如果要创建应该执行的程序包,则应包括__main__.py文件。 稍后 ,您将看到如何也可以为程序包创建入口点,这些入口点的行为类似于常规程序。

准备打包发布 (Preparing Your Package for Publication)

Now you’ve got a package you want to publish, or maybe you copied our package. Which steps are necessary before you can upload the package to PyPI?

现在,您已经有了要发布的软件包,或者您已经复制了我们的软件包 。 将包上传到PyPI之前,需要执行哪些步骤?

命名包裹 (Naming Your Package)

The first—and possibly the hardest—step is to come up with a good name for your package. All packages on PyPI need to have unique names. With more than 150,000 packages already on PyPI, chances are that your favorite name is already taken.

第一步(可能也是最难的一步)是为您的包装命名。 PyPI上的所有软件包都必须具有唯一的名称。 在PyPI上已经有超过150,000个软件包,很可能已经采用了您喜欢的名称。

You might need to brainstorm and do some research to find the perfect name. Use the PyPI search to check if a name is already taken. The name that you come up with will be visible on PyPI.

您可能需要集思广益,并做一些研究才能找到完美的名字。 使用PyPI搜索来检查名称是否已被使用。 您想出的名称将在PyPI上可见。

To make the reader package easier to find on PyPI, we give it a more descriptive name and call it realpython-reader. The same name will be used to install the package using pip:

为了使reader包更易于在PyPI上找到,我们给它一个更具描述性的名称,并将其realpython-reader 。 使用相同的名称通过pip安装软件包:

 $ pip install realpython-reader
$ pip install realpython-reader

Even though we use realpython-reader as the PyPI name, the package is still called reader when it’s imported:

即使我们使用realpython-reader作为PyPI名称,但在导入时该包仍称为reader

>>>
>>>
 >>>  import reader
>>>  help ( reader )

>>>  from reader import feed
>>>  feed . get_titles ()
['How to Publish an Open-Source Python Package to PyPI', ...]

As you see, you can use different names for your package on PyPI and when importing. However, if you use the same name or very similar names, then it will be easier for your users.

如您所见,您可以在PyPI上和导入时为包使用不同的名称。 但是,如果您使用相同或非常相似的名称,则对您的用户来说将更加容易。

配置程序包 (Configuring Your Package)

In order for your package to be uploaded to PyPI, you need to provide some basic information about it. This information is typically provided in the form of a setup.py file. There are initiatives that try to simplify this collection of information. At the moment though, setup.py is the only fully supported way of providing information about your package.

为了将您的包上传到PyPI,您需要提供有关它的一些基本信息。 通常以setup.py文件的形式提供此信息。 有一些举措试图简化这种信息收集。 目前, setup.py是提供有关软件包信息的唯一完全受支持的方法。

The setup.py file should be placed in the top folder of your package. A fairly minimal setup.py for reader looks like this:

setup.py文件应放在包的顶部文件夹中。 对于reader最小的setup.py看起来像这样:

We will only cover some of the options available in setuptools here. The documentation does a good job of going into all the detail.

我们仅在此处介绍setuptools可用的一些选项。 该文档很好地完成了所有细节。

The parameters that are 100% necessary in the call to setup() are the following:

调用setup() 100%必需的参数如下:

  • name: the name of your package as it will appear on PyPI
  • version: the current version of your package
  • packages: the packages and subpackages containing your source code
  • name将在PyPI上显示的软件包名称
  • version您的软件包的当前版本
  • packages包含您的源代码的包和子包

We will talk more about versions later. The packages parameter takes a list of packages. In our example, there is only one package: reader.

稍后我们将详细讨论版本packages参数采用软件包列表。 在我们的示例中,只有一个包: reader

You also need to specify any subpackages. In more complicated projects, there might be many packages to list. To simplify this job, setuptools includes find_packages(), which does a good job of discovering all your subpackages. You could have used find_packages() in the reader project as follows:

您还需要指定任何子包。 在更复杂的项目中,可能会列出许多软件包。 为了简化这项工作, setuptools包含find_packages() ,它可以很好地发现所有子包。 您本可以在reader项目中使用find_packages() ,如下所示:

 from from setuptools setuptools import import find_packagesfind_packages , , setup

setup

setupsetup (
    (
    ...
    ...
    packagespackages == find_packagesfind_packages (( excludeexclude == (( "tests""tests" ,)),
    ,)),
    ...
...
)
)

While only name, version, and packages are required, your package becomes much easier to find on PyPI if you add some more information. Have a look at the realpython-reader page on PyPI and compare the information with setup.py above. All the information comes from setup.py and README.md.

尽管只需要nameversionpackages ,但是如果您添加更多信息,则可以在PyPI上更轻松地找到您的软件包。 看看PyPI上的realpython-reader页面 ,并将信息与上面的setup.py进行比较。 所有信息都来自setup.pyREADME.md

有关PyPI中的<code> realpython-reader </ code>软件包的信息

The last two parameters to setup() deserve special mention:

需要特别提及setup()的最后两个参数:

  • install_requires is used to list any dependencies your package has to third party libraries. The reader depends on feedparser and html2text, so they should be listed here.

  • entry_points is used to create scripts that call a function within your package. In our example, we create a new script realpython that calls main() within the reader/__main__.py file.

  • install_requires用于列出您的软件包对第三方库的任何依赖关系。 reader依赖feedparserhtml2text ,因此应在此处列出。

  • entry_points用于创建调用程序包中的函数的脚本。 在我们的示例中,我们创建了一个新脚本realpython ,该脚本在reader/__main__.py文件中调用main()

For another example of a typical setup file, see Kenneth Reitz’s setup.py repository on GitHub.

有关典型安装文件的另一个示例,请参阅GitHub上的 Kenneth Reitz的setup.py存储库

记录包裹 (Documenting Your Package)

Before releasing your package to the world, you should add some documentation. Depending on your package, the documentation can be as small as a simple README file, or as big as a full web page with tutorials, example galleries, and an API reference.

在将软件包发布给世人之前,您应该添加一些文档 。 根据您的软件包,文档的大小可以像一个简单的README文件一样小,也可以像一个完整的带有教程,示例画廊和API参考的网页一样大。

At a minimum, you should include a README file with your project. A good README should quickly describe your project, as well as tell your users how to install and use your package. Typically, you want to include your README as the long_description argument to setup(). This will display your README on PyPI.

至少,您应该在项目中包含README文件。 一个好的README应该快速描述您的项目,并告诉您的用户如何安装和使用您的软件包。 通常,您希望将README作为setup()long_description参数包含在内。 这将在PyPI上显示您的README文件。

Traditionally, PyPI has used reStructuredText for package documentation. However, since March 2018 Markdown has also been supported.

传统上,PyPI使用reStructuredText来包装文档。 但是,自2018年3月以来, Markdown 也得到了支持

Outside of PyPI, Markdown is more widely supported than reStructuredText. If you don’t need any of the special features of reStructuredText, you’ll be better off keeping your README in Markdown. Note that you should use the setup() parameter long_description_content_type to tell PyPI which format you are using. Valid values are text/markdown, text/x-rst, and text/plain.

在PyPI之外,Markdown比reStructuredText得到更广泛的支持。 如果您不需要reStructuredText的任何特殊功能,最好将自己的README保留在Markdown中。 请注意,您应该使用setup()参数long_description_content_type告诉PyPI您正在使用哪种格式 。 有效值为text/markdowntext/x-rsttext/plain

For bigger projects, you might want to offer more documentation than can reasonably fit in a single file. In that case, you can use sites like GitHub or Read the Docs, and link to the documentation using the url parameter. In the setup.py example above, url is used to link to the reader GitHub repository.

对于较大的项目,您可能需要提供比合理地容纳在单个文件中更多的文档。 在这种情况下,您可以使用GitHubRead Docs等网站,并使用url参数链接到文档。 在上面的setup.py示例中, url用于链接到reader GitHub存储库

对软件包进行版本控制 (Versioning Your Package)

Your package needs to have a version, and PyPI will only let you do one upload of a particular version for a package. In other words, if you want to update your package on PyPI, you need to increase the version number first. This is a good thing, as it guarantees reproducibility: two systems with the same version of a package should behave the same.

您的软件包需要有一个版本,而PyPI仅允许您为一个软件包上传一个特定版本。 换句话说,如果要在PyPI上更新软件包,则需要先增加版本号。 这是一件好事,因为它保证了可重复性:具有相同版本软件包的两个系统应具有相同的行为。

There are many different schemes that can be used for your version number. For Python projects, PEP 440 gives some recommendations. However, in order to be flexible, that PEP is complicated. For a simple project, stick with a simple versioning scheme.

版本号可以使用许多不同的方案 。 对于Python项目, PEP 440提供了一些建议。 但是,为了灵活起见,PEP很复杂。 对于简单的项目,请坚持使用简单的版本控制方案。

Semantic versioning is a good default scheme to use. The version number is given as three numerical components, for instance 0.1.2. The components are called MAJOR, MINOR, and PATCH, and there are simple rules about when to increment each component:

语义版本控制是一个很好的默认方案。 版本号由三个数字部分给出,例如0.1.2 。 这些组件称为MAJOR,MINOR和PATCH,并且有一些有关何时增加每个组件的简单规则:

  • Increment the MAJOR version when you make incompatible API changes.
  • Increment the MINOR version when you add functionality in a backwards-compatible manner.
  • Increment the PATCH version when you make backwards-compatible bug fixes. (Source)
  • 进行不兼容的API更改时,请增加MAJOR版本。
  • 当您以向后兼容的方式添加功能时,请增加MINOR版本。
  • 进行向后兼容的错误修复时,请增加PATCH版本。 ( 来源

You may need to specify the version in different files inside your project. In the reader project, we specified the version both in setup.py and in reader/__init__.py. To make sure the version numbers are kept consistent, you can use a tool called Bumpversion.

您可能需要在项目内的其他文件中指定版本。 在reader项目中,我们在setup.pyreader/__init__.py都指定了版本。 为了确保版本号保持一致,可以使用一个名为Bumpversion的工具。

You can install Bumpversion from PyPI:

您可以从PyPI安装Bumpversion:

To increment the MINOR version of reader, you would do something like this:

要增加reader的MINOR版本,您可以执行以下操作:

 $ bumpversion --current-version $ bumpversion --current-version 1.0.0 minor setup.py reader/__init__.py
1 .0.0 minor setup.py reader/__init__.py

This would change the version number from 1.0.0 to 1.1.0 in both setup.py and reader/__init__.py. To simplify the command, you can also give most of the information in a configuration file. See the Bumpversion documentation for details.

这会将setup.pyreader/__init__.py的版本号从1.0.0更改为1.1.0 。 为了简化命令,您还可以在配置文件中提供大多数信息。 有关详细信息,请参见Bumpversion文档

将文件添加到包中 (Adding Files to Your Package)

Sometimes, you’ll have files inside your package that are not source code files. Examples include data files, binaries, documentation, and—as we have in this project—configuration files.

有时,您的程序包中会包含不是源代码文件的文件。 示例包括数据文件,二进制文件,文档以及(如我们在本项目中一样的)配置文件。

To tell setup() to include such files, you use a manifest file. For many projects, you don’t need to worry about the manifest, as setup() creates one that includes all code files as well as README files.

要告诉setup()包含此类文件,请使用清单文件。 对于许多项目,您无需担心清单,因为setup()创建的清单包括所有代码文件和README文件。

If you need to change the manifest, you create a manifest template which must be named MANIFEST.in. This file specifies rules for what to include and exclude:

如果需要更改清单,请创建一个清单模板,该模板必须命名为MANIFEST.in 。 该文件为要包含和排除的内容指定了规则:

This example will include all .txt files in the reader directory, which in effect is the configuration file. See the documentation for a list of available rules.

此示例将在reader目录中包括所有.txt文件,该文件实际上是配置文件。 请参阅文档以获取可用规则列表。

In addition to creating MANIFEST.in, you also need to tell setup() to copy these non-code files. This is done by setting the include_package_data argument to True:

除了创建MANIFEST.in ,还需要告诉setup() 复制这些非代码文件 。 这是通过将include_package_data参数设置为True

 setupsetup (
    (
    ...
    ...
    include_package_datainclude_package_data == TrueTrue ,
    ,
    ...
...
)
)

The include_package_data argument controls whether non-code files are copied when your package is installed.

include_package_data参数控制在安装软件包时是否复制非代码文件。

发布到PyPI (Publishing to PyPI)

Your package is finally ready to meet the world outside your computer! In this section, you’ll see how to actually upload your package to PyPI.

您的包裹终于准备好与您的计算机外部的世界接触! 在本节中,您将看到如何实际将软件包上传到PyPI。

If you don’t already have an account on PyPI, now is the time to create one: register your account on PyPI. While you’re at it, you should also register an account on TestPyPI. TestPyPI is very useful, as you can try all the steps of publishing a package without any consequences if you mess up.

如果您尚未在PyPI上拥有帐户,那么现在该创建一个帐户了:在PyPI上注册您的帐户 。 在使用它时,还应该在TestPyPI上注册一个帐户 。 TestPyPI非常有用,因为如果您搞砸了,可以尝试发布软件包的所有步骤,而不会造成任何后果。

To upload your package to PyPI, you’ll use a tool called Twine. You can install Twine using Pip as usual:

要将软件包上传到PyPI,您将使用一个名为Twine的工具。 您可以照常使用Pip安装Twine:

Using Twine is quite simple, and you will soon see how to use it to check and publish your package.

使用Twine非常简单,您将很快看到如何使用它来检查和发布软件包。

建立你的包裹 (Building Your Package)

Packages on PyPI are not distributed as plain source code. Instead, they are wrapped into distribution packages. The most common formats for distribution packages are source archives and Python wheels.

PyPI上的软件包不作为纯源代码分发。 而是将它们包装到分发包中。 分发程序包最常见的格式是源档案和Python wheel

A source archive consists of your source code and any supporting files wrapped into one tar file. Similarly, a wheel is essentially a zip archive containing your code. In contrast to the source archive, the wheel includes any extensions ready to use.

源归档文件由您的源代码和包装在一个tar文件中的所有支持文件组成。 同样,轮子实际上是包含您的代码的zip存档。 与源归档文件相反,该转盘包括任何可以使用的扩展名。

To create a source archive and a wheel for your package, you can run the following command:

要为您的包裹创建一个源档案和一个转轮,您可以运行以下命令:

 $ python setup.py sdist bdist_wheel
$ python setup.py sdist bdist_wheel

This will create two files in a newly created dist directory, a source archive and a wheel:

这将在一个新创建的dist目录中创建两个文件,一个源归档文件和一个wheel:

Note: On Windows, the source archive will be a .zip file by default. You can choose the format of the source archive with the --format command line option.

注意:在Windows上,默认情况下,源归档文件将是.zip文件。 您可以使用--format命令行选项选择源归档的格式。

You might wonder how setup.py knows what to do with the sdist and bdist_wheel arguments. If you look back to how setup.py was implemented, there is no mention of sdist, bdist_wheel, or any other command line arguments.

您可能想知道setup.py如何知道如何处理sdistbdist_wheel参数。 如果您回顾一下setup.py实现方式,则没有提到sdistbdist_wheel或任何其他命令行参数。

All the command line arguments are instead implemented in the upstream distutils standard library. You can list all available arguments by adding the --help-commands option:

相反,所有命令行参数都在上游distutils标准库中实现 。 您可以通过添加--help-commands选项列出所有可用的参数:

 $ python setup.py --help-commands
$ python setup.py --help-commands
Standard commands:
Standard commands:
  build             build everything needed to install
  build             build everything needed to install
  build_py          "build" pure Python modules (copy to build directory)
  build_py          "build" pure Python modules (copy to build directory)
  build_ext         build C/C++ and Cython extensions (compile/link to build directory)
  build_ext         build C/C++ and Cython extensions (compile/link to build directory)
< ... many more commands ...>
< ... many more commands ...>

For information about one particular command, you can do something like python setup.py sdist --help.

有关一个特定命令的信息,您可以执行python setup.py sdist --help

测试您的包裹 (Testing Your Package)

First, you should check that the newly built distribution packages contain the files you expect. On Linux and macOS, you should be able to list the contents of the tar source archive as follows:

首先,您应该检查新建的分发包中是否包含所需的文件。 在Linux和macOS上,您应该能够如下列出tar源归档文件的内容:

On Windows, you can use a utility like 7-zip to look inside the corresponding zip file.

在Windows上,您可以使用7-zip之类的实用程序在相应的zip文件中查找。

You should see all your source code listed, as well as a few new files that have been created containing information you provided in setup.py. In particular, make sure that all subpackages and supporting files are included.

您应该看到列出的所有源代码,以及已经创建的一些新文件,其中包含setup.py提供的信息。 特别是,请确保包括所有子包和支持文件。

You can also have a look inside the wheel by unzipping it as if it were a zip file. However, if your source archive contains the files you expect, the wheel should be fine as well.

您也可以通过解压缩轮子来查看轮子内部,就好像它是一个zip文件一样。 但是,如果您的源归档文件包含您期望的文件,则转轮也应该很好。

Newer versions of Twine (1.12.0 and above) can also check that your package description will render properly on PyPI. You can run twine check on the files created in dist:

较新版本的Twine( 1.12.0及更高版本)还可以检查您的软件包说明将在PyPI上正确呈现。 您可以对dist创建的文件运行twine check

 $ twine check dist/*
$ twine check dist/*
Checking distribution dist/realpython_reader-1.0.0-py3-none-any.whl: Passed
Checking distribution dist/realpython_reader-1.0.0-py3-none-any.whl: Passed
Checking distribution dist/realpython-reader-1.0.0.tar.gz: Passed
Checking distribution dist/realpython-reader-1.0.0.tar.gz: Passed

While it won’t catch all problems you might run into, it will for instance let you know if you are using the wrong content type.

虽然它不能解决您可能遇到的所有问题,但是例如,它将使您知道使用的内容类型是否错误。

上载您的包裹 (Uploading Your Package)

Now you’re ready to actually upload your package to PyPI. For this, you’ll again use the Twine tool, telling it to upload the distribution packages you have built. First, you should upload to TestPyPI to make sure everything works as expected:

现在,您可以将包实际上传到PyPI了。 为此,您将再次使用“ Twine”工具,告诉它上载已构建的分发程序包。 首先,您应该上传到TestPyPI以确保一切正常。

Twine will ask you for your username and password.

Twine会询问您您的用户名和密码。

Note: If you’ve followed the tutorial using the reader package as an example, the previous command will probably fail with a message saying you are not allowed to upload to the realpython-reader project.

注意:如果您以reader包为例学习了本教程,则先前的命令可能会失败,并显示一条消息,提示您不允许上传到realpython-reader项目。

You can change the name in setup.py to something unique, for example test-your-username. Then build the project again and upload the newly built files to TestPyPI.

您可以将setup.pyname更改为唯一的name ,例如test-your-username 。 然后再次构建项目,并将新生成的文件上传到TestPyPI。

If the upload succeeds, you can quickly head over to TestPyPI, scroll down, and look at your project being proudly displayed among the new releases! Click on your package and make sure everything looks okay.

如果上传成功,您可以快速转到TestPyPI ,向下滚动并查看在新版本中自豪地显示的项目! 单击您的包裹,并确保一切正常。

If you have been following along using the reader package, the tutorial ends here! While you can play with TestPyPI as much as you want, you shouldn’t upload dummy packages to PyPI just for testing.

如果您一直在使用reader包,那么教程将在此处结束! 尽管您可以随意使用TestPyPI,但不应将虚拟软件包上传到PyPI只是为了进行测试。

However, if you have your own package to publish, then the moment has finally arrived! With all the preparations taken care of, this final step is short:

但是,如果您要发布自己的程序包,那么此刻终于来临! 完成所有准备工作后,最后一步很短:

 $ twine upload dist/*
$ twine upload dist/*

Provide your username and password when requested. That’s it!

根据要求提供您的用户名和密码。 而已!

Head over to PyPI and look up your package. You can find it either by searching, by looking at the Your projects page, or by going directly to the URL of your project: pypi.org/project/your-package-name/.

前往PyPI并查找您的包裹。 您可以通过搜索 ,查看“ 您的项目”页面或直接转到项目的URL: pypi.org/project/your-package-name/来找到它。

Congratulations! Your package is published on PyPI!

恭喜你! 您的软件包已在PyPI上发布!

pip install您的软件包 (pip install Your Package)

Take a moment to bask in the blue glow of the PyPI web page and (of course) brag to your friends.

花点时间沐浴在PyPI网页的蓝色光芒中,(当然)向您的朋友吹牛。

Then open up a terminal again. There is one more great pay off!

然后再次打开一个终端。 还有一个巨大的回报!

With your package uploaded to PyPI, you can install it with pip as well:

将您的软件包上传到PyPI后,您还可以使用pip进行安装:

Replace your-package-name with the name you chose for your package. For instance, to install the reader package, you would do the following:

your-package-name选择的名称替换your-package-name 。 例如,要安装reader软件包,您可以执行以下操作:

 $ pip install realpython-reader
$ pip install realpython-reader

Seeing your own code installed by pip is a wonderful feeling!

看到pip安装的自己的代码真是太好了!

其他有用的工具 (Other Useful Tools)

Before wrapping up, there are a few other tools that are useful to know about when creating and publishing Python packages.

在总结之前,还有一些其他的工具对于创建和发布Python包非常有用。

虚拟环境 (Virtual Environments)

In this guide, we haven’t talked about virtual environments. Virtual environments are very useful when working with different projects, each with their own differing requirements and dependencies.

在本指南中,我们没有讨论虚拟环境。 当使用不同的项目时,虚拟环境非常有用,每个项目都有各自不同的要求和依赖性。

See the following guides for more information:

有关更多信息,请参见以下指南:

In particular, it’s useful to test your package inside a minimal virtual environment to make sure you’re including all necessary dependencies in your setup.py file.

特别是,在最小的虚拟环境中测试软件包很有用,以确保将所有必要的依赖项包括在setup.py文件中。

切碎机 (Cookiecutter)

One great way to get started with your project is to use Cookiecutter. It sets up your project by asking you a few questions based on a template. Many different templates are available.

开始使用项目的一种好方法是使用Cookiecutter 。 它通过基于模板询问几个问题来设置您的项目。 可以使用许多不同的模板

First, make sure you have Cookiecutter installed on your system. You can install it from PyPI:

首先,请确保您的系统上安装了Cookiecutter。 您可以从PyPI安装它:

As an example, we’ll use the pypackage-minimal template. To use a template, give Cookiecutter a link to the template:

作为示例,我们将使用pypackage-minimal模板。 要使用模板,请给Cookiecutter指向模板的链接:

 $ cookiecutter https://github.com/kragniz/cookiecutter-pypackage-minimal
$ cookiecutter https://github.com/kragniz/cookiecutter-pypackage-minimal
author_name [Louis Taylor]: Real Python
author_name [Louis Taylor]: Real Python
author_email [louis@kragniz.eu]: office@realpython.com
author_email [louis@kragniz.eu]: office@realpython.com
package_name [cookiecutter_pypackage_minimal]: realpython-reader
package_name [cookiecutter_pypackage_minimal]: realpython-reader
package_version [0.1.0]:
package_version [0.1.0]:
package_description [...]: Read Real Python tutorials
package_description [...]: Read Real Python tutorials
package_url [...]: https://github.com/realpython/reader
package_url [...]: https://github.com/realpython/reader
readme_pypi_badge [True]:
readme_pypi_badge [True]:
readme_travis_badge [True]: False
readme_travis_badge [True]: False
readme_travis_url [...]:
readme_travis_url [...]:

After you have answered a series of questions, Cookiecutter sets up your project. In this example, the template created the following files and directories:

在回答了一系列问题之后,Cookiecutter设置您的项目。 在此示例中,模板创建了以下文件和目录:

Cookiecutter’s documentation is extensive and includes a long list of available cookiecutters, as well as tutorials on how to create your own template.

Cookiecutter的文档内容广泛,包括一长串可用的cookiecutter,以及有关如何创建自己的模板的教程。

掠过 (Flit)

The history of packaging in Python is quite messy. One common criticism is that using an executable file like setup.py for configuration information is not ideal.

Python打包的历史非常混乱。 一种普遍的批评是,使用setup.py类的可执行文件获取配置信息并不理想。

PEP 518 defines an alternative: using a file called pyproject.toml instead. The TOML format is a simple configuration file format:

PEP 518定义了一种替代方案:改为使用一个名为pyproject.toml的文件。 TOML格式是一种简单的配置文件格式:

[…] it is human-usable (unlike JSON), it is flexible enough (unlike configparser), stems from a standard (also unlike configparser), and it is not overly complex (unlike YAML). (Source)

[…]它是人类可使用的(与JSON不同),它足够灵活(与configparser不同),源于标准(也与configparser不同),并且也不太复杂(与YAML不同)。 ( 来源

While PEP 518 is already a few years old, the pyproject.toml configuration file is not yet fully supported in the standard tools.

尽管PEP 518已经使用了几年,但标准工具尚不完全支持pyproject.toml配置文件。

However, there are a few new tools that can publish to PyPI based on pyproject.toml. One such tool is Flit, a great little project that makes it easy to publish simple Python packages. Flit doesn’t support advanced packages like those creating C extensions.

但是,有一些新工具可以基于pyproject.toml发布到PyPI。 这样的工具就是Flit ,这是一个很棒的小项目,可以轻松发布简单的Python包。 Flit不支持高级软件包,例如创建C扩展的软件包。

You can pip install flit, and then start using it as follows:

您可以pip install flit ,然后按如下所示开始使用它:

 $ flit init
$ flit init
Module name [reader]:
Module name [reader]:
Author []: Real Python
Author []: Real Python
Author email []: office@realpython.com
Author email []: office@realpython.com
Home page []: https://github.com/realpython/reader
Home page []: https://github.com/realpython/reader
Choose a license (see http://choosealicense.com/ for more info)
Choose a license (see http://choosealicense.com/ for more info)
1. MIT - simple and permissive
1. MIT - simple and permissive
2. Apache - explicitly grants patent rights
2. Apache - explicitly grants patent rights
3. GPL - ensures that code based on this is shared with the same terms
3. GPL - ensures that code based on this is shared with the same terms
4. Skip - choose a license later
4. Skip - choose a license later
Enter 1-4 [1]:

Enter 1-4 [1]:

Written pyproject.toml; edit that file to add optional extra info.
Written pyproject.toml; edit that file to add optional extra info.

The flit init command will create a pyproject.toml file based on the answers you give to a few questions. You might need to edit this file slightly before using it. For the reader project, the pyproject.toml file for Flit ends up looking as follows:

flit init命令将根据您对几个问题的回答创建一个pyproject.toml文件。 使用该文件之前,您可能需要稍微对其进行编辑。 对于reader项目,Flit的pyproject.toml文件最终看起来如下:

You should recognize most of the items from our original setup.py. One thing to note though is that version and description are missing. This is not a mistake. Flit actually figures these out itself by using __version__ and the docstring defined in the __init__.py file. Flit’s documentation explains everything about the pyproject.toml file.

您应该从我们的原始setup.py识别出大多数项目。 不过要注意的一件事是缺少versiondescription 。 这不是一个错误。 Flit实际上通过使用__version____init__.py文件中定义的文档字符串来自行__version__这些内容。 Flit的文档解释了有关pyproject.toml文件的所有内容。

Flit can build your package and even publish it to PyPI. To build your package, simply do the following:

Flit可以构建您的包,甚至将其发布到PyPI。 要构建您的软件包,只需执行以下操作:

 $ flit build
$ flit build

This creates a source archive and a wheel, exactly like python setup.py sdist bdist_wheel did earlier. To upload your package to PyPI, you can use Twine as earlier. However, you can also use Flit directly:

这将创建一个源存档和一个转轮,就像python setup.py sdist bdist_wheel之前所做的一样。 要将软件包上传到PyPI,您可以像以前一样使用Twine。 但是,您也可以直接使用Flit:

The publish command will build your package if necessary, and then upload the files to PyPI, prompting you for your username and password if necessary.

必要时, publish命令将构建您的软件包,然后将文件上传到PyPI,并在必要时提示您输入用户名和密码。

To see Flit in action, have a look at the 2 minute lightning talk from EuroSciPy 2017. The Flit documentation is a great resource for more information. Brett Cannon’s tutorial on packaging up your Python code for PyPI includes a section about Flit.

要了解Flit的实际应用,请查看EuroSciPy 2017的2分钟闪电演讲 。Flit 文档是获取更多信息的绝佳资源。 Brett Cannon的打包PyPI的Python代码教程包括有关Flit的部分。

诗歌 (Poetry)

Poetry is another tool that can be used to build and upload your package. It’s quite similar to Flit, especially for the things we’re looking at here.

诗歌是可以用来构建和上传软件包的另一种工具。 它与Flit非常相似,尤其是对于我们在这里要看的东西。

Before you use Poetry, you need to install it. It’s possible to pip install poetry as well. However, the author recommends that you use a custom installation script to avoid potential dependency conflicts. See the documentation for installation instructions.

使用诗歌之前,需要先安装它。 也可以pip install poetry 。 但是, 作者建议您使用自定义安装脚本来避免潜在的依赖冲突。 请参阅文档以获取安装说明。

With Poetry installed, you start using it with an init command:

安装了Poetry之后,您可以通过init命令开始使用它:

 $ poetry init

$ poetry init

This command will guide you through creating your pyproject.toml config.

This command will guide you through creating your pyproject.toml config.

Package name [code]: realpython-reader
Package name [code]: realpython-reader
Version [0.1.0]: 1.0.0
Version [0.1.0]: 1.0.0
Description []: Read the latest Real Python tutorials
Description []: Read the latest Real Python tutorials
...
...

This will create a pyproject.toml file based on your answers to questions about your package. Unfortunately, the actual specifications inside the pyproject.toml differ between Flit and Poetry. For Poetry, the pyproject.toml file ends up looking like the following:

这将根据您对软件包问题的回答创建一个pyproject.toml文件。 不幸的是,Flit和Poetry之间的pyproject.toml内部实际规范有所不同。 对于Poetry, pyproject.toml文件最终如下所示:

Again, you should recognize all these items from the earlier discussion of setup.py. One thing to note is that Poetry will automatically add classifiers based on the license and the version of Python you specify. Poetry also requires you to be explicit about versions of your dependencies. In fact, dependency management is one of the strong points of Poetry.

同样,您应该从setup.py的先前讨论中认识所有这些项目。 需要注意的一件事是,Poetry会根据许可证和您指定的Python版本自动添加分类器。 诗歌还要求您明确说明依赖项的版本。 实际上,依赖性管理是诗歌的长处之一。

Just like Flit, Poetry can build and upload packages to PyPI. The build command creates a source archive and a wheel:

就像Flit一样,Poetry可以构建软件包并将其上传到PyPI。 build命令创建一个源档案和一个轮子:

 $ poetry build
$ poetry build

This will create the two usual files in the dist subdirectory, which you can upload using Twine as earlier. You can also use Poetry to publish to PyPI:

这将在dist子目录中创建两个常用文件,您可以像以前一样使用Twine上载这些文件。 您还可以使用“诗歌”发布到PyPI:

This will upload your package to PyPI. In addition to building and publishing, Poetry can help you earlier in the process. Similar to Cookiecutter, Poetry can help you start a new project with the new command. It also supports working with virtual environments. See Poetry’s documentation for all the details.

这会将您的包上传到PyPI。 除了构建和发布之外,Poetry还可以在此过程的早期为您提供帮助。 类似于Cookiecutter,Poetry可以帮助您使用new命令启动新项目。 它还支持使用虚拟环境。 有关所有详细信息,请参见诗歌的文档

Apart from the slightly different configuration files, Flit and Poetry work very similarly. Poetry is broader in scope as it also aims to help with dependency management, while Flit has been around a little longer. Andrew Pinkham’s article Python’s New Package Landscape covers both Flit and Poetry. Poetry was one of the topics at the special 100th episode of the Python Bytes podcast.

除了略有不同的配置文件外,Flit和Poetry的工作方式非常相似。 诗歌的范围更广,因为它还旨在帮助进行依存关系管理,而弗利特(Flit)的历史已经更长了。 安德鲁·平克汉姆(Andrew Pinkham)的文章《 Python的新包装格局》涵盖了Flit和Poetry。 诗歌是Python Bytes播客第100集的特别主题之一。

结论 (Conclusion)

You now know how to prepare your project and upload it to PyPI, so that it can be installed and used by other people. While there are a few steps you need to go through, seeing your own package on PyPI is a great pay off. Having others find your project useful is even better!

现在,您知道了如何准备项目并将其上传到PyPI,以便其他人可以安装和使用它。 尽管您需要完成一些步骤,但是在PyPI上看到自己的软件包是很有意义的。 让其他人发现您的项目很有用!

In this tutorial, you’ve seen the steps necessary to publish your own package:

在本教程中,您已经看到了发布自己的包所必需的步骤:

  • Find a good name for your package
  • Configure your package using setup.py
  • Build your package
  • Upload your package to PyPI
  • 为您的包裹找一个好名字
  • 使用setup.py配置您的软件包
  • 建立你的包裹
  • 将您的包上传到PyPI

In addition, you’ve also seen a few new tools for publishing packages that use the new pyproject.toml configuration file to simplify the process.

此外,您还看到了一些用于发布程序包的新工具,这些工具使用新的pyproject.toml配置文件来简化此过程。

If you still have questions, feel free to reach out in the comments section below. Also, the Python Packaging Authority has a lot of information with more detail than we covered here.

如果您仍然有疑问,请随时访问下面的评论部分。 另外, Python打包授权机构提供了许多信息,比我们在此介绍的信息更加详细。

翻译自: https://www.pybloggers.com/2018/11/how-to-publish-an-open-source-python-package-to-pypi/

python pypi

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值