Learn Python from Python poetry for dependency management [picture and text]

Charlie is not a dog 2022-06-23 17:48:23 阅读数:228

learnpythonpythonpoetrydependency

Abstract : In this tutorial , You explored how to create new Python Poetry Project and how to Poetry Add to existing project .

When your Python When a project depends on an external package , You need to make sure you use the correct version of each package . After the update , The package may not work as it did before the update .Python Poetry And Class's dependency manager helps you specify 、 Install and resolve external packages in the project . In this way , You can ensure that the correct dependent version is always used on each machine .

Use Poetry Will help you start a new project 、 Maintain existing projects and master Dependency management . You will be ready to use pyproject.toml file , It will be in Python Define the criteria for building requirements in the project .

To complete this tutorial and make the most of it , You should be aware of the virtual environment 、 Modules and packages and pip.

Although this tutorial focuses on dependency management , but Poetry It can also help you build and package projects . If you want to share your work , Then you can even put your Poetry Project publishing to Python Packaging Index (PyPI).

Pay attention to the prerequisites


In-depth study Python Poetry Before the details , You need to know some prerequisites . First , You will read a short overview of the terms you will encounter in this tutorial . Next , You will install Poetry In itself .

Related terms

If you ever import stay Python Statements used in scripts , Then you have used modules. Some of these modules may have been written by you Python file . Others may be built-in modular , for example datetime. however , Sometimes Python Not enough is provided . At that time, you may turn to external packaging modules . When your Python When the code depends on an external module , You can say these package It's your project rely on term .

You can go to PyPI Not belonging to Python Standard library packages . Before you know how it works , You need to install... On your system Poetry.

Python Poetry install

To use... On the command line Poetry, You should install it system wide . If you just want to try , Then you can use pip. But you should be careful to try this approach , because Poetry Will install its own dependencies , This may conflict with other packages you use in your project .

install Poetry The recommended method is to use official install-poetry Script . You can manually download and run this Python file , You can also select your operating system below to use the corresponding commands :

  • window
  • Linux + macOS
PS C:\\> (Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py -UseBasicParsing).Content | python -

If you are using Windows, Then you can use Invoke-Webrequest with -UseBasicParsing Option cmdlet Will request URL Download your content to Standard output stream (stdout). With pipeline characters (|), You hand over the output to Standard input stream ( The standard input ) Of python. under these circumstances , You pipeline your content install-poetry.py Transferred to the Python Interpreter .

Be careful : Some users are Windows 10 Upper use PowerShell Command will report an error .

In the output , You should see the message that the installation is complete . You can poetry --version Run in the terminal to see if poetry It works . This command will display your current Poetry edition . If you want to update Poetry, You can run poetry self update.

Python Poetry introduction


install Poetry after , It's time to see Poetry How it works . In this section , You will learn how to start a new Poetry Project and how to Poetry Add to existing project . You will also see the project structure and examine pyproject.toml file .

Create a new Poetry project

You can use new Command and project name as parameters to create a new Poetry project . In this tutorial , The project is called rp-poetry. Create project , Then enter the newly created Directory :

$ poetry new rp-poetry
$ cd rp-poetry

By running poetry new rp-poetry, You can create a New folder for rp-poetry/. When you look inside a folder , You will see a structure :

rp-poetry/
│
├── rp\_poetry/
│ └── \_\_init\_\_.py
│
├── tests/
│ ├── \_\_init\_\_.py
│ └── test\_rp\_poetry.py
│
├── README.rst
└── pyproject.toml

Poetry Will automatically normalize the package name for you . It will - Dash in project name ( ) transformation _ Underline the folder name ( ) rp_poetry/. otherwise ,Python The name is not allowed in , Therefore, you cannot import it as a module . For better control, create package names , You can use the --name Options are named differently than project folders :

$ poetry new rp-poetry --name realpoetry

If you prefer to store the source code in additional src/ In parent folder , that Poetry You can use the following --src Sign to comply with the agreement :

