ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Python/프로젝트 패키징
    코딩/Python 2024. 3. 15. 19:00
    728x90

    Source: https://packaging.python.org/en/latest/tutorials/packaging-projects/

    Packaging Python Projects

    This tutorial walks you through how to package a simple Python project. It will show you how to add the necessary files and structure to create the package, how to build the package, and how to upload it to the Python Package Index (PyPI).

    이 튜토리얼에서는 간단한 Python 프로젝트를 패키징하는 방법을 안내한다. 패키지를 생성하는 데 필요한 파일과 구조를 추가하는 방법, 패키지를 빌드하는 방법, Python 패키지 인덱스(PyPI)에 업로드하는 방법을 보여준다.

    Tip

    If you have trouble running the commands in this tutorial, please copy the command and its output, then open an issue on the packaging-problems repository on GitHub. We’ll do our best to help you!

    이 튜토리얼의 명령을 실행하는 데 문제가 있는 경우 명령과 해당 출력을 복사한 다음 GitHub의 packaging-problems repository에서 문제를 공개한다. 최선을 다해 도울 것이다!

     

    Some of the commands require a newer version of pip, so start by making sure you have the latest version installed:

    일부 명령에는 최신 버전의 pip가 필요하므로 먼저 최신 버전이 설치되어 있는지 확인한다.

     

    Unix/macOS

    python3 -m pip install --upgrade pip

     

    Windows

    py -m pip install --upgrade pip

    A simple project

    This tutorial uses a simple project named example_package_YOUR_USERNAME_HERE. If your username is me, then the package would be example_package_me; this ensures that you have a unique package name that doesn’t conflict with packages uploaded by other people following this tutorial. We recommend following this tutorial as-is using this project, before packaging your own project.

    Create the following file structure locally:

    이 튜토리얼에서는 example_package_YOUR_USERNAME_HERE라는 간단한 프로젝트를 사용한다. 사용자 이름이 me라면 패키지는 example_package_me가 된다. 이렇게 하면 이 튜토리얼을 따르는 다른 사람들이 업로드한 패키지와 충돌하지 않는 고유한 패키지 이름을 갖게 된다. 자신의 프로젝트를 패키징하기 전에 이 프로젝트를 사용하여 이 튜토리얼을 있는 그대로 따르는 것이 좋다.

    로컬에서 다음 파일 구조를 만든다.

    packaging_tutorial/
    └── src/
        └── example_package_YOUR_USERNAME_HERE/
            ├── __init__.py
            └── example.py

     

    The directory containing the Python files should match the project name. This simplifies the configuration and is more obvious to users who install the package.

    __init__.py is recommended to import the directory as a regular package, even if as is our case for this tutorial that file is empty [1].

    example.py is an example of a module within the package that could contain the logic (functions, classes, constants, etc.) of your package. Open that file and enter the following content:

    Python 파일이 포함된 디렉터리는 프로젝트 이름과 일치해야 한다. 이는 구성을 단순화하고 패키지를 설치하는 사용자에게 더 명확하다.

    이 튜토리얼의 경우 파일이 비어 있더라도 __init__.py를 사용하여 디렉토리를 일반 패키지로 가져오는 것이 좋다[1].

    example.py는 패키지의 로직(함수, 클래스, 상수 등)을 포함할 수 있는 패키지 내 모듈의 예다. 해당 파일을 열고 다음 내용을 입력한다.

    def add_one(number):
        return number + 1

     

    If you are unfamiliar with Python’s modules and import packages, take a few minutes to read over the Python documentation for packages and modules.

    Once you create this structure, you’ll want to run all of the commands in this tutorial within the packaging_tutorial directory.

    Python의 모듈 및 가져오기 패키지에 익숙하지 않은 경우 몇 분 동안 패키지 및 모듈에 대한 Python 설명서를 읽는다.

    이 구조를 생성한 후에는 Packaging_tutorial 디렉터리 내에서 이 튜토리얼의 모든 명령을 실행하고 싶을 것이다.

    Creating the package files

    You will now add files that are used to prepare the project for distribution. When you’re done, the project structure will look like this:

    이제 배포용 프로젝트를 준비하는 데 사용되는 파일을 추가한다. 완료되면 프로젝트 구조는 다음과 같다.

    packaging_tutorial/
    ├── LICENSE
    ├── pyproject.toml
    ├── README.md
    ├── src/
    │   └── example_package_YOUR_USERNAME_HERE/
    │       ├── __init__.py
    │       └── example.py
    └── tests/

    Creating a test directory

    tests/ is a placeholder for test files. Leave it empty for now.

    tests/는 테스트 파일을 위한 자리 표시자이다. 지금은 비워 둔다.

    Choosing a build backend

    Tools like pip and build do not actually convert your sources into a distribution package (like a wheel); that job is performed by a build backend. The build backend determines how your project will specify its configuration, including metadata (information about the project, for example, the name and tags that are displayed on PyPI) and input files. Build backends have different levels of functionality, such as whether they support building extension modules, and you should choose one that suits your needs and preferences.

    You can choose from a number of backends; this tutorial uses Hatchling by default, but it will work identically with Setuptools, Flit, PDM, and others that support the [project] table for metadata.

    pip 및 build와 같은 도구는 실제로 소스를 배포 패키지(예: wheel)로 변환하지 않는다. 해당 작업은 빌드 백엔드에 의해 수행된다. 빌드 백엔드는 메타데이터(PyPI에 표시되는 이름 및 태그와 같은 프로젝트에 대한 정보) 및 입력 파일을 포함하여 프로젝트가 구성을 지정하는 방법을 결정한다. 빌드 백엔드는 확장 모듈의 구성을 지원하는지 여부 등 다양한 수준의 기능을 갖고 있으므로 필요와 선호도에 맞는 것을 선택해야 한다.

    다양한 백엔드 중에서 선택할 수 있다; 이 튜토리얼에서는 기본적으로 Hatchling을 사용하지만 Setuptools, Flit, PDM 및 메타데이터용 [project] 테이블을 지원하는 기타 제품과 동일하게 작동한다.

    Note

    Some build backends are part of larger tools that provide a command-line interface with additional features like project initialization and version management, as well as building, uploading, and installing packages. This tutorial uses single-purpose tools that work independently.

    일부 빌드 백엔드는 프로젝트 초기화, 버전 관리, 패키지 빌드, 업로드 및 설치와 같은 추가 기능이 포함된 명령줄 인터페이스를 제공하는 대규모 도구의 일부다. 이 튜토리얼에서는 독립적으로 작동하는 단일 목적 도구를 사용한다.

     

    The pyproject.toml tells build frontend tools like pip and build which backend to use for your project. Below are some examples for common build backends, but check your backend’s own documentation for more details.

    pyproject.toml은 pip와 같은 빌드 프론트엔드 도구와 프로젝트에 사용할 백엔드를 빌드하도록 알려준다. 다음은 일반적인 빌드 백엔드에 대한 몇 가지 예다. 자세한 내용은 백엔드 자체 설명서를 확인한다.

     

    Hatchling

    [build-system]
    requires = ["hatchling"]
    build-backend = "hatchling.build"

     

    setuptools

    [build-system]
    requires = ["setuptools>=61.0"]
    build-backend = "setuptools.build_meta"

     

    Flit

    [build-system]
    requires = ["flit_core>=3.4"]
    build-backend = "flit_core.buildapi"

     

    PDM

    [build-system]
    requires = ["pdm-backend"]
    build-backend = "pdm.backend"

     

    The requires key is a list of packages that are needed to build your package. The frontend should install them automatically when building your package. Frontends usually run builds in isolated environments, so omitting dependencies here may cause build-time errors. This should always include your backend’s package, and might have other build-time dependencies.

    The build-backend key is the name of the Python object that frontends will use to perform the build.

    Both of these values will be provided by the documentation for your build backend, or generated by its command line interface. There should be no need for you to customize these settings.

    Additional configuration of the build tool will either be in a tool section of the pyproject.toml, or in a special file defined by the build tool. For example, when using setuptools as your build backend, additional configuration may be added to a setup.py or setup.cfg file, and specifying setuptools.build_meta in your build allows the tools to locate and use these automatically.

    requires 키는 패키지를 빌드하는 데 필요한 패키지 목록이다. 패키지를 빌드할 때 프런트엔드가 이를 자동으로 설치해야 한다. 프런트엔드는 일반적으로 격리된 환경에서 빌드를 실행하므로 여기서 종속성을 생략하면 빌드 시간 오류가 발생할 수 있다. 여기에는 항상 백엔드 패키지가 포함되어야 하며 다른 빌드 시간 종속성이 있을 수 있다.

    build-backend 키는 프런트엔드가 빌드를 수행하는 데 사용할 Python 개체의 이름이다.

    이 두 값은 모두 빌드 백엔드에 대한 문서에서 제공되거나 해당 명령줄 인터페이스에서 생성된다. 이러한 설정을 사용자 정의할 필요는 없다.

    빌드 도구의 추가 구성은 pyproject.toml의 도구 섹션이나 빌드 도구에서 정의한 특수 파일에 있다. 예를 들어 setuptools를 빌드 백엔드로 사용하는 경우 setup.py 또는 setup.cfg 파일에 추가 구성이 추가될 수 있으며 빌드에서 setuptools.build_meta를 지정하면 도구가 이러한 구성을 자동으로 찾아 사용할 수 있다.

    Configuring metadata

    Open pyproject.toml and enter the following content. Change the name to include your username; this ensures that you have a unique package name that doesn’t conflict with packages uploaded by other people following this tutorial.

    pyproject.toml을 열고 다음 내용을 입력한다. 사용자 이름을 포함하도록 이름을 변경한다. 이렇게 하면 이 튜토리얼을 따르는 다른 사람들이 업로드한 패키지와 충돌하지 않는 고유한 패키지 이름을 갖게 된다.

    [project]
    name = "example_package_YOUR_USERNAME_HERE"
    version = "0.0.1"
    authors = [
      { name="Example Author", email="author@example.com" },
    ]
    description = "A small example package"
    readme = "README.md"
    requires-python = ">=3.8"
    classifiers = [
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ]
    
    [project.urls]
    Homepage = "https://github.com/pypa/sampleproject"
    Issues = "https://github.com/pypa/sampleproject/issues"

     

    • name is the distribution name of your package. This can be any name as long as it only contains letters, numbers, ., _ , and -. It also must not already be taken on PyPI. Be sure to update this with your username for this tutorial, as this ensures you won’t try to upload a package with the same name as one which already exists.
    • version is the package version. (Some build backends allow it to be specified another way, such as from a file or Git tag.)
    • authors is used to identify the author of the package; you specify a name and an email for each author. You can also list maintainers in the same format.
    • description is a short, one-sentence summary of the package.
    • readme is a path to a file containing a detailed description of the package. This is shown on the package detail page on PyPI. In this case, the description is loaded from README.md (which is a common pattern). There also is a more advanced table form described in the pyproject.toml guide.
    • requires-python gives the versions of Python supported by your project. An installer like pip will look back through older versions of packages until it finds one that has a matching Python version.
    • classifiers gives the index and pip some additional metadata about your package. In this case, the package is only compatible with Python 3, is licensed under the MIT license, and is OS-independent. You should always include at least which version(s) of Python your package works on, which license your package is available under, and which operating systems your package will work on. For a complete list of classifiers, see https://pypi.org/classifiers/.
    • urls lets you list any number of extra links to show on PyPI. Generally this could be to the source, documentation, issue trackers, etc.

     

    • name은 패키지의 배포 이름이다. 문자, 숫자, ., _ 및 -만 포함하는 한 어떤 이름이든 가능하다. 또한 PyPI에서 이미 사용 중이어서는 안 된다. 이 튜토리얼의 사용자 이름으로 이를 업데이트해야 한다. 이렇게 하면 이미 존재하는 패키지와 동일한 이름을 가진 패키지를 업로드하려고 시도하지 않게 된다.
    • version은 패키지 버전이다. (일부 빌드 백엔드에서는 파일이나 Git 태그 등 다른 방식으로 지정할 수 있다.)
    • authors는 패키지 작성자를 식별하는 데 사용된다. 각 작성자의 이름과 이메일을 지정한다. 동일한 형식으로 관리자를 나열할 수도 있다.
    • description은 패키지에 대한 짧은 한 문장 요약이다.
    • readme는 패키지에 대한 자세한 설명이 포함된 파일의 경로다. 이는 PyPI의 패키지 세부 정보 페이지에 표시된다. 이 경우 설명은 README.md(일반적인 패턴)에서 로드된다. pyproject.toml 가이드에 설명된 고급 테이블 형식도 있다.
    • require-python은 프로젝트에서 지원하는 Python 버전을 제공하다. pip와 같은 설치 프로그램은 일치하는 Python 버전이 있는 패키지를 찾을 때까지 이전 버전의 패키지를 다시 살펴본다.
    • classifiers는 패키지에 대한 추가 메타데이터를 색인 및 pip에 제공하다. 이 경우 패키지는 Python 3만 호환되고 MIT 라이선스에 따라 라이선스가 부여되며 OS 독립적이다. 최소한 패키지가 작동하는 Python 버전, 패키지를 사용할 수 있는 라이선스, 패키지가 작동할 운영 체제를 항상 포함해야 한다. 분류자의 전체 목록은 https://pypi.org/classifiers/를 참조한다.
    • urls를 사용하면 PyPI에 표시할 추가 링크를 원하는 만큼 나열할 수 있다. 일반적으로 이는 소스, 문서, 이슈 추적기 등에 대한 것일 수 있다.

    See the pyproject.toml guide for details on these and other fields that can be defined in the [project] table. Other common fields are keywords to improve discoverability and the dependencies that are required to install your package.

    [project] 테이블에 정의할 수 있는 이러한 필드와 기타 필드에 대한 자세한 내용은 pyproject.toml 가이드를 참조한다. 다른 공통 필드는 패키지를 설치하는 데 필요한 검색 가능성과 종속성을 향상시키는 키워드다.

    Creating README.md

    Open README.md and enter the following content. You can customize this if you’d like.

    README.md를 열고 다음 내용을 입력한다. 원하는 경우 이를 맞춤설정할 수 있다.

    # Example Package

     

    This is a simple example package. You can use below to write your content.

    이것은 간단한 예제 패키지이다. 자신의 콘텐츠를 작성하기 위해 아래와 같이 사용할 수 있다.

    [GitHub-flavored Markdown](https://guides.github.com/features/mastering-markdown/)

    Creating a LICENSE

    It’s important for every package uploaded to the Python Package Index to include a license. This tells users who install your package the terms under which they can use your package. For help picking a license, see https://choosealicense.com/. Once you have chosen a license, open LICENSE and enter the license text. For example, if you had chosen the MIT license:

    Python 패키지 색인에 업로드된 모든 패키지에 라이선스를 포함하는 것이 중요하다. 이는 패키지를 설치하는 사용자에게 패키지를 사용할 수 있는 조건을 알려준다. 라이선스 선택에 대한 도움말은 https://choosealicense.com/을 참조한다. 라이센스를 선택했으면 LICENSE를 열고 라이센스 텍스트를 입력한다. 예를 들어, MIT 라이센스를 선택한 경우:

    Copyright (c) 2018 The Python Packaging Authority
    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:
    
    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.
    
    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
    SOFTWARE.

     

    Most build backends automatically include license files in packages. See your backend’s documentation for more details.

    대부분의 빌드 백엔드에는 패키지에 라이선스 파일이 자동으로 포함된다. 자세한 내용은 백엔드 설명서를 참조한다.

    Including other files

    The files listed above will be included automatically in your source distribution. If you want to include additional files, see the documentation for your build backend.

    위에 나열된 파일은 소스 배포판에 자동으로 포함된다. 추가 파일을 포함하려면 빌드 백엔드 설명서를 참조한다.

    Generating distribution archives

    The next step is to generate distribution packages for the package. These are archives that are uploaded to the Python Package Index and can be installed by pip.

    Make sure you have the latest version of PyPA’s build installed:

    다음 단계는 패키지에 대한 배포 패키지를 생성하는 것이다. 이는 Python 패키지 색인에 업로드되고 pip로 설치할 수 있는 아카이브다.

    최신 버전의 PyPA 빌드가 설치되어 있는지 확인한다.

     

    Unix/macOS

    python3 -m pip install --upgrade build

     

    Windows

    py -m pip install --upgrade build

    Tip

    If you have trouble installing these, see the Installing Packages tutorial.

    설치하는 데 문제가 있는 경우 패키지 설치 튜토리얼을 참조한다.

     

    Now run this command from the same directory where pyproject.toml is located:

    이제 pyproject.toml이 있는 동일한 디렉터리에서 이 명령을 실행한다.

     

    Unix/macOS

    python3 -m build

     

    Windows

    py -m build

     

    This command should output a lot of text and once completed should generate two files in the dist directory:

    이 명령은 많은 양의 텍스트를 출력해야 하며 완료되면 dist 디렉터리에 두 개의 파일을 생성해야 한다.

    dist/
    ├── example_package_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
    └── example_package_YOUR_USERNAME_HERE-0.0.1.tar.gz

     

    The tar.gz file is a source distribution whereas the .whl file is a built distribution. Newer pip versions preferentially install built distributions, but will fall back to source distributions if needed. You should always upload a source distribution and provide built distributions for the platforms your project is compatible with. In this case, our example package is compatible with Python on any platform so only one built distribution is needed.

    tar.gz 파일은 소스 배포판이고 .whl 파일은 빌드된 배포판이다. 최신 pip 버전은 빌드된 배포판을 우선적으로 설치하지만 필요한 경우 소스 배포판으로 대체된다. 항상 소스 배포판을 업로드하고 프로젝트가 호환되는 플랫폼에 대해 빌드된 배포판을 제공해야 한다. 이 경우 예제 패키지는 모든 플랫폼에서 Python과 호환되므로 빌드된 배포판은 하나만 필요하다.

    Uploading the distribution archives

    Finally, it’s time to upload your package to the Python Package Index!

    The first thing you’ll need to do is register an account on TestPyPI, which is a separate instance of the package index intended for testing and experimentation. It’s great for things like this tutorial where we don’t necessarily want to upload to the real index. To register an account, go to https://test.pypi.org/account/register/ and complete the steps on that page. You will also need to verify your email address before you’re able to upload any packages. For more details, see Using TestPyPI.

    To securely upload your project, you’ll need a PyPI API token. Create one at https://test.pypi.org/manage/account/#api-tokens, setting the “Scope” to “Entire account”. Don’t close the page until you have copied and saved the token — you won’t see that token again.

    Now that you are registered, you can use twine to upload the distribution packages. You’ll need to install Twine:

    마지막으로 Python 패키지 색인에 패키지를 업로드할 시간이다!

    가장 먼저 해야 할 일은 테스트 및 실험을 위한 패키지 인덱스의 별도 인스턴스인 TestPyPI에 계정을 등록하는 것이다. 실제 인덱스에 반드시 업로드하고 싶지 않은 이 튜토리얼과 같은 작업에 적합하다. 계정을 등록하려면 https://test.pypi.org/account/register/로 이동하여 해당 페이지의 단계를 완료한다. 또한 패키지를 업로드하기 전에 이메일 주소를 확인해야 한다. 자세한 내용은 TestPyPI 사용을 참조한다.

    프로젝트를 안전하게 업로드하려면 PyPI API 토큰이 필요하다. https://test.pypi.org/manage/account/#api-tokens에서 하나를 만들고 "범위"를 "전체 계정"으로 설정한다. 토큰을 복사하고 저장할 때까지 페이지를 닫지 않는다. 해당 토큰은 다시 표시되지 않는다.

    이제 등록되었으므로 Twine을 사용하여 배포 패키지를 업로드할 수 있다. Twine을 설치해야 한다.

     

    Unix/macOS

    python3 -m pip install --upgrade twine

     

    Windows

    py -m pip install --upgrade twine

     

    Once installed, run Twine to upload all of the archives under dist:

    설치가 완료되면 Twine을 실행하여 dist 아래의 모든 아카이브를 업로드한다.

     

    Unix/macOS

    python3 -m twine upload --repository testpypi dist/*

     

    Windows

    py -m twine upload --repository testpypi dist/*

     

    You will be prompted for a username and password. For the username, use __token__. For the password, use the token value, including the pypi- prefix.

    After the command completes, you should see output similar to this:

    사용자 이름과 비밀번호를 입력하라는 메시지가 표시된다. 사용자 이름에는 __token__을 사용한다. 비밀번호에는 pypi- 접두사를 포함한 토큰 값을 사용한다.

    명령이 완료되면 다음과 유사한 출력이 표시된다.

    Uploading distributions to https://test.pypi.org/legacy/
    Enter your username: __token__
    Uploading example_package_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl
    100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 8.2/8.2 kB • 00:01 • ?
    Uploading example_package_YOUR_USERNAME_HERE-0.0.1.tar.gz
    100% ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 6.8/6.8 kB • 00:00 • ?

     

    Once uploaded, your package should be viewable on TestPyPI; for example: 

    업로드되면 패키지를 TestPyPI에서 볼 수 있어야 한다. 예: https://test.pypi.org/project/example_package_YOUR_USERNAME_HERE.

    Installing your newly uploaded package

    You can use pip to install your package and verify that it works. Create a virtual environment and install your package from TestPyPI:

    pip를 사용하여 패키지를 설치하고 작동하는지 확인할 수 있다. 가상 환경을 만들고 TestPyPI에서 패키지를 설치한다.

     

    Unix/macOS

    python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps example-package-YOUR-USERNAME-HERE

     

    Windows

    py -m pip install --index-url https://test.pypi.org/simple/ --no-deps example-package-YOUR-USERNAME-HERE

     

    Make sure to specify your username in the package name!

    pip should install the package from TestPyPI and the output should look something like this:

    패키지 이름에 사용자 이름을 지정한다!

    pip는 TestPyPI에서 패키지를 설치해야 하며 출력은 다음과 같아야 한다.

    Collecting example-package-YOUR-USERNAME-HERE
      Downloading https://test-files.pythonhosted.org/packages/.../example_package_YOUR_USERNAME_HERE_0.0.1-py3-none-any.whl
    Installing collected packages: example_package_YOUR_USERNAME_HERE
    Successfully installed example_package_YOUR_USERNAME_HERE-0.0.1

    Note

    This example uses --index-url flag to specify TestPyPI instead of live PyPI. Additionally, it specifies --no-deps. Since TestPyPI doesn’t have the same packages as the live PyPI, it’s possible that attempting to install dependencies may fail or install something unexpected. While our example package doesn’t have any dependencies, it’s a good practice to avoid installing dependencies when using TestPyPI.

    이 예에서는 --index-url 플래그를 사용하여 라이브 PyPI 대신 TestPyPI를 지정한다. 또한 --no-deps를 지정한다. TestPyPI에는 실제 PyPI와 동일한 패키지가 없으므로 종속성 설치 시도가 실패하거나 예상치 못한 항목이 설치될 수 있다. 예제 패키지에는 종속성이 없지만 TestPyPI를 사용할 때 종속성을 설치하지 않는 것이 좋다.

     

    You can test that it was installed correctly by importing the package. Make sure you’re still in your virtual environment, then run Python:

    패키지를 가져와서 올바르게 설치되었는지 테스트할 수 있다. 아직 가상 환경에 있는지 확인한 후 Python을 실행한다.

     

    Unix/macOS

    python3

     

    Windows

    py

     

    and import the package:

    패키지를 가져온다.

    from example_package_YOUR_USERNAME_HERE import example
    example.add_one(2)
    3

    Next steps

    Congratulations, you’ve packaged and distributed a Python project! ✨ 🍰 ✨

    Keep in mind that this tutorial showed you how to upload your package to Test PyPI, which isn’t a permanent storage. The Test system occasionally deletes packages and accounts. It is best to use TestPyPI for testing and experiments like this tutorial.

    When you are ready to upload a real package to the Python Package Index you can do much the same as you did in this tutorial, but with these important differences:

    축하한다. Python 프로젝트를 패키징하고 배포했다! ✨ 🍰 ✨

    이 튜토리얼에서는 영구 저장소가 아닌 Test PyPI에 패키지를 업로드하는 방법을 보여주었다. 테스트 시스템은 때때로 패키지와 계정을 삭제한다. 이 튜토리얼과 같은 테스트 및 실험에는 TestPyPI를 사용하는 것이 가장 좋다.

    실제 패키지를 Python 패키지 색인에 업로드할 준비가 되면 이 튜토리얼에서 했던 것과 거의 동일한 작업을 수행할 수 있지만 다음과 같은 중요한 차이점이 있다.

     

    • Choose a memorable and unique name for your package. You don’t have to append your username as you did in the tutorial, but you can’t use an existing name.
    • Register an account on https://pypi.org - note that these are two separate servers and the login details from the test server are not shared with the main server.
    • Use twine upload dist/* to upload your package and enter your credentials for the account you registered on the real PyPI. Now that you’re uploading the package in production, you don’t need to specify --repository; the package will upload to https://pypi.org/ by default.
    • Install your package from the real PyPI using python3 -m pip install [your-package].

     

    • 패키지에 대해 기억에 남는 고유한 이름을 선택한다. 튜토리얼에서 했던 것처럼 사용자 이름을 추가할 필요는 없지만 기존 이름을 사용할 수는 없다.
    • https://pypi.org에 계정을 등록한다. 이 서버는 두 개의 별도 서버이며 테스트 서버의 로그인 세부 정보는 기본 서버와 공유되지 않는다.
    • Twine upload dist/*를 사용하여 패키지를 업로드하고 실제 PyPI에 등록한 계정의 자격 증명을 입력한다. 이제 프로덕션 환경에서 패키지를 업로드하므로 --repository를 지정할 필요가 없다. 패키지는 기본적으로 https://pypi.org/에 업로드된다.
    • python3 -m pip install [your-package]를 사용하여 실제 PyPI에서 패키지를 설치한다.

    At this point if you want to read more on packaging Python libraries here are some things you can do:

    이 시점에서 Python 라이브러리 패키징에 대해 더 자세히 알고 싶다면 다음과 같이 할 수 있다.

    Read about advanced configuration for your chosen build backend: Hatchling, setuptools, Flit, PDM.

    Look at the guides on this site for more advanced practical information, or the discussions for explanations and background on specific topics.

    Consider packaging tools that provide a single command-line interface for project management and packaging, such as hatch, flit, pdm, and poetry.

    선택한 빌드 백엔드에 대한 고급 구성(Hatchling, setuptools, Flit, PDM)에 대해 읽는다.

    보다 고급 실제 정보를 보려면 이 사이트의 가이드를 살펴보거나 특정 주제에 대한 설명 및 배경에 대한 토론을 살펴본다.

    hatch, flit, pdm, poetry 등 프로젝트 관리 및 패키징을 위한 단일 명령줄 인터페이스를 제공하는 패키징 도구를 고려해 본다.

    Notes

    [1]

    Technically, you can also create Python packages without an __init__.py file, but those are called namespace packages and considered an advanced topic (not covered in this tutorial). If you are only getting started with Python packaging, it is recommended to stick with regular packages and __init__.py (even if the file is empty).

    기술적으로 __init__.py 파일 없이 Python 패키지를 생성할 수도 있지만 이를 네임스페이스 패키지라고 하며 고급 주제로 간주된다(이 튜토리얼에서는 다루지 않음). Python 패키징을 시작하는 경우에는 일반 패키지와 __init__.py(파일이 비어 있더라도)를 계속 사용하는 것이 좋다.

    728x90

    '코딩 > Python' 카테고리의 다른 글

    Python/Pandas/10 minutes to pandas  (0) 2024.05.03
    Pyton/프로그램의 종료, exit() & quit()  (0) 2024.04.17
    Python/Reference/어휘분석  (1) 2024.03.15
    Python/Reference/소개  (0) 2024.03.15
    Python/PEP 8 – Style Guide for Python Code  (0) 2024.03.10

    댓글

Designed by Tistory.