python开源包下载_如何开源您的第一个python包

python开源包下载

为什么要使用Python包? (Why a Python package?)

Python is an intuitive general-purpose language with an easy-to-understand syntax. It makes prototyping, web development, data science and more, much easier than in any other programming languages. This is due to its large and supportive community and its numerous software libraries.

Python是一种直观的通用语言,具有易于理解的语法。 与其他任何编程语言相比,它使原型制作,Web开发,数据科学等工作变得更加容易。 这是由于其庞大的支持社区以及众多的软件库

You have ever found yourself writing mutliple times the same lines of code in different projects? Or perhaps, you have already written some useful library that you would like to make available to others? Or maybe, you are just interested in Python Packaging or in contributing to the Python community?

您是否曾经发现自己在不同项目中以相同的代码行编写多倍次数? 或者,也许您已经编写了一些有用的库,想将其提供给其他人? 或者,也许您只是对Python打包感兴趣或对Python社区做出了贡献?

In this article we will create a small package and then upload it to Python Package Index (PyPi) so that anyone can download and use your code as a software library using pip install .

在本文中,我们将创建一个小程序包,然后将其上传到Python程序包索引(PyPi),以便任何人都可以使用pip install下载并将您的代码用作软件库。

When I built my first package in Python, I found the process somewhat tedious. That motivated me to write this article which will put you through the basics of how to build a Python package and share it with the rest of the world.

当我使用Python构建第一个程序包时,我发现该过程有些乏味。 这促使我写这篇文章,它将带您了解如何构建Python程序包与世界其他地方共享的基础知识。

要求 (Requirements)

If you have a GitHub account and Python installed you can jump ahead to the Project Overview.

如果您拥有GitHub帐户并安装了Python,则可以跳至“项目概述”。

Git存储库 (Git Repository)

To be part of the open-source community, you must publicly host a project on a version control hosting service. The most common choice is to use a Git repository host which holds a virtual storage of your project. It allows you to coordinate work among programmers and save versions of your code, which you can access when needed. The most used hosting service is GitHub. If you don’t have an account yet, the first step is to create one right here.

要成为开源社区的一部分,您必须在版本控制托管服务上公开托管项目。 最常见的选择是使用Git存储库主机,该主机可保存项目的虚拟存储。 它允许您协调程序员之间的工作并保存代码版本,您可以在需要时访问它们。 最常用的托管服务是GitHub 。 如果您还没有帐户,那么第一步就是在此处创建一个帐户。

Python (Python)

We will use Python 3. Any version from Python 3.5 can be used for the project. If you don’t have Python, you can download it from python.org’s download page. I will be using Python 3.7 on Windows, yet it doesn’t matter what version or OS you have for this project. If you are new to Python, I could suggest you to go through some exercises of this tutorial.

我们将使用Python3。该项目可以使用Python 3.5中的任何版本。 如果您没有Python,可以从python.org的下载页面下载 。 我将在Windows上使用Python 3.7,但是该项目使用的版本或操作系统都没有关系。 如果您不熟悉Python,建议您阅读本教程的一些练习。

集成开发环境 (IDE)

An Integrated Development Environment (IDE) is a source code editor that provides you with debugging and automation tools. It doesn’t matter what code editor or IDE you use as long as you like it. I will personnaly use a light yet powerful code editor called Visual Studio Code.

集成开发环境(IDE)是源代码编辑器,可为您提供调试和自动化工具。 您可以使用任何代码编辑器或IDE都没有关系。 我将个人使用一个轻便但功能强大的代码编辑器,称为Visual Studio Code

Ready to code!
Ready to deep dive! Photo by Max Duzij on Unsplash
准备深潜! Max DuzijUnsplash拍摄的照片

项目概况 (Project Overview)

Let’s now build a simple package dealing with prime numbers. If you already have some code you would like to use instead, feel free to skip this part after structuring your code to resemble the project.

现在,让我们构建一个处理素数的简单程序包。 如果您已经有一些代码要使用,则可以在将代码结构化为类似于项目之后随意跳过此部分。