$ poetry new --src rp-poetry
$ cd rp-poetry

By adding --src sign , You created a file called Folder src/, It contains your rp_poetry/ Catalog :

rp-poetry/
│
├── src/
│ │
│ └── rp\_poetry/
│ └── \_\_init\_\_.py
│
├── tests/
│ ├── \_\_init\_\_.py
│ └── test\_rp\_poetry.py
│
├── README.rst
└── pyproject.toml

Create a new Poetry Project time , You will immediately receive a basic folder structure .

Check the project structure

The rp_poetry/ Is the subfolder itself spectacular . In this directory , You'll find one __init__.py File containing your package version :

\# rp\_poetry/\_\_init\_\_.py
\_\_version\_\_ = "0.1.0"

When you jump to tests/ Folder and open when test_rp_poetry.py, You'll notice it rp_poetry It is already importable :

\# tests/test\_rp\_poetry.py
from rp\_poetry import \_\_version\_\_
def test\_version():
assert \_\_version\_\_ == "0.1.0"

Poetry The first test was also added to the project . The test_version() Function check Of __version__ Is the variable rp_poetry/__init__.py Contains the expected version . however , The __init__.py The file is not the only place where you can define the package version . Another position is pyproject.toml file .

Use pyproject.toml file

Use Poetry One of the most important documents is pyproject.toml file . This file is not Poetry The invention of the . This is a PEP 518 As defined in The configuration file standard :

this PEP Appoint Python How should software packages specify the build dependencies they have to execute their chosen build system . As part of this specification , A new configuration file has been introduced for the package , Used to specify their build dependencies ( It is expected that the same configuration file will be used for future configuration details ).( source )

The author takes into account the “ New profile ” Several file formats . Last , They decided to adopt TOML Format , namely Tom's Obvious Minimal Language Abbreviation . In their view ,TOML Flexible enough , Better than other options (YAML、JSON、CFG or INI) Better readability and less complexity . To see TOML The appearance of the , Please open the pyproject.toml file :

 1# pyproject.toml
2
3\[tool.poetry\]
4name = "rp-poetry"
5version = "0.1.0"
6description = ""
7authors = \["Philipp <[email protected]>"\]
8
9\[tool.poetry.dependencies\]
10python = "^3.9"
11
12\[tool.poetry.dev-dependencies\]
13pytest = "^5.2"
14
15\[build-system\]
16requires = \["poetry-core>=1.0.0"\]
17build-backend = "poetry.core.masonry.api"

You can go to pyproject.toml There are four parts in the file . These parts are called surface . They include things like Poetry Such tools are used to identify and Dependency management or To build a routine Instructions .

If the table name is tool specific , You have to use tool. The prefix . By using such Sub table , You can add descriptions for different tools in the project . under these circumstances , Only tool.poetry. however , You may see examples like this [tool.pytest.ini_options] by pytest In other projects .

stay [tool.poetry] The above first 3 In the child table of row , You can store information about your Poetry General information about the project . Your available keys are provided by Poetry Definition . Although some keys are optional , But you must specify four keys :

  1. name: Your bag name
  2. version: The version of the package , It's best to follow semantic version control
  3. description: A brief description of your package
  4. authors: The author list , Format name <email>

The first [tool.poetry.dependencies]9 Row sum [tool.poetry.dev-dependencies] The first 12 The child tables of rows are critical to your dependency management . In the next section, I'd like to Poetry When adding dependencies to a project , You will learn more about these sub tables . Now? , It is important to recognize the difference between package dependencies and development dependencies .

The pyproject.toml The last table of the file is located at [build-system]15 That's ok . This table defines Poetry And other building tools can use data , But because it's not tool specific , So it has no prefix .Poetry Created pyproject.toml A file with two keys :

  1. requires: List of dependencies required to build the package , Make this key necessary
  2. build-backend: Used to perform the build process Python object

If you want to know more about pyproject.toml This part of the document , Then you can read PEP 517 Source tree in to learn more .

When you use Poetry When starting a new project , This is it. pyproject.toml The file you started . as time goes on , You will add configuration details about your package and the tools you are using . With Python The growth of projects , Your pyproject.toml Files will grow . For sub tables [tool.poetry.dependencies] and [tool.poetry.dev-dependencies]. In the next section , You will learn how to extend these sub tables .

Use Python Poetry


Once you set up a Poetry project , The real work can begin . once Poetry In place , You can start coding . In the process , You will learn Poetry How to provide you with A virtual environment And handle your dependencies .

Use Poetry Virtual environment for

When you start a new Python Project time , Creating a virtual environment is a good practice . otherwise , You may confuse different dependencies from different projects . Using a virtual environment is Poetry One of the core functions of , It will never interfere with your overall situation Python install .

however ,Poetry The virtual environment will not be created immediately when you start the project . You can do this by Poetry List all virtual environments connected to the current project to confirm Poetry The virtual environment has not been created . If you haven't ,cd Get into rp-poetry/ Then run a command :

$ poetry env list

at present , There should be no output .

When you run some commands ,Poetry Will create a virtual environment all the way . If you want to better control the creation of virtual environment , Then you may decide to tell Poetry Which one do you want to use Python edition , And then from there :

$ poetry env use python3

Use this command , You will use and install Poetry same Python edition . Use python3 The works of , When you're in your Python Executable program PATH.

Be careful : perhaps , You can pass the absolute path to Python Executable file . It should be with you in pyproject.toml Found in the file Python Version constraints match . without , Then you may be in trouble , Because you use Python The version is different from the version required by the project . The code running in your environment may have problems on another machine .

What's worse is , External packages usually depend on specific Python edition . therefore , Users who install packages may receive error messages , Because your dependency version is different from Python Version incompatible .

When you run env use, You will see a message :

Creating virtualenv rp-poetry-AWdWY-py3.9 in ~/Library/Caches/pypoetry/virtualenvs
Using virtualenv: ~/Library/Caches/pypoetry/virtualenvs/rp-poetry-AWdWY-py3.9

As you can see ,Poetry Build a unique name for your project environment . The name contains the project name and Python edition . The seemingly random string in the middle is the hash value of your parent directory . Through the unique string in the middle ,Poetry Can handle the same name and the same on the system Python Multiple projects of version . It's important , Because by default ,Poetry Create all virtual environments in the same folder .

Poetry No other configuration required , stay virtualenvs/Poetry The cache directory Create a virtual environment in a folder :

Use Python Poetry Manage dependencies _Poetry

If you want to change the default cache directory , You can edit it Poetry Configuration of . When you are already using virtualenvwrapper Or other third-party tools to manage your virtual environment , It would be useful . To view the current configuration , Include configured cache-dir, You can run the following command :

$ poetry config --list

Usually , You don't have to change this path . If you want to know about Poetry More information about virtual environment interaction , that Poetry The document contains a chapter on managing the environment .

As long as you are in the project folder ,Poetry Will use the virtual environment associated with it . If you have any questions , Sure env list Run the following command again to check whether the virtual environment is activated :

$ poetry env list

This will show something like rp-poetry-AWdWY-py3.9 (Activated). With an activated virtual environment , You can start managing some dependencies and see Poetry The charm of .

Declare your dependencies

Poetry A key element of is its handling of dependencies . Before we start , First look at the two dependency tables in the file pyproject.toml:

\# rp\_poetry/pyproject.toml (Excerpt)
\[tool.poetry.dependencies\]
python = "^3.9"
\[tool.poetry.dev-dependencies\]
pytest = "^5.2"

There are currently two dependencies declared for your project . One is Python In itself . The other is pytest, A widely used testing framework . As you saw before , Your project contains a tests/ Folders and one test_rp_poetry.py file . Use pytest As a dependency ,Poetry You can run your tests immediately after installation .