The first thing you have to do is find a suitable name for your library. Since our library deals with prime numbers, I went for primelib .

您要做的第一件事是为您的库找到一个合适的名称。 由于我们的图书馆处理质数,因此我选择了primelib

Below is how the project structure will look like. You can either create the files alongside me or directly download the whole repository on GitHub.

下面是项目结构的样子。 您可以与我一起创建文件,也可以直接在GitHub上下载整个存储库

primelib/
primelib/
__init__.py
prime_numbers.py
tests/
test_prime.py
.gitignore
LICENSE
README.md
setup.py

This may look like a lot of files but don’t worry, we are going to make and explain them one after the other.

这可能看起来像很多文件,但请放心,我们将逐一进行解释。

逐步构建项目 (Build The Project Step by Step)

启动并克隆GitHub存储库 (Initiate and Clone the GitHub Repository)

The first thing to do is to initiate a repository in GitHub. Sign in on GitHub and click the green “New button. You should come upon a page whose title is “Create a new repository”. Fill in the blanks like below while opting for a README file, a Python .gitignore file, and an MIT License. When you are ready, click “Create repository”.

首先要做的是在GitHub中启动存储库。 在GitHub上登录,然后点击绿色的“ 新建 按钮。 您应该进入一个标题为“ Create a new repository ”的页面。 选择README文件,Python .gitignore文件和MIT许可证时,请像下面那样填写空白。 准备就绪后,单击“ 创建存储库 ”。

Create a new repository on GitHub

Once you have your repository created on GitHub, you must clone it locally on your computer. For this you should have Git installed as well as a terminal on your machine. In Windows I recommend to use the new Windows Terminal although you can definitely go for the Command Prompt. Open a terminal and make sure git is correctly installed by running git --version . Then go wherever you would like to store your project locally using cd . Finally you can run the git clone https://github.com/YOUR-USERNAME/primelib.git . The link is provided when clicking on the green “Code” button.

在GitHub上创建存储库后,必须在计算机上本地克隆它。 为此,您应该在机器上安装Git以及一个终端。 在Windows中,我建议您使用新的Windows Terminal,尽管您绝对可以使用命令提示符。 打开终端,并通过运行git --version确保正确安装了git --version 。 然后使用cd转到要在本地存储项目的任何地方。 最后,您可以运行git clone https://github.com/YOUR-USERNAME/primelib.git 。 单击绿色的“ 代码 ”按钮时,将提供链接。

You should now have your project copied on your computer. Feel free to open the primelib folder in your favorite code editor. You should have the following structure.

现在,您应该将项目复制到计算机上。 primelib在您喜欢的代码编辑器中打开primelib文件夹。 您应该具有以下结构。

.gitignore
LICENSE
README.md
  • The .gitignore file enables you to ignore some files while tracking and uploading your code to the repository.

    .gitignore文件使您可以在跟踪代码并将其上传到存储库时忽略某些文件。
  • The LICENSE file is just a .txt file containing the license for the project. You can find your needs here, although the MIT license is a good default choice for several projects.

    LICENSE文件只是一个.txt文件,其中包含项目的许可证。 您可以在这里找到您的需求,尽管MIT许可证是几个项目的不错的默认选择。

  • The README.md file is a Markdown-formatted file containing a description of the project. You can write documentation for the modules and functions that your library will provide.

    README.md文件是Markdown格式的文件,其中包含项目的描述。 您可以编写库将提供的模块和功能的文档。
Image for post
We all love Python. Photo by Chris Ried on Unsplash
我们都喜欢Python。 克里斯·里德 ( Chris Ried)Unsplash

Python代码 (Python Code)

In the primelib/ folder, you can now add a new folder also called primelib that will contain all your code. In this new folder, create 2 Python files called prime_numbers.py and __init__.py (with two leading and two trailing underscores).

现在,您可以在primelib/文件夹中添加一个也称为primelib的新文件夹,其中将包含所有代码。 在这个新文件夹中,创建2个Python文件,分别称为prime_numbers.py__init__.py prime_numbers.py (两个下划线和两个下划线)。

primelib/
__init__.py
prime_numbers.py
.gitignore
LICENSE
README.md