Be careful : In writing this tutorial ,pytest Use Python 3.10 function Poetry It doesn't work .Poetry Installed one with Python 3.10 Incompatible pytest edition .

Poetry Developers are already aware of this problem , It will follow Poetry 1.2 Fixed due to the release of .

Make sure you are rp-poetry/ In the project folder and run the command :

$ poetry install

Use this install command ,Poetry Check your pyproject.toml Dependencies in the file , Then parse and install them . When you have many dependencies that require different versions of different third-party packages , The parsing part is particularly important . Before installing any packages ,Poetry It determines which version of the package meets the version limit set by other packages .

except pytest Beyond its requirements ,Poetry The project itself is also installed . such , You can import... Now rp_poetry Into your test :

\# tests/test\_rp\_poetry.py
from rp\_poetry import \_\_version\_\_
def test\_version():
assert \_\_version\_\_ == "0.1.0"

After installing the project package , You can import rp_poetry Test and check __version__ character string . With pytest install , You can use poetry run Command to execute the test :

 1$ poetry run pytest
2========================= test session starts ==========================
3platform darwin -- Python 3.9.1, pytest-5.4.3, py-1.10.0, pluggy-0.13.1
4rootdir: /Users/philipp/Real Python/rp-poetry
5collected 1 item
6
8
9========================== 1 passed in 0.01s ===========================

Your current test has run successfully , So you can safely continue coding . however , If you look closely at section 3 That's ok , You'll find something strange . It said pytest-5.4.3,5.2 Unlike pyproject.toml As stated in the document . Good connection !

Take a look back. , In the document pytest Dependencies pyproject.toml As shown below :

\# rp\_poetry/pyproject.toml (Excerpt)
\[tool.poetry.dev-dependencies\]
pytest = "^5.2"

^ The preceding caret ( )5.2 It has a specific meaning , It is Poetry One of the provided version constraints . It means Poetry You can install any version that matches the non-zero number on the far left of the version string . It means 5.4.3 Allow to use . edition 6.0 Will not be allowed .

When Poetry When trying to resolve a dependent version , Symbols like caret will become very important . If there are only two requirements , It's not too difficult . The more dependencies you declare , The more complicated it is . Let's see Poetry How can you handle this problem by installing the new package into your project .

Install with Poetry My bag

you pip You may have used the installation before, but it does not belong to Python Standard library packages . If you pip install Run... With the package name as a parameter , be pip stay Python Package Index Find package on . You can use... In the same way Poetry.

If you want to requests Add an external package to your project , Then you can run a command :

$ poetry add requests

By running poetry add requests, You are transferring the latest version of requests Add libraries to your project . You can use version constraints ,requests<=2.1 perhaps requests==2.24 If you want to be more specific . When you do not add any constraints ,Poetry Will always try to install the latest version of the package .

Sometimes , You only want to use certain packages in your development environment . Use pytest, You've found one of them . Another common library includes a code format like black , A document generation and other Sphinx , And a similar static analysis tool pylint Of ,Flake8,mypy, or coverage.py.

Be clear about Poetry A development package is a dependency , You can poetry add Use this --dev Options run . You can also use shorthand -D Options , It is the same as the following --dev:

$ poetry add black -D

You add requests For project dependencies and black Develop dependencies .Poetry I did something for you backstage . One side , It adds your declared dependencies to pyproject.toml In file :

\# rp\_poetry/pyproject.toml (Excerpt)
\[tool.poetry.dependencies\]
python = "^3.9"
requests = "^2.26.0"
\[tool.poetry.dev-dependencies\]
pytest = "^5.2"
black = "^21.9b0"

Poetry Will be requests Add package as project dependency to tool.poetry.dependencies In the table , At the same time black Add as a development dependency to tool.poetry.dev-dependencies.

Distinguishing between project dependencies and development dependencies can prevent installation users from needing to run programs . Development dependencies are only relevant to other developers of your package , They hope pytest Use black. When users install your package , They only install requests it .

Be careful : You can go further and declare Optional dependencies . When you want users to choose to install a specific database adapter that does not need but enhances your package , That would come in handy . You can go to Poetry file Learn more about optional dependencies in .

Except yes pyproject.toml In addition to changes to the file ,Poetry And created a new one called poetry.lock. In this document ,Poetry Will track all packages and exact versions you use in your project .

Handle poetry.lock


When you run the poetry add On command ,Poetry It will update automatically pyproject.toml And fix it poetry.lock Parsed version in file . however , You don't have to let Poetry Complete all work . You can manually apply to pyproject.toml Add dependencies to the file and lock them later .

Pin dependencies poetry.lock

If you want to use Python Build a web crawler , Then you may need to use Beautiful Soup To parse your data . Add it to the file tool.poetry.dependencies In the table pyproject.toml:

\# rp\_poetry/pyproject.toml (Excerpt)
\[tool.poetry.dependencies\]
python = "^3.9"
requests = "^2.26.0"
beautifulsoup4 = "4.10.0"

By adding beautifulsoup4 = "4.10.0", You tell Poetry It should fully install this version . When you pyproject.toml When adding requirements to a document , It is not installed yet . as long as poetry.lock No files exist in your project , You can poetry install Run after manually adding dependencies , because Poetry First search poetry.lock file . If not found ,Poetry Will parse pyproject.toml Dependencies listed in the file .

once poetry.lock File exists ,Poetry This file will be relied on to install dependencies . Run only poetry install Will trigger a warning , Prompt that the two files are out of sync and an error will occur , because Poetry I don't know yet. beautifulsoup4 Any version in the project .

To put pyproject.toml Manually added dependencies in the file are fixed to poetry.lock, You must first run the following poetry lock command :

$ poetry lock
Updating dependencies
Writing lock file

By running poetry lock,Poetry Handle pyproject.toml All dependencies in the file and lock them to poetry.lock In file . Poetry doesn't stop there . Runtime poetry lock,Poetry It also recursively traverses and locks all dependencies of your direct dependencies .

Be careful :poetry lock If there is a new version available that suits your version limit , This command also updates your existing dependencies . If you don't want to update poetry.lock Any dependencies already in the file , You have to --no-update Options added to poetry lock In command :

$ poetry lock --no-update

under these circumstances ,Poetry Resolve only new dependencies , but poetry.lock Any existing dependency versions in the file will not be changed .

Now that you have fixed all dependencies , It's time to install them so you can use them in your project .

Install dependencies poetry.lock

If you follow the steps in the previous section , Then you have installed pytest and black Using the poetry add command . You also locked beautifulsoup4, But you haven't installed Beautiful Soup. To verify beautifulsoup4 Not yet installed , Please use the following command to open Python Interpreter poetry run:

$ poetry run python3

perform poetry run python3 Will be in Poetry Open an interactive... In an environment REPL conversation . First , Try importing requests. It should be perfect . Then try importing bs4, This is a Beautiful Soup Module name of . This should cause errors , Because... Is not installed yet Beautiful Soup:

\>>>
\>>> import requests
\>>> import bs4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'bs4'

As expected , You can requests Import... Without difficulty , also bs4 Module not found . By typing exit() And click to exit the interactive Python Interpreter Enter.

Use poetry lock After the command locks the dependency , You must run this poetry install command , So that you can actually use them in your project :

$ poetry install
Installing dependencies from lock file
Package operations: 2 installs, 0 updates, 0 removals
• Installing soupsieve (2.2.1)
• Installing beautifulsoup4 (4.10.0)
Installing the current project: rp-poetry (0.1.0)

By running poetry install,Poetry Read poetry.lock File and install all dependencies declared in it . Now? ,bs4 Ready to use... In your project . To test this , Please enter poetry run python3 And import bs4Python Interpreter :

\>>>
\>>> import bs4
\>>> bs4.\_\_version\_\_
'4.10.0'