Let’s start with prime_numbers.py which contains the Python code we will be using. You can just copy and paste this code into your prime_numbers.py file.

让我们从prime_numbers.py开始,其中包含我们将要使用的Python代码。 您可以仅将此代码复制并粘贴到您的prime_numbers.py文件中。

import math


def _divides(div, n):
    """
    returns True if and only if div divides n which is equivalent to
    n = k*div with k an integer.
    """
    return (n % div == 0)


def is_prime(n):
    """Function to evaluate whether an integer is a prime number.
    A prime number is defined as being greater than 1 and is not a product of
    two strictly smaller integers.

    Args: 
        n (int): integer to evaluate

    Returns: 
        bool: whether or not n is a prime number
        
    """
    if type(n) is not int or n <=1:
        # If smaller than 1 or not an integer, it is not a prime number
        return False
    # n is not a prime number if a divisor is found in between 2 and sqrt(n)  
    for div in range(2, math.floor(math.sqrt(n))+1):
        if _divides(div, n):
            return False
    return True

The Python code contains two functions:

Python代码包含两个函数:

  • _divides is a private function therefore starting with a leading underscore. It is used by the next function is_prime and returns True if and only if div divides n .

    _divides是一个私有函数,因此以下划线开头。 下一个函数is_prime使用它,并且仅当divn返回True

  • is_prime checks whether a number n has a divisor different than 1 and itself, it returns True if so.

    is_prime检查数字n的除数和它本身是否具有除数,如果是,则返回True

The __init__.py file is necessary to turn primelib into a package. It will be the file executed by your Python interpreter when running import primelib or from primelib import ... . To make your functionis_prime directly accessible from your library with the command: primelib.is_prime(n) , you must write the following in your __init__.py file:

__init__.py文件是将primelib转换为软件包所必需的。 当运行import primelibfrom primelib import ...时,它将是您的Python解释器执行的文件。 要使用命令primelib.is_prime(n)从库中直接访问is_prime函数,必须在__init__.py文件中编写以下内容:

from primelib.prime_numbers import is_prime

测验 (Tests)

Alright now is time to create some tests to make sure our functions work as expected. You can now create a tests folder within your project directory and add a test_prime.py file in it.

现在是时候创建一些测试以确保我们的功能按预期工作了。 现在,您可以在项目目录中创建一个tests文件夹,并在其中添加一个test_prime.py文件。

primelib/
__init__.py
prime_numbers.py
tests/
test_prime.py
.gitignore
LICENSE
README.md

You can simply copy the following tests.

您可以简单地复制以下测试。

from primelib import is_prime


def test_false():
    assert is_prime(10) is False


def test_true():
    assert is_prime(11) is True

Then you can use the Pytest library which is part of Python Standard Library, so it comes with Python, no need to install it. Pytest will automatically check your assert statements in any test_*.py file. In your terminal, you can just run the following command.

然后,您可以使用Python标准库中的Pytest ,因此它是Python附带的,无需安装。 Pytest会自动检查任何test_*.py 。py文件中的assert语句。 在您的终端中,您只需运行以下命令。

python -m pytest

You should now see your two tests passed with success. This means you are ready to build the package and share your library with the community.

现在,您应该看到两个测试成功通过。 这意味着您已准备好构建软件包并与社区共享您的库。

Image for post
Time to build your library. Photo by Matt Artz on Unsplash
是时候建立您的图书馆了。 Matt ArtzUnsplash拍摄的照片

建立图书馆 (Build the Library)

We are going to use three libraries setuptools , wheel and twine . Make sure they are available in your environment.

我们将使用三个库setuptoolswheeltwine 。 确保它们在您的环境中可用。

pip install --upgrade setuptools wheel twine

One last file is required to build the package. You must add a setup.py file at the root of your directory. This tells setuptools how to actually build the package. Let’s add this last file to obtain the final tree structure.

构建软件包需要最后一个文件。 您必须在目录的根目录下添加一个setup.py文件。 这告诉setuptools如何实际构建软件包。 让我们添加最后一个文件以获得最终的树结构。