The perfect ! There are no mistakes this time , And you have the exact version of your statement . It means Beautiful Soup Has been properly fixed to your poetry.lock In file , Installed in your project , And it's ready to use . To list the packages available in the project and check their details , You can use the show command . When you use --help Flag when running it , You'll see how to use it :

$ poetry show --help

To check the package , You can use show Package name as a parameter , You can also use --tree Option lists all dependencies as a tree . This will help you see the nested requirements of the project .

Update dependency

To update your dependencies ,Poetry Different options are provided according to the two situations :

  1. Update dependencies within version constraints .
  2. Update dependencies outside version constraints .

You can go to pyproject.toml Version limit found in file . When the dependencies of the new version still meet your version limit , You can use the following update command :

$ poetry update

The update The command will update all packages and their dependencies within the version limit . after ,Poetry Will update your poetry.lock file .

If you want to update one or more specific packages , Then you can list them as parameters :

$ poetry update requests beautifulsoup4

Use this command ,Poetry New versions that meet the version limits listed in the file will be searched requests And the new version . Then it will resolve all the dependencies of your project and fix the version into your file . Your file will remain unchanged , Because the constraints listed are still valid .beautifulsoup4pyproject.tomlpoetry.lockpyproject.toml

If you want to use a ratio pyproject.toml The version defined in the file updates the dependency with a higher version , You need to pyproject.toml Adjust the file in advance . Another option is add Use version constraints or latest Label run command :

$ poetry add [email protected] --dev

When you run add with latest When marking the command , It will find the latest version of the package and update your pyproject.toml file . contain latest Label or version constraints are important for using this add Command is essential . Without it , You will receive a message , Indicates that the package already exists in your project . in addition , Don't forget it --dev Add flags for development dependencies . otherwise , You will add the package to the general dependencies .

After adding a new version , You must run install The commands you learned in the previous section . That's the only way , Your update will be locked to poetry.lock In file .

If you're not sure what version based changes the update will introduce for your dependencies , You can use the --dry-run sign . This flag applies to the command update and add command . It displays operations in your terminal without performing any operations . such , You can safely discover version changes and decide which update scheme is best for you .

distinguish pyproject.toml and poetry.lock

although pyproject.toml The version requirements in the document may be very loose , but Poetry Will lock you in poetry.lock The version actually used in the file . That's why Git Reasons why this document should be submitted when . adopt poetry.lock stay Git Repository Provide documentation , You can ensure that all developers will use the same version of the required package . When you encounter problems that include poetry.lock File repository , Best use Poetry.

Use poetry.lock, You can make sure that the version you are using is exactly the same as that used by other developers . If other developers don't use Poetry, You can add it to unused Poetry Set up in an existing project .

take poetry Add to existing project


Is likely to , Your project is not from poetry new The order begins . perhaps , You may have inherited one that doesn't use Poetry Project created , But now you want to use Poetry Manage dependencies . In these types of cases , You can use Poetry Add to existing Python In the project .

add to pyproject.toml To the script folder

If your project contains only some Python file , Then you can still add Poetry As the basis for future construction . In this case , Only one file ,hello.py:

\# rp-hello/hello.py
print("Hello World!")

The only thing this script can do is output a string "Hello World!". But maybe this is just the beginning of a grand project , So you decided to Poetry Add to your project .poetry new You will use the following poetry init command , Instead of using the previous command :

$ poetry init
This command will guide you through creating your pyproject.toml config.
Package name \[rp-hello\]: rp-hello
Version \[0.1.0\]:
Description \[\]: My Hello World Example
Author \[Philipp <[email protected]>, n to skip\]:
License \[\]:
Compatible Python versions \[^3.9\]:
Would you like to define your main dependencies interactively? (yes/no) \[yes\] no
Would you like to define your development dependencies interactively? (yes/no) \[yes\] no
Generated file