primelib/
primelib/
__init__.py
prime_numbers.py
tests/
test_prime.py
.gitignore
LICENSE
README.md
setup.py

Here is the setup.py file. You can copy and paste it while replacing YOUR-USERNAME with your name to make the library name unique.

这是setup.py文件。 您可以复制并粘贴它,同时用您的名称替换YOUR-USERNAME以使库名称唯一。

from setuptools import setup, find_packages


with open("README.md", "r") as f:
    long_description = f.read()


setup(
    name="primelib-YOUR-USERNAME",
    version="0.0.1",
    author="YOUR NAME",
    author_email="YOU@EMAIL.COM",
    description="A small package to work with prime numbers",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/clement-bonnet/medium-first-package",
    packages=find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ]
)

The three mandatory parameters are name, version and packages. You can now build the library with the following.

这三个必填参数是名称版本软件包 。 您现在可以使用以下内容构建库。

python setup.py sdist bdist_wheel

This generates distribution archives in the dist/ directory. You can now install the library in your local environment doing python setup.py install . You can try to import primelib in a Python shell.

这将在dist/目录中生成分发存档。 现在,您可以通过python setup.py install在本地环境中安装该库。 您可以尝试在Python Shell中导入primelib

python
>>> import primelib
>>> primelib.is_prime(13)
True

在PyPi上上传 (Upload on PyPi)

Now that you have a working library, you can upload it on Python Package Index (PyPi) to share it with the Python community. For the purpose of this tutorial we are going to use TestPyPi, it works exactly like PyPi but it is made for testing packages in order to keep the real servers as clean as possible.

有了工作库后,您可以将其上传到Python包索引(PyPi)上,以与Python社区共享。 就本教程而言,我们将使用TestPyPi ,它的工作原理与PyPi完全相同,但是它是为测试软件包而设计的,目的是保持真实服务器尽可能的干净。

First you have to register an account on TestPypi and verify your email. You can finally upload your package as archives using the following line.

首先,您必须在TestPypi注册一个帐户并验证您的电子邮件。 最后,您可以使用以下行将软件包作为存档上传。

python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/*

That’s done! Your package is now available for the community. If it was uploaded on PyPi you would directly be able to install the package with pip install primelib , but since it’s on TestPyPi for now, you can install your package using the following:

大功告成! 您的软件包现在可供社区使用。 如果它是在PyPi上上传的, 可以直接使用pip install primelib来安装该软件包,但是由于它目前在TestPyPi上,因此可以使用以下方法安装软件包:

pip install --index-url https://test.pypi.org/simple/ primelib-YOUR-USERNAME

If you encounter any issues with packaging, please refer to the Python Packaging tutorial.

如果您在打包时遇到任何问题,请参阅Python打包教程

Your library is now available within your Python environment. I strongly recommend to use virtualenv to manage different environments.

您的库现在在Python环境中可用。 我强烈建议使用virtualenv来管理不同的环境。

结论 (Conclusion)

Congrats! You have learnt how to create a Python package to wrap some code of yours and then how to share your library with the community so that anyone can use your work.

恭喜! 您已经了解了如何创建Python包来包装您的一些代码,然后如何与社区共享您的库,以便任何人都可以使用您的作品。

I hope you now feel ready to contribute to the Python community and share your great code with the rest of the world!

希望您现在愿意为Python社区做出贡献,并与世界其他地方分享您的出色代码!

If you’re interested in going further, I would recommend these important, yet much more advanced topics:

如果您有兴趣进一步研究,我将推荐这些重要但更高级的主题:

  • Use virtual environments (virtualenv)

    使用虚拟环境( virtualenv )

  • Use a continuous integration tool (Travis CI)

    使用持续集成工具( Travis CI )

  • Versions management tools (SemVer)

    版本管理工具( SemVer )

  • Automate testings with nox (nox)

    使用Nox( nox )自动执行测试

  • Automate HTML documentation (Sphinx)

    自动化HTML文档( Sphinx )

翻译自: https://towardsdatascience.com/how-to-open-source-your-first-python-package-e717444e1da0

python开源包下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值