The poetry init The command starts an interactive session to create pyproject.toml file . Poetry It provides you with suggestions for most configurations you need to set up , You can press Enter To use them . When you do not declare any dependencies ,pyproject.tomlPoetry The files created are as follows :

\# rp-hello/pyproject.toml
\[tool.poetry\]
name = "rp-hello"
version = "0.1.0"
description = "My Hello World Example"
authors = \["Philipp <[email protected]>"\]
\[tool.poetry.dependencies\]
python = "^3.9"
\[tool.poetry.dev-dependencies\]
\[build-system\]
requires = \["poetry-core>=1.0.0"\]
build-backend = "poetry.core.masonry.api"

The content looks similar to the examples you experienced in the previous sections .

Now you can use Poetry All commands provided by the project . With pyproject.toml file , You can now run the script :

$ poetry run python3 hello.py
Creating virtualenv rp-simple-UCsI2-py3.9 in ~/Library/Caches/pypoetry/virtualenvs
Hello World!

because Poetry No virtual environment was found to use , So it creates a new environment before executing your script . After doing this , It will show your Hello World! Message without any errors . This means that you now have a running Poetry project .

Use existing requirements.txt file

Sometimes your project already has a requirements.txt file . have a look requirements.txt This Python Web crawler files :

$ cat requirements.txt
beautifulsoup4==4.9.3
certifi==2020.12.5
chardet==4.0.0
idna==2.10
requests==2.25.1
soupsieve==2.2.1
urllib3==1.26.4

Use this cat Utilities , You can read the file and write the contents to standard output . In this case , It shows the dependencies of the web crawler project . Use establish Poetry After the project poetry init, You can add the cat The utility is similar to the following poetry add Command in combination with :

$ poetry add \`cat requirements.txt\`
Creating virtualenv rp-require-0ubvZ-py3.9 in ~/Library/Caches/pypoetry/virtualenvs
Updating dependencies
Writing lock file
Package operations: 7 installs, 0 updates, 0 removals
• Installing certifi (2020.12.5)
• Installing chardet (4.0.0)
• Installing idna (2.10)
• Installing soupsieve (2.2.1)
• Installing urllib3 (1.26.4)
• Installing beautifulsoup4 (4.9.3)
• Installing requests (2.25.1)

When the requirements document is as simple as this , Use poetry add and cat It can save you some manual work .

requirements.txt However , Sometimes files are more complex . In these cases , You can execute a test run and view the results , Or manually add the requirements to the file [tool.poetry.dependencies] In the table pyproject.toml. You want to see the structure of pyproject.toml Whether it works , You can go to poetry check And then run .

establish requirements.txt since poetry.lock

In some cases , You must have a requirements.txt file . for example , Maybe you want to Heroku Hosting your Django project . In this case ,Poetry Provides export command . If you have one Poetry project , You can requirements.txt From your poetry.lock Create a file in the file :

$ poetry export --output requirements.txt

poetry export Using this command in this way creates a requirements.txt Files containing hashes and environment tags . This means that you can ensure that you deal with poetry.lock The content of the document is similar to the very strict requirements . If you also want to include your development dependencies , You can add --dev Into the command . To see all available options , You can choose poetry export --help.

Command Reference


This tutorial introduces you to Poetry Dependency management for . In the process , You used some Poetry Command line interface (CLI) command :

Use Python Poetry Manage dependencies _ A virtual environment _02

You can view Poetry CLI Documentation for the above commands and Poetry More information about other commands provided . You can also poetry --help Run directly in the terminal to view information !

Conclusion

--

In this tutorial , You explored how to create new Python Poetry Project and how to Poetry Add to existing project .Poetry A key part of is pyproject.toml file . And Use a combination of poetry.lock, You can ensure that the exact version of each package required to install the project . When you track poetry.lockGit When files in the repository , You also want to ensure that all other developers in the project install the same version of the dependency on their machines .

版权声明:本文为[Charlie is not a dog]所创,转载请带上原文链接,感谢。 https://pythonmana.com/2022/01/202201051804123561.html