Error running poetry pycharm

Poetry is a tool that facilitates creating a Python virtual environment based on the project dependencies. You can declare the libraries your project depends on, and Poetry will install and update them for you.

Poetry is a tool that facilitates creating a Python virtual environment based on the project dependencies. You can declare the libraries your project depends on, and Poetry will install and update them for you.

Project dependencies are recorded in the pyproject.toml file that specifies required packages, scripts, plugins, and URLs. See the pyproject reference for more information about its structure and format.

To use Poetry in PyCharm, you need to install it on your machine and create a specific Python environment.

Install Poetry

  1. Open Terminal (on macOS and Linux) or PowerShell (on Windows) and execute the following command:

    curl -sSL https://install.python-poetry.org | python3 —

    (Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py —

    curl -sSL https://install.python-poetry.org | python3 —

  2. On macOS and Windows, the installation script will suggest adding the folder with the poetry executable to the PATH variable. Do that by running the following command:

    export PATH=»/Users/jetbrains/.local/bin:$PATH»

    $Env:Path += «;C:UsersjetbrainsAppDataRoamingPythonScripts»; setx PATH «$Env:Path»

    Don’t forget to replace jetbrains with your username!

  3. To verify the installation, run the following command:

    poetry —version

    You should see something like Poetry (version 1.2.0).

Refer to the Poetry Installation Instructions for more details.

Create a Poetry environment

  1. Do one of the following:

    • Click the Python Interpreter selector and choose Add New Interpreter.

    • Press Ctrl+Alt+S to open Settings and go to . Click the Add Interpreter link next to the list of the available interpreters.

    • Click the Python Interpreter selector and choose Interpreter Settings. Click the Add Interpreter link next to the list of the available interpreters.

  2. Select Add Local Interpreter.

  3. In the left-hand pane of the Add Python Interpreter dialog, select Poetry Environment.

    creating a poetry environment

  4. The following actions depend on whether you want to create a new Poetry environment or to use an existing one.

    New Poetry environment
    • Select Poetry Environment.

    • Choose the base interpreter from the list, or click Choose the base interpreter and find the desired Python executable in your file system.

    • If PyCharm doesn’t detect the poetry executable, specify the following path in the Poetry executable field, replacing jetbrains with your username:

      /Users/jetbrains/Library/Application Support/pypoetry/venv/bin/poetry

      C:UsersjetbrainsAppDataRoamingpypoetryvenvScriptspoetry.exe

      /home/jetbrains/.local/bin/poetry

    Existing Poetry environment
    • Make sure that the project directory contains a pyproject.toml file.

    • Select Existing environment. Then expand the Interpreter list and choose the desired interpreter.

    • If the desired interpreter is not on the list, clickApp general ellipsis, and then browse for the Python executable within the previously configured Poetry environment.

    The selected Poetry environment will be reused for the current project.

  5. Click OK to complete the task.

If you select a poetry environment when creating a new Python project, PyCharm adds two files to your project:

  • pyproject.toml: specifies the project requirements

  • poetry.lock: records changes in the projects requirements

Each time you modify the pyproject.toml file, PyCharm notifies you and offers two actions: to record the changes in the poetry.lock file or to record the changes and install the unsatisfied requirements.

Lock or update poetry

Last modified: 09 December 2022

koxudaxi / poetry-pycharm-plugin
Goto Github
PK

View Code? Open in Web Editor
NEW

178.0
178.0
14.0
12.33 MB

A PyCharm plugin for poetry

Home Page: https://koxudaxi.github.io/poetry-pycharm-plugin/

License: Apache License 2.0

Kotlin 91.24%
Python 2.55%
Java 6.10%
HTML 0.11%
jetbrains
kotlin
lock
pip
plugin
poetry
poetry-pycharm-plugin
pycharm
pycharm-plugin
pyproject-toml
python
python-poetry

poetry-pycharm-plugin’s Introduction

Hi there 👋

  • I develop and contribute to OSS. I focus that improve the development environment😄
  • I got interviewed about pydantic-pycharm-plugin for JetBrains’ PyCharm Blog🎤
  • My poetry plugin has been merged into PyCharm source code🎉
    PyCharm 2021.3 or later provide poetry integration as a built-in feature😎
    👉What’s New in PyCharm 2021.3
  • I’m looking for sponsers to continue develpment!! 🚀

poetry-pycharm-plugin’s People

poetry-pycharm-plugin’s Issues

Poetry plugin prevents inspections to be visible in settings

Describe the bug
No inspections are visible in the settings window, we are presented with a blank page.
Disabling or removing the plugin fixes the problem.

Screenshots
2020-09-26

To Reproduce
Open Settings -> Editor -> Inspections

Expected behavior
Inspections settings should be visible.

Environments:

  • IDE: PyCharm Professional 2020.2.2
  • OS: Microsoft Windows 10 [Version 10.0.19041.508]
  • Poetry version: 1.0.10
  • Plugin version: 0.5.1

Marked is incompatible for PyCharm EAP while compatible

Describe the bug
Marked is incompatible for PyCharm EAP while compatible

To Reproduce
Steps to reproduce the behavior:

  1. Install pycharm EAP
  2. Install plugin manually (the marketplace will only install 1.0.3 which is broken)
  3. Restart pycharm

Expected behavior
Plugin to work without extra steps

Environments (please complete the following information):

  • IDE: PyCharm Professional 2021.1 (211.4961.30)
  • OS: Windows 10 20H2
  • Poetry Version: 1.1.4
  • Plugin version: 1.0.6

Additional context
Work around is to bump the version up in the plugin.xml file in the installed plugin

Having an unrestricted version available on GitHub would also be appreciated if you want to keep the restriction in the marketplace version

Version 1.0.4 throws NoSuchMethodError for TomlTableHeader.getKey()

Describe the bug
Every time I touch the pyproject.toml file (open it or modify a package version) I get the following exception:

java.lang.NoSuchMethodError: 'org.toml.lang.psi.TomlKey org.toml.lang.psi.TomlTableHeader.getKey()' at com.koxudaxi.poetry.PoetryExtrasLineMarkerContributor.getInfo(PoetryExtrasLineMarkerContributor.kt:20) at com.intellij.execution.lineMarker.RunLineMarkerProvider.getLineMarkerInfo(RunLineMarkerProvider.java:50) at com.intellij.codeInsight.daemon.impl.LineMarkersPass.queryProviders(LineMarkersPass.java:158) at com.intellij.codeInsight.daemon.impl.LineMarkersPass.lambda$doCollectInformation$3(LineMarkersPass.java:83) at com.intellij.codeInsight.daemon.impl.Divider.divideInsideAndOutsideInOneRoot(Divider.java:81) at com.intellij.codeInsight.daemon.impl.LineMarkersPass.doCollectInformation(LineMarkersPass.java:78) at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:56) at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$doRun$1(PassExecutorService.java:400) at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1137) at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$doRun$2(PassExecutorService.java:393) at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658) at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610) at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65) at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.doRun(PassExecutorService.java:392) at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$run$0(PassExecutorService.java:368) at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:172) at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:183) at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:366) at com.intellij.concurrency.JobLauncherImpl$VoidForkJoinTask$1.exec(JobLauncherImpl.java:188) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)

Environments (please complete the following information):

  • IDE: PyCharm Community 2020.3.3
  • OS: macOS 11.2
  • Poetry Version 1.1.4
  • Plugin version 1.0.4

Highlight package when a new version is available

Add package highlighting in pyproject.toml when a new version is available, in the same way that it’s done for requirements.txt:

Screenshot 2020-07-31 at 11 38 26

v1.0.5 Exception

Describe the bug
v1.0.5 Kills the run/debug configuration pane in Intellij

To Reproduce
Steps to reproduce the behavior:

  1. Go to ‘Run -> Edit Configurations…’
  2. Click on an existing python configuration
  3. Configuration Pane on the right handside of the window is blank
  4. Click on the «+» button, click on the Python option — nothing happens

Expected behaviour
I should be able to edit an existing python run/debug configs or, create new ones

Screenshots
image

Environments (please complete the following information):

  • IDE: Intellij Ultimate 2020.3.2
  • OS: Kubuntu 20.04
  • Poetry Version : 1.1.4
  • Plugin version 1.0.5

Additional context
The IDE reported the following exception from the plugin:

Stacktrace
com.intellij.diagnostic.PluginException: Cannot create class com.koxudaxi.poetry.PyProjectTomlWatcher [Plugin: com.koxudaxi.poetry]
	at com.intellij.serviceContainer.ComponentManagerImpl.instantiateClass(ComponentManagerImpl.kt:725)
	at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.instantiateClass(ExtensionComponentAdapter.java:51)
	at com.intellij.openapi.extensions.impl.XmlExtensionAdapter$SimpleConstructorInjectionAdapter.instantiateClass(XmlExtensionAdapter.java:133)
	at com.intellij.openapi.extensions.impl.ExtensionComponentAdapter.createInstance(ExtensionComponentAdapter.java:43)
	at com.intellij.openapi.extensions.impl.XmlExtensionAdapter.createInstance(XmlExtensionAdapter.java:69)
	at com.intellij.openapi.extensions.impl.ExtensionPointImpl.processAdapter(ExtensionPointImpl.java:472)
	at com.intellij.openapi.extensions.impl.ExtensionPointImpl.access$200(ExtensionPointImpl.java:37)
	at com.intellij.openapi.extensions.impl.ExtensionPointImpl$1.next(ExtensionPointImpl.java:367)
	at com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.forEachExtensionSafe(ExtensionProcessingHelper.java:27)
	at com.intellij.openapi.extensions.ExtensionPointName.forEachExtensionSafe(ExtensionPointName.java:49)
	at com.intellij.openapi.editor.impl.EditorFactoryImpl.createEditor(EditorFactoryImpl.java:203)
	at com.intellij.openapi.editor.impl.EditorFactoryImpl.createEditor(EditorFactoryImpl.java:157)
	at com.intellij.openapi.fileEditor.impl.text.TextEditorComponent.createEditor(TextEditorComponent.java:133)
	at com.intellij.openapi.fileEditor.impl.text.TextEditorComponent.<init>(TextEditorComponent.java:79)
	at com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl$PsiAwareTextEditorComponent.<init>(PsiAwareTextEditorImpl.java:107)
	at com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl.createEditorComponent(PsiAwareTextEditorImpl.java:85)
	at com.intellij.openapi.fileEditor.impl.text.TextEditorImpl.<init>(TextEditorImpl.java:52)
	at com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorImpl.<init>(PsiAwareTextEditorImpl.java:36)
	at com.intellij.openapi.fileEditor.impl.text.PsiAwareTextEditorProvider.createEditor(PsiAwareTextEditorProvider.java:31)
	at com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl.openFileImpl4Edt(FileEditorManagerImpl.java:891)
	at com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl.lambda$openFileImpl4$17(FileEditorManagerImpl.java:860)
	at com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl.runBulkTabChange(FileEditorManagerImpl.java:1680)
	at com.intellij.openapi.fileEditor.impl.FileEditorManagerImpl.lambda$openFileImpl4$18(FileEditorManagerImpl.java:859)
	at com.intellij.openapi.application.TransactionGuardImpl.runWithWritingAllowed(TransactionGuardImpl.java:216)
	at com.intellij.openapi.application.TransactionGuardImpl.access$200(TransactionGuardImpl.java:24)
	at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:199)
	at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822)
	at com.intellij.openapi.application.impl.ApplicationImpl.lambda$invokeAndWait$8(ApplicationImpl.java:476)
	at com.intellij.openapi.application.impl.LaterInvocator$1.run(LaterInvocator.java:126)
	at com.intellij.openapi.application.impl.FlushQueue.doRun(FlushQueue.java:85)
	at com.intellij.openapi.application.impl.FlushQueue.runNextEvent(FlushQueue.java:134)
	at com.intellij.openapi.application.impl.FlushQueue.flushNow(FlushQueue.java:47)
	at com.intellij.openapi.application.impl.FlushQueue$FlushNow.run(FlushQueue.java:190)
	at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
	at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:776)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:727)
	at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
	at java.base/java.security.AccessController.doPrivileged(Native Method)
	at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
	at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:746)
	at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:976)
	at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:843)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:454)
	at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:773)
	at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$9(IdeEventQueue.java:453)
	at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822)
	at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:501)
	at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
	at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
	at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Caused by: java.lang.reflect.InvocationTargetException
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
	at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
	at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
	at com.intellij.serviceContainer.ComponentManagerImpl.instantiateClass(ComponentManagerImpl.kt:684)
	... 52 more
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.koxudaxi.poetry.PoetryKt
	at com.koxudaxi.poetry.PyProjectTomlWatcher.<init>(poetry.kt:430)
	... 57 more

Fails to Complete `pyproject.toml` Analysis

Describe the bug
Poetry plugin fails «Analyzing…» pyproject.toml in PyCharm Professional 2020.3.3

To Reproduce

  1. Navigate to pyproject.toml
  2. Allow plugin to do analysis.
  3. PyCharm exception window.

Expected behavior
No exception to be thrown.

Screenshots
image

Environments (please complete the following information):

  • IDE: PyCharm Professional 2020.3.3
  • OS: Ubuntu 20.10
  • Poetry Version: 1.1.4
  • Plugin version: 1.0.3

Additional context
Stacktrace:

java.lang.NoSuchMethodError: 'java.util.List org.toml.lang.psi.TomlTableHeader.getNames()'
	at com.koxudaxi.poetry.PoetryExtrasLineMarkerContributor.getInfo(PoetryExtrasLineMarkerContributor.kt:20)
	at com.intellij.execution.lineMarker.RunLineMarkerProvider.getLineMarkerInfo(RunLineMarkerProvider.java:50)
	at com.intellij.codeInsight.daemon.impl.LineMarkersPass.queryProviders(LineMarkersPass.java:158)
	at com.intellij.codeInsight.daemon.impl.LineMarkersPass.lambda$doCollectInformation$3(LineMarkersPass.java:83)
	at com.intellij.codeInsight.daemon.impl.Divider.divideInsideAndOutsideInOneRoot(Divider.java:81)
	at com.intellij.codeInsight.daemon.impl.LineMarkersPass.doCollectInformation(LineMarkersPass.java:78)
	at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:56)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$doRun$1(PassExecutorService.java:400)
	at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1137)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$doRun$2(PassExecutorService.java:393)
	at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:658)
	at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:610)
	at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:65)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.doRun(PassExecutorService.java:392)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.lambda$run$0(PassExecutorService.java:368)
	at com.intellij.openapi.application.impl.ReadMostlyRWLock.executeByImpatientReader(ReadMostlyRWLock.java:172)
	at com.intellij.openapi.application.impl.ApplicationImpl.executeByImpatientReader(ApplicationImpl.java:183)
	at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:366)
	at com.intellij.concurrency.JobLauncherImpl$VoidForkJoinTask$1.exec(JobLauncherImpl.java:188)
	at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290)
	at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020)
	at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656)
	at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594)
	at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:183)

A slightly modified sample pyproject.toml:

[tool.poetry]
name = "Sample"
version = "0.1.0"
description = ""
authors = ["Cooper Pellaton <[email protected]>"]

[tool.poetry.dependencies]
python = "^3.9"
pymongo= { version = "^3.11.2", extras = [ "srv" ] }
google-cloud-logging = "^2.0.1"
tqdm = "^4.54.0"
celery = "^5.0.2"
pandas = "^1.1.4"
Flask-RESTful = "^0.3.8"
nltk = "^3.5"
mock = "^4.0.2"
requests = "^2.25.0"
Flask = "^1.1.2"
gunicorn = "^20.0.4"
google-cloud-storage = "^1.33.0"
supervisor = "^4.2.1"
gevent = "^20.9.0"
pylint = "^2.6.0"
redis = "^3.5.3"
freezegun = "^1.0.0"
pytest = "^6.2.2"
pytest-cov = "^2.11.1"
pyspellchecker = "^0.5.6"

[tool.poetry.dev-dependencies]
autopep8 = "^1.5.4"
ipython = "^7.19.0"

[tool.pytest.ini_options]
minversion = "6.0"
addopts = "-ra -q -p no:nose2pytest"
testpaths = [
    "test"
]

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

Virtual Environment Creation Failed with ModuleNotFound Exception

Hi
I am getting following error while trying to create virtual environment using poetry plugin:
Screen Shot 2020-09-25 at 2 47 25 PM

Environments (please complete the following information):

  • IDE: PyCharm 2020.2 Prof
  • OS: MacOS Majove
  • Poetry Version : 1.1.0b4
  • Plugin version: 0.5.0

Support remote host

PyCharm doesn’t support creating an environment for the remote hosts with the third-party plugin.
We need the feature when creating an environment like docker, WSL.

PyCharm team will support the feature.

Related Issues

#106
#151
#58

«Failed To Create Interpreter» on Windows

When trying to add a Poetry Environment python interpreter, I’m getting the following error:

Cannot run program "C:Usersisrael.tsadok.poetrybinpoetry" (in directory "C:Usersisrael.tsadokcodetestpoet"): CreateProcess error=193, %1 is not a valid Win32 application

To Reproduce

On Windows:

  1. Click the python interpreter button on the bottom right corner of PyCharm
  2. Click «Add Interpreter…»
  3. Choose «Poetry Environment» on the left-hand side
  4. Choose «Python 3.9» as base environment
  5. Click OK

Environment:

  • IDE: PyCharm Community 2020.3
  • OS: Windows 10 (Build 20279.1)
  • Poetry Version: 1.1.4
  • Plugin version: 1.0.2

Support poetry errors

This plugin should treat errors of poetry commands.
Screenshot_2020-05-15_23-17-17

Version 1.0 [extension points compatible] Relase

Version 1.0 should support the same features as other Python Interpreter(example: pipenv) with extension points.

This issue would be updated after version 0.1 is released.

TODO

  • freeze a list of features
  • impliment required functions for extension points
  • test

Features

extension points

We must list the extension points that will implement.

Extension points

Plugin Poetry v0.5.2 is incompatible with last version of IntelliJ

Describe the bug
The Poetry plugin v0.5.2 does not appear on the IntelliJ marketplace. v0.1.3 does appear.

I tried to install it manually and IntelliJ threw the next error:

Plugin 'Poetry' version 0.5.2 is incompatible with this installation: since build 202.7319.64 > IU-202.7319.50

To Reproduce
Steps to reproduce the behavior:

  1. Using IntelliJ 2020.2.2, build 202.7319.50
  2. Download Poetry 0.5.2
  3. Go to Plugins > ⋮ > Install plugin from disk
  4. Select poetry plugin
  5. See error

Expected behavior

  1. The last version of the plugin should show up in the maketplace. It doesn’t.
  2. Should be able to install the last version manually.

Screenshots
demo

Environments (please complete the following information):

  • IDE: IntelliJ 2020.2.2, build 202.7319.50
  • OS: Windows 10 v2004
  • Poetry Version 1.1.0
  • Plugin version 0.5.2

Wrong system interpreter icon in settings

Describe the bug
System interpreter icon is wrong. System interpreter is shown with virtualenv-like icon (i.e. python logo with V) instead of system icon (plain python logo).

To Reproduce
Steps to reproduce the behavior:

  1. Go to Interpreter Settings
  2. Add a System Interpreter
  3. Open Interpreter settings again and notice System Interpreter icon

Expected behavior
A system interpreter should have a plain python icon, not a virtualenv-like icon (see screenshots below). First screenshot is without the plugin and second screenshot (with the wrong icon) is with the plugin.

Screenshots
icon1
Correct system interpreter icon (plugin disabled)

icon2
Wrong system interpreter icon (plugin enabled)

Environments (please complete the following information):

  • IDE: PyCharm Professional 2020.2.3
  • OS: Microsoft Windows 10 [Version 10.0.19041.508]
  • Poetry version: 1.1.2
  • Plugin version: 0.5.3

Show Python Version in Interpreter Name

Is your feature request related to a problem? Please describe.
I cannot tell which interpreter to use for a given version of python. Because the version appears at the end of the string for poetry interpreters and pycharm uses the beginning of the string, the interpreter names end up being something like this.

Poetry (project-name)
Poetry (project-name) (2)
Poetry (project-name) (3)

Describe the solution you’d like
I would like the auto-generated name of the environment to include the python version.

Desired outcome would be something like the following.
Poetry (project-name-3.6)
Poetry (project-name-3.7)
Poetry (project-name-3.8)

Describe alternatives you’ve considered
Manually editing the name after interpreter creation is not easy using the pycharm UI because it shows all interpreters for all projects in the same form. I cannot set the interpreter name at the time of creation.

Additional context
I am using poetry with pyenv on a linux machine.

Version 0.5 [extension points partial compatible] Relase

Version 0.5 should support extension points on PyCharm 2020.2.2.

I would implement two classes for extension points.

  • PySdkProvider
  • PyPackageManagerProvider

Poetry Version

Poetry version 1.1.0b3

Related Issues

python-poetry/poetry#2711

TODO

  • implemention
  • test
  • documentation

Implemention

  • PySdkProvider
  • PyPackageManagerProvider

Test

use-cases

  • add new poetry Interpreter with install packages from pyproject.toml
  • add new poetry Interpreter without install packages from pyproject.toml
  • add new poetry interpreter without existing environment
  • add new poetry interpreter from the existing environment
  • lock file from a popup after changing pyproject.toml
  • update file from a popup after changing pyproject.toml
  • install new packages from a notification after the lock file is updated
  • install packages from action of installation (alt+enter)
  • run scripts
  • install/uninstall packages from settings (GUI)
  • open project that is created by old version poetry plugin.

Create poetry environment when starting a new project

When creating new project, there are only three options to create new environment:

  • Virtualenv
  • Pipenv
  • Conda

Is it possible to add Poetry in this list or it would require additional API on PyCharm side?

image

Temporary workaround

Create project with existing python interpreter and then create poetry environment

Exception in Poetry plugin for Pycharm

Describe the bug
Upon updating the Poetry plugin for Pycharm I get an exception:

1/2

java.lang.NoClassDefFoundError: org/toml/lang/psi/TomlTableHeader at com.koxudaxi.poetry.PoetryKt.tomlTableHeaderHasKey(poetry.kt:721) at com.koxudaxi.poetry.PoetryKt.<clinit>(poetry.kt:722) at com.koxudaxi.poetry.PoetrySdkProvider.getSdkAdditionalText(PoetrySdkProvider.kt:59) at com.jetbrains.python.sdk.PySdkRenderingKt.name(PySdkRendering.kt:31) at com.jetbrains.python.sdk.PySdkRenderingKt.name(PySdkRendering.kt:18) at com.jetbrains.python.sdk.PySdkPopupFactory$Companion.nameInPopup(PySdkPopupFactory.kt:29) at com.jetbrains.python.sdk.PySdkPopupFactory$Companion.descriptionInPopup(PySdkPopupFactory.kt:36) at com.jetbrains.python.configuration.PySdkStatusBar.getWidgetState(PySdkStatusBar.kt:75) at com.intellij.openapi.wm.impl.status.EditorBasedStatusBarPopup.lambda$update$2(EditorBasedStatusBarPopup.java:266) at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238) at com.intellij.util.Alarm$Request.runSafely(Alarm.java:376) at com.intellij.util.Alarm$Request.run(Alarm.java:362) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) at com.intellij.util.concurrency.SchedulingWrapper$MyScheduledFutureTask.run(SchedulingWrapper.java:220) at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:201) at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822) at com.intellij.openapi.application.impl.ApplicationImpl.lambda$invokeLater$4(ApplicationImpl.java:324) at com.intellij.openapi.application.impl.FlushQueue.doRun(FlushQueue.java:85) at com.intellij.openapi.application.impl.FlushQueue.runNextEvent(FlushQueue.java:134) at com.intellij.openapi.application.impl.FlushQueue.flushNow(FlushQueue.java:47) at com.intellij.openapi.application.impl.FlushQueue$FlushNow.run(FlushQueue.java:190) at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313) at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:776) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:727) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:746) at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:976) at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:843) at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:454) at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:773) at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$9(IdeEventQueue.java:453) at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822) at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:501) at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90) Caused by: java.lang.ClassNotFoundException: org.toml.lang.psi.TomlTableHeader PluginClassLoader[PluginDescriptor(name=Poetry, id=com.koxudaxi.poetry, path=/Users/milkman/Library/Application Support/JetBrains/PyCharmCE2020.3/plugins/poetry-pycharm-plugin, version=1.0.5)] [email protected] at com.intellij.ide.plugins.cl.PluginClassLoader.loadClass(PluginClassLoader.java:129) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ... 42 more

2/2

java.lang.NoClassDefFoundError: Could not initialize class com.koxudaxi.poetry.PoetryKt at com.koxudaxi.poetry.PoetryConfigLoader$runActivity$1.run(PoetryConfigLoader.kt:24) at com.intellij.openapi.project.DumbServiceImpl.lambda$smartInvokeLater$9(DumbServiceImpl.java:526) at com.intellij.openapi.application.TransactionGuardImpl.runWithWritingAllowed(TransactionGuardImpl.java:216) at com.intellij.openapi.application.TransactionGuardImpl.access$200(TransactionGuardImpl.java:24) at com.intellij.openapi.application.TransactionGuardImpl$2.run(TransactionGuardImpl.java:199) at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822) at com.intellij.openapi.application.impl.ApplicationImpl.lambda$invokeLater$4(ApplicationImpl.java:324) at com.intellij.openapi.application.impl.FlushQueue.doRun(FlushQueue.java:85) at com.intellij.openapi.application.impl.FlushQueue.runNextEvent(FlushQueue.java:134) at com.intellij.openapi.application.impl.FlushQueue.flushNow(FlushQueue.java:47) at com.intellij.openapi.application.impl.FlushQueue$FlushNow.run(FlushQueue.java:190) at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313) at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:776) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:727) at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721) at java.base/java.security.AccessController.doPrivileged(Native Method) at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:746) at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:976) at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:843) at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$8(IdeEventQueue.java:454) at com.intellij.openapi.progress.impl.CoreProgressManager.computePrioritized(CoreProgressManager.java:773) at com.intellij.ide.IdeEventQueue.lambda$dispatchEvent$9(IdeEventQueue.java:453) at com.intellij.openapi.application.impl.ApplicationImpl.runIntendedWriteActionOnCurrentThread(ApplicationImpl.java:822) at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:501) at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

To Reproduce
Steps to reproduce the behavior:

  1. Update Poetry 1.0.4 -> 1.0.5

Environments (please complete the following information):

  • IDE: Pycharm 2020.3.3
  • OS: macOS 10.13.6
  • Poetry Version 1.1.4
  • Plugin version 1.0.5

Additional context
I’m a noob so can’t provide more info because I’m not sure what else to provide/how to provide it.

Dependabot couldn’t authenticate with https://pypi.python.org/simple/

Recognize existing environments from existing projects?

Hi! Loving the plugin! Thanks for taking the effort to build it.

I would like to suggest that a differentiation can be made between creating a new or adding an existing environment, so that we can register poetry environments that were created prior to installing the plugin, in the same manner you can do that with a Conda or Virtualenv environment.

Set source roots when multiple packages specified

Poetry itself supports nonstandard project setups where potentially multiple packages are included in one distribution: https://python-poetry.org/docs/pyproject/#packages. Maybe this plugin can use that information to automatically set up sources roots.

Ability to change where a new env is generated/move already existing venv

Would it be possible to change the location of the venv that is created and/or move the location of a previously created venv?

Create env on remote hosts

Ability to create an env on the remote host

error when adding interpreter

I am trying to install a new interpreter in pycharm with this plugin on windows 10 home with pycharm 2020.1. I am missing fields that you show in your screenshot and I get an error when trying to point to poetry.bat.

image

WSL python support

Support building poetry environments with WSL.

I am guessing that this would require remote interpreter support by design.

Support installing extras packages

This plugin install packages which are only dependencies or dev-dependencies
But, a general project has extras packages.
I want to install it with an install button on the editor(like run/debug button)

Wrong warning: Package containing module is not listed in project requirements

I noticed that with PyCharm 2020.2.3 and the poetry plugin 0.53 I get warnings that packages are not listed in the requirements.
For example a very simple environment where I just installed selenium:

❯ poetry update
Creating virtualenv ... /.cache/pypoetry/virtualenvs
Updating dependencies
Resolving dependencies... (0.1s)


Package operations: 2 installs, 0 updates, 0 removals

  - Installing urllib3 (1.25.10)
  - Installing selenium (3.141.0)

Gives me the warning:
image

I even added a requirements.txt but that did not help. If I switch to a non poetry interpreter like the System Interpreter the warning vanishes.
I really don’t like warning and even more I don’t like to add comments just to silence them. Is this a known bug or something specific to my environment?

Kind regards,
Alex

Poetry Script support

Is your feature request related to a problem? Please describe.
You have to open a shell to exec poetry run script-a

Describe the solution you’d like
I would like to have pycharm to recognize [tool.poetry.scripts] as Run Configurations like NPM scripts area.

poetry plugin recommendation

Python version dependency in pyproject.toml breaks poetry for modified Python versions

Describe the bug
Trying to create a new interpreter on Debian with python3.9 generates invalid pyproject.toml

To Reproduce
Steps to reproduce the behavior:

  1. Install python3.9 on Debian.
  2. Try to generate a virtualenv based on that
  3. Error:
ParseConstraintError

  Could not parse version constraint: ^3.9.1+

  at ~/.poetry/lib/poetry/_vendor/py3.6/poetry/core/semver/__init__.py:164 in parse_single_constraint
      160│         else:
      161│             return version
      162│ 
      163│     raise ParseConstraintError(
    → 164│         "Could not parse version constraint: {}".format(constraint)
      165│     )
      166│ 

This is because the version of the Debian Python is 3.9.1+ and that gets put in the deps:

[tool.poetry.dependencies]
python = "^3.9.1+"

Expected behavior
poetry init suggests ^3.9, that’s probably a more sensible value.

Environments (please complete the following information):
Python 3.9 is only available on testing/sid, but it should still work.

Updating to 2020.3 EAP downgrades poetry plugin

Describe the bug
After updating to 2020.3 EAP version 0.5 of the plugin disappears from the marketplace.

Interestingly enough, it appears that all features of 0.5 work. The package manger UI is filled correctly as is the virtualenv integration.

To Reproduce
Steps to reproduce the behavior:

  1. Install plugin on 2020.2
  2. Make version 0.5.0 a required plugin
  3. Upgrade to 2020.3 EAP
  4. See error «version 0.5 is required but 0.1.2 is installed»

Expected behavior
The correct version should be available

Screenshots
image
image

Environments (please complete the following information):

  • IDE: IntelliJ IIntelliJ IDEA 2020.3 EAP (Ultimate Edition), Build #IU-203.3645.34, built on September 21, 2020
  • OS: running in WSL (ArchLinux) on Windows 10
  • Poetry Version 1.0.10
  • Plugin version 0.5?

Version 0.1 [minimum features] Release

Version 0.1 should support minimum features without extension points.

I would cover the common use-case in this version.

TODO

  • freeze a list of features
  • documentation
  • improve contribution guideline
  • test for common use-case

Features

  • add a new/existing poetry environment as an interpreter
  • install packages with pyproject.toml when adding an interpreter
  • add a new pyproject.toml when it does not exists
  • install and import a package with poetry (QuickFix)
  • install packages from poetry.lock
  • update and lock with a popup
  • show a message and a link to fix settings (QuickFix)
  • install extras by clicking a line marker (Toml plugin is required)

Test

use-cases

  • add new poetry Interpreter with install packages from pyproject.toml
  • add new poetry Interpreter without install packages from pyproject.toml
  • add new poetry interpreter from existing enviroment
  • lock file from a popup after changing pyproject.toml
  • update file from a popup after changing pyproject.toml
  • install new packages from a notification after lock file is updated
  • install packages from action of installation (alt+enter)

1.0.3: failure on creating environment via python3 version not from PATH

Describe the bug
Plugin uses python3 path from PATH not from ‘create poetry dialog’ and could fail on multiple Python3 version installed.

To Reproduce
Steps to reproduce the behavior:

  1. macos
  2. have three versions of Python3 installed on machine: 3.6, 3.7, 3.8 with 3.7 as default:
$ which python3
/usr/local/bin/python3

$ /usr/local/bin/python3 -V
Python 3.7.9

$ which -a python3
/usr/local/bin/python3
/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
/Library/Frameworks/Python.framework/Versions/3.8/bin/python3
  1. install poetry on every Python3 version via ‘path/../python3 -m pip install poetry==1.1.4’
  2. open project with python version required as «^3.8» in Pycharm 2020.3.3 with Poetry plugin v1.0.3

Expected behavior
created poetry environment

Screenshots
2021-02-03_05-20-35
2021-02-03_05-21-26
If applicable, add screenshots to help explain your problem.

Environments (please complete the following information):
Already done above.
It might be helpful to move this section to the top of the form.

Additional context
Full text from error window:

executed command

/Library/Frameworks/Python.framework/Versions/3.8/bin/poetry env use /usr/local/bin/python3


  NoCompatiblePythonVersionFound

  The specified Python version (3.7.9) is not supported by the project (^3.8).
  Please choose a compatible version or loosen the python constraint specified in the pyproject.toml file.

  at /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/poetry/utils/env.py:675 in create_venv
       671│             # If an executable has been specified, we stop there
       672│             # and notify the user of the incompatibility.
       673│             # Otherwise, we try to find a compatible Python version.
       674│             if executable:
    →  675│                 raise NoCompatiblePythonVersionFound(
       676│                     self._poetry.package.python_versions, python_patch
       677│                 )
       678│ 
       679│             io.write_line(

Document features

add documents include screen captures (GIF animation) on each feature

Support for pydantic-like models?

Hi, I’m using your plugin for quite some time and it’s awesome — thanks for your work! :)

I’m developing ormar — a mini async orm with fastapi in mind, that uses pydantic for validation (https://github.com/collerek/ormar)

I’m subclassing the pydanic.BaseModel as my ormar.Model and hacking around with pydantic internals to make it work.
(You can ignore Meta class below, the field definition is like in pydantic but I use my custom fields classes as type hints — id and name in example).

image
It does kind of work, but in example above it shows Base clases of my fields, and I would like to display user=User(id: Integer, name: String), or even better -> user=User(id:int, name:str)

I’m already playing with __annotations__, pydantic fields shape, type_ and a lot of internals, so I would like to adjust my models/ fields to play well with your plugin.

But for that I need information from where do you grab the information to display in code completion, hints etc.

I’m also exposing QuerySet operations like User.objects.create(**kwargs) or User.objects.update(**kwargs) that as kwargs should accept only pydantic/ormar fields -> can you somehow register a custom function to be picked up by your plugin, or make it work in other way (so display hints like in __init__()).

I tried looking into your code but saw a huge number of jetbeans dependencies and I don’t even know kotlin :D

So would be really grateful for info how I can adjust my project to be more in line with your plugin, as I find it super useful.

Thanks in advance and sorry for the long text.

Error creating a new project

Describe the bug
When I try to create a new flask project with poetry as its enviroment I get the following error.
Running the command myself in my user directory I get this error:
[RuntimeError] Poetry could not find a pyproject.toml file in C:UsersMax or its parents
I assume PyCharm is not setting the working directory correctly when running the command

Environments (please complete the following information):

  • IDE: PyCharm 2020.2.3 (Professional Edition) Build #PY-202.7660.27, built on October 6, 2020
  • OS: Windows 10
  • Poetry Version 1.0.10
  • Plugin version 0.5.3

Release roadmap

Release schedule

Version release issue detail code status target date
0.0.x experimental phase released
0.1 #55 minimum features released 2020/07/27
0.5 #109 minimum features released 2020/09/22
1.0 #56 extension points compatible released 2020/12/11
1.1 #182 support EAP 211 pushed (waiting for approval by Jetbrains) 2021/02/xx
1.5 support remote host #152 2021/xx/xx

`Install Packages` is in `Open Recent` menu

Install Packages is in Open Recent menu.
It’s invalid content.

Project Policy

I describe project policy in a document.

Support PyCharm 2020.3

PyCharm 2020.3 will be released that has a new feature for PythonSDK
This plugin will support it.

TODO

Implement

  • com.jetbrains.python.sdk.configuration.PyProjectSdkConfigurationExtension
    (Pythonid.projectSdkConfigurationExtension)

Related Issues

https://youtrack.jetbrains.com/issue/PY-44743

Project dependency detection via pyproject.toml

So, say I have the following folder structure:

root/
    library/
        poetry.lock
        pyproject.toml
    dependency/
       poetry.lock
       pyproject.toml

I would attach root/library and root/dependency as individual Pycharm projects — each with their own Poetry environments.

However, these projects can also depend on each other:

#root/library/pyproject.toml
...

[tool.poetry.dependencies]
dependency = {path = "../dependency", develop = true}

While this all works pretty well, I still need to go into Preferences -> Project -> Project Dependencies and specify how these projects depend on one another manually. Is it possible for the Poetry plugin to detect these dependencies and automatically configure the Preferences -> Project -> Project Dependencies panel accordingly?

If it’s possible (I’m unfamiliar with the Pycharm plugin APIs and would have to look around) and there’s interest, I’d love to contribute a PR to support this as it’d be really useful in my opinion.

Unable to create venv via plugin.

Describe the bug
I am trying to create new venv via poetry and getting this error

Installing dependencies from lock file

PackageInfoError

Unable to determine package info for path: /tmp/pypoetry-git-rembg-forkwsEl10

Fallback egg_info generation failed.

Command ['/tmp/tmp_ogNPR/.venv/bin/python', 'setup.py', 'egg_info'] errored with the following return code 1, and output: 
Traceback (most recent call last):
  File "setup.py", line 1, in <module>
    import pathlib
ImportError: No module named pathlib

/home/sapiosexual/.poetry/lib/poetry/_vendor/py2.7/subprocess32.py:149: RuntimeWarning: The _posixsubprocess module is not being used. Child process reliability may suffer if your program uses threads.
  "program uses threads.", RuntimeWarning)

Python 2.7 will no longer be supported in the next feature release of Poetry (1.2).
You should consider updating your Python version to a supported one.

Note that you will still be able to manage Python 2.7 projects by using the env command.
See https://python-poetry.org/docs/managing-environments/ for more information.

I am perfectly sure I have installed poetry for python3. I am using Python3.8 as base interpreter. I am able to create new venv using terminal.

To Reproduce
Steps to reproduce the behavior:

  1. Go to settings ctrl + alt + s.
  2. Click on Project
  3. Click on Project Interpreter
  4. Click on gear wheel
  5. Click on Add
  6. Click on Poetry Environment
  7. Choose Location and base interpreter
  8. Click on Ok
  9. See error

Expected behavior
Brand new venv with installed dependencies.

Environments (please complete the following information):

  • IDE: PyCharm 2020.3 (Professional Edition)
    Build #PY-203.5981.165, built on December 18, 2020
    Runtime version: 11.0.9+11-b1145.21 amd64
    VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
    Linux 5.4.0-58-generic
  • OS: Ubuntu Ubuntu 20.04.1 LTS
  • Poetry Version 1.1.4
  • Plugin version 1.0.1

poetry lock with «—no-update»

When I edit my dependencies in pyproject.toml, I normally want to run poetry lock --no-update, rather than just poetry lock.

The plugin UI does not provide a way to do this:

Screenshot from 2020-12-30 01-01-13

Do you think it would be useful to add an option to use --no-update, when the user clicks on «poetry lock»?

Many thanks!

Repair of Broken Env

It is possible to get into an repairable state if the current interpreter is deleted. I found this while trying out the plugin and deciding to switch from in-project to not in-project.

Steps to reproduce:

  1. Configure poetry to use an in-project environment.
poetry config virtualenvs.in-project true
  1. Create interpreter using the plugin pointing to a pyenv base interpreter (e.g. ~/.pyenv/versions/3.6.10/bin/python).
  2. Delete the in project environment.
  1. Configure poetry to not use an in project environment.
poetry config --unset virtualenvs.in-project
  1. Try to recreate the environment using the plugin. The current environment is listed as invalid. However, the add python interpreter dialogue reads «Poetery (sic) interpreter has been already added, select .» Therefore, there is no way out of this state.

Support PyCharm 2021.1

Add poetry logo

PyCharm can show a log for the package manager plugin.
The places are Plugin Market and config panels of Interpreter. I attached the screenshots examples at the end of the issue.

@abn
Can we use the official poetry log in this plugin?
I couldn’t find the license of the logo and the original image.
if we can’t use the image then I close this issue.

Screenshot_2020-10-04_04-19-06
Screenshot_2020-10-04_04-18-38

Creating new project interpreter does not work on windows

Attempting to add a new project interpreter it goes through the motions then gives the error «Directory C:UsersXXXAppDataLocalpypoetryCachevirtualenvssample-poetry-app-FpOpy9hG-py3.8
binpython not found».

The environment does get created but the path to python instead is:
C:UsersXXXAppDataLocalpypoetryCachevirtualenvssample-poetry-app-FpOpy9hG-py3.8Scriptspython.exe

Python bases attempted: 3.8.3 and 3.7.3
poetry version: 1.0.6
OS: Windows 10
PyCharm: 2020.1.2 Profession Edition

No reaction starting a new project

Describe the bug
Start pycharm click to add a new project nothing happens.
Same is behaviour in Linux and Windows.
Poetry is currently the only plugin.

Screenshots
image

Environments (please complete the following information):

  • IDE: PyCharm Community 2020.3.3-1
  • OS: ArchLinux or Windows 10
  • Poetry Version 1.1.4
  • Plugin version 1.0.5

Virtualenv gets deleted when I enable Poetry plugin

Describe the bug

Whenever I start IDEA with the Poetry plugin enabled, it starts indexing the virtualenv and within seconds the whole $VIRTUAL_ENV directory gets completely removed. No new virtualenv is created in its place. This only occurs in one project though.

  1. IDEA complains «Invalid Python interpreter selected for the module».
  2. I restore the virtualenv from backup
  3. When I click on the «Configure Python Interpreter» on IDEA’s notification, immediately it starts deleting files, which takes a few seconds until completely removed.
  4. Go to 1

This started occurring in within the last week, I performed a ‘brew update’ and update to IDEA plugins. Until then I had been using the Poetry plugin without issues.

Disabling the Poetry plugin solves this issue.

I am not sure how to debug this further, nothing relevant appears in idea.log file. Is it possible to log all commands that the Poetry plugin invokes?

Environments (please complete the following information):

  • IDE: IntelliJ IDEA 2020.3.1 (Ultimate Edition)
  • OS: macOS 10.15.7
  • Poetry Version 1.1.4
  • Plugin version 1.0.1

java.util.MissingResourceException: Can’t find bundle for base name messages.PoetryPsiBundle

To Reproduce
Steps to reproduce the behavior:

  1. Start PyCharm with a project opened
  2. Wait for the IDE to initialise
  3. Observe the red exclamation mark error in the right corner of the status bar, the exception is:
java.util.MissingResourceException: Can't find bundle for base name messages.PoetryPsiBundle, locale ru_RU
	at java.base/java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:2055)
	at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1689)
	at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1593)
	at java.base/java.util.ResourceBundle.getBundle(ResourceBundle.java:1284)
	at com.intellij.AbstractBundle.getResourceBundle(AbstractBundle.java:156)
	at com.intellij.AbstractBundle.getResourceBundle(AbstractBundle.java:143)
	at com.intellij.codeInspection.InspectionEP.getLocalizedString(InspectionEP.java:200)
	at com.intellij.codeInspection.InspectionEP.getGroupDisplayName(InspectionEP.java:61)
	at com.intellij.codeInspection.InspectionEP.getGroupPath(InspectionEP.java:132)
	at com.intellij.codeInspection.ex.InspectionToolWrapper.getGroupPath(InspectionToolWrapper.java:156)
	at com.intellij.codeInspection.ex.InspectionSearchableOptionContributor.processOptions(InspectionSearchableOptionContributor.java:40)
	at com.intellij.ide.ui.search.SearchableOptionsRegistrarImpl.lambda$initialize$1(SearchableOptionsRegistrarImpl.java:131)
	at com.intellij.openapi.extensions.impl.ExtensionProcessingHelper.forEachExtensionSafe(ExtensionProcessingHelper.java:33)
	at com.intellij.openapi.extensions.ExtensionPointName.forEachExtensionSafe(ExtensionPointName.java:49)
	at com.intellij.ide.ui.search.SearchableOptionsRegistrarImpl.initialize(SearchableOptionsRegistrarImpl.java:131)
	at com.intellij.openapi.options.newEditor.SettingsFilter.lambda$new$1(SettingsFilter.java:53)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
	at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:668)
	at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1$1.run(Executors.java:665)
	at java.base/java.security.AccessController.doPrivileged(Native Method)
	at java.base/java.util.concurrent.Executors$PrivilegedThreadFactory$1.run(Executors.java:665)
	at java.base/java.lang.Thread.run(Thread.java:834)

Environments (please complete the following information):

  • IDE: PyCharm Pro 2020.3 EAP 1
  • Plugin version: 0.5.1

Additional context

It seems there is an unresolved reference to this bundle in:

<localInspection language=«TOML« enabledByDefault=«true« implementationClass=«com.koxudaxi.poetry.PoetryVersionInspection« displayName=«Poetry Package versions« bundle=«messages.PoetryPsiBundle« groupKey=«INSP.GROUP.python« suppressId=«PoetryPackageVersion«/>

Recommend Projects

  • React photo
    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo
    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo
    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo
    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo
    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo
    Laravel

    A PHP framework for web artisans

  • D3 photo
    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo
    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo
    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo
    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo
    Alibaba

    Alibaba Open Source for everyone

  • D3 photo
    D3

    Data-Driven Documents codes.

  • Tencent photo
    Tencent

    China tencent open source team.

CI

JetBrains IntelliJ Plugins
license

A JetBrains PyCharm plugin for poetry.

This plugin has been merged into PyCharm source code🎉🔗

PyCharm 2021.3 or later provide poetry integration as a built-in feature😎

👉What’s New in PyCharm 2021.3

If you have any questions then please crate an issue on JetBrains youtrack

JetBrains maintains the poetry feature in PyCharm.

JetBrains

Demo🔗

poetry_demo1

Quick Installation🔗

The plugin is in JetBrains repository (Poetry Plugin Page)

You can install the stable version on PyCharm’s Marketplace (Preference -> Plugins -> Marketplace) Official Document

I recommend PyCharm 2020.3 and the plugin version 1.0 or later to get all features and performance.

search plugin

Features🔗

Implemented🔗

  • add a new/existing poetry environment as a interpreter
  • install packages with pyproject.toml when add a interpreter
  • add a new pyproject.toml when it does not exists
  • install and import a package with poetry (QuickFix)
  • install packages from poetry.lock
  • update and lock with a popup
  • show a message and a link to fix settings (QuickFix)
  • install extras and run scripts by clicking a line marker (Toml plugin is required)
  • show a message for outdated version packages (Toml plugin is required)
  • install/uninstall packages from GUI
  • detect poetry project when open new project

Motivation🔗

Poetry is a popular package manager of python.

However, PyCharm doesn’t support poetry.

This plugin support poetry. This source code was forked from the Pipenv integration code in IntelliJ-community.

In this issue PY-30702, the feature is discussing. But, We need time to get the proper functionality in PyCharm.

The plugin has useful features like installing from poetry.lock.(you can watch demo video)

However, The feature is limited. PyCharm has to provided extension points for perfect features.

I guess if the plugin be used a lot of people, then JetBrains developers will implement extension points or poetry integration in PyCharm.

This project is currently in an experimental phase🔗

~~This plugin supports minimum features to use poetry in PyCharm.~~

~~There is feature restrictions.~~

~~But, PyCharm team will add a few api to resolve the problem. The detail is in this issue.~~

PyCharm provides APIs that are for third-party package manager plugins.

The project needs any feedback and PRs. We’re waiting for your feedback and PRs.

Feature Restrictions🔗

The plugin can’t provide some features for technical reasons.

Because PyCharm has not provided APIs to support third-party python package managers yet. (a.k.a extension points)

We will be able to implement the following features when JetBrains add extension points to PyCharms.

  • ~~Create a new environment when creating a new project.~~
  • Use the Custom Icon for poetry. (Coming Soon)
  • ~~Install/uninstall a package from GUI(settings)~~
  • And more.

Screen Shots🔗

add_package
new_sdk
installed_package
run_config
update_lock
quick_fix
install_from_lock_file
install_extras

Contribute🔗

We are waiting for your contributions to poetry-pycharm-plugin.

Links🔗

  • A JetBrains PyCharm plugin for pydantic.
  • I got interviewed about creating a plugin for JetBrains’ PyCharm Blog.

Содержание

  1. Как добавить интерпретатор `Python 3.x` в Pycharm
  2. 3 ответа
  3. Configure a Python interpreter
  4. Python interpreters in PyCharm
  5. Setting an existing Python interpreter
  6. Change the Python interpreter using the Python Interpreter selector
  7. Change the Python interpreter in the project settings
  8. Modify a Python interpreter
  9. Creating a new Python interpreter
  10. Setting the default interpreter
  11. Managing interpreter packages

Как добавить интерпретатор `Python 3.x` в Pycharm

Я только что установил PyCharm 2017.3.3, и я пытаюсь запустить проект, написанный на python 3, но он не запускается. Я проверил страницу настроек, на которой у нее есть только интерпретатор Python 2.7. Как я могу обновить интерпретатор до Python 3.x.

Я проверил официальный PyCahrm

3 ответа

Сначала найдите своего интерпретатора в своей системе Ubuntu, затем выполните следующие действия:

В меню файла нажмите или выберите settings:

2] В меню файла нажмите или выберите settings:

Щелкните правой кнопкой мыши по стрелке вниз project interpreter и выберите show all из имеющихся там опций.

Щелкните правой кнопкой мыши по стрелке вниз project interpreter и выберите show all из имеющихся там опций.

В появившемся диалоговом окне Add local interpreter выберите System Interpreter, затем нажмите на три точки справа и перейдите к моему местоположению моего python usr/bin/python3.5. И с этим вы должны использовать ваш проект в этой версии python.

Сначала найдите своего интерпретатора в своей системе Ubuntu, затем выполните следующие действия:

В меню файла нажмите или выберите settings:

В меню файла нажмите или выберите settings:

Щелкните правой кнопкой мыши по стрелке вниз project interpreter и выберите show all из имеющихся там опций.

[!d5]

Щелкните правой кнопкой мыши по стрелке вниз project interpreter и выберите show all из имеющихся там опций.

В появившемся диалоговом окне Add local interpreter выберите System Interpreter, затем нажмите на три точки справа и перейдите к моему местоположению моего python usr/bin/python3.5. И с этим вы должны использовать ваш проект в этой версии python.

Сначала найдите своего интерпретатора в своей системе Ubuntu, затем выполните следующие действия:

В меню файла нажмите или выберите settings:

В меню файла нажмите или выберите settings:

Щелкните правой кнопкой мыши по стрелке вниз project interpreter и выберите show all из имеющихся там опций.

[!d5]

Щелкните правой кнопкой мыши по стрелке вниз project interpreter и выберите show all из имеющихся там опций.

В появившемся диалоговом окне Add local interpreter выберите System Interpreter, затем нажмите на три точки справа и перейдите к моему местоположению моего python usr/bin/python3.5. И с этим вы должны использовать ваш проект в этой версии python.

Источник

Configure a Python interpreter

Python interpreters in PyCharm

To work with your Python code in PyCharm, you need to configure at least one Python interpreter. You can use a system interpreter that is available with your Python installation. You can also create a Virtualenv, Pipenv, Poetry, or Conda virtual environment . A virtual environment consists of a base interpreter and installed packages.

With PyCharm Professional , you can also configure interpreters to execute your Python code on remote environments: SSH, Vagrant, WSL (only for Windows), Docker, and Docker Compose

When you configure a Python interpreter , you need to specify the path to the Python executable in your system. So, before configuring a Python interpreter, you need to ensure that you’ve downloaded Python and installed it in your system and you’re aware of a path to it. You can create several Python interpreters based on the same Python executable. This is helpful when you need to create different virtual environments for developing different types of applications. For example, you can create one virtual environment based on Python 3.6 to develop Django applications and another virtual environment based on the same Python 3.6 to work with scientific libraries.

Python interpreters can be configured for a new project or for the current project (you can create a new interpreter or use one of the existing interpreters).

Setting an existing Python interpreter

At any time, you can switch your Python interpreter either using the Python Interpreter selector or in the project Settings/Preferences .

Change the Python interpreter using the Python Interpreter selector

The Python Interpreter selector is located on the status bar. It is the most convenient and quickest way to switch the Python interpreter. Just click it and select the target interpreter:

Change the Python interpreter in the project settings

Press Ctrl+Alt+S to open the IDE settings and select Project

Expand the list of the available interpreters and click the Show All link.

Select the target interpreter.

When PyCharm stops supporting any of the outdated Python versions, the corresponding Python interpreter is marked as unsupported.

When you change an SSH interpreter, you might need to synchronize the local content with the target server. Mind a notification balloon in the lower-right corner: You can choose to perform one of the following actions:

Auto-upload files to the server

Synchronize files and then enable auto-uploading

Modify a Python interpreter

Press Ctrl+Alt+S to open the IDE settings and select Project

Expand the list of the available interpreters and click the Show All link.

Select the target interpreter and click Edit .

You can specify an alternative interpreter name for the selected interpreter. The Python interpreter name specified in the Name field, becomes visible in the list of available interpreters. Click OK to apply the changes.

Creating a new Python interpreter

To add a new interpreter to the current project:

Do one of the following:

Click the Python Interpreter selector and choose Add New Interpreter .

Press Ctrl+Alt+S to open the project Settings/Preferences and go to Project:

| Python Interpreter . Click the Add Interpreter link next to the list of the available interpreters.

Choose the interpreter type to add and perform the specific settings. For virtual environments and system interpreters, select Add Local Interpreters . For remote interpreters, select a specific type.

Note that SSH, WSL, Vagrant, Docker, and Docker Compose are available only for the commercial version of PyCharm. WSL is Windows specific.

Select Add Local Interpreter from the list of the available interpreter types.

In the left-hand pane of the Add Python Interpreter dialog, select Virtualenv Environment . The following actions depend on whether the virtual environment existed before.

If New Virtualenv is selected:

Specify the location of the new virtual environment in the text field, or click and find location in your file system. Note that the directory where the new virtual environment should be located, must be empty!

Choose the base interpreter from the list, or click and find a Python executable in your file system.

If PyCharm detects no Python on your machine, it provides two options: to download the latest Python versions from python.org or to specify a path to the Python executable (in case of non-standard installation).

Select the Inherit global site-packages checkbox if you want that all packages installed in the global Python on your machine to be added to the virtual environment you’re going to create. This checkbox corresponds to the —system-site-packages option of the virtualenv tool.

If you select any of the existing virtual environments from the Interpreter list, it will be reused for the current project.

Click OK to complete the task.

If you have added the user base’s binary directory to your PATH environmental variable, you don’t need to set any additional options: the path to the pipenv executable will be autodetected.

Click OK to complete the task.

If you have not modified the PATH variable, PyCharm shows an error message: Pipenv executable is not found . Discover the proper executable path as described in the pipenv installation procedure and enter the target string in the Pipenv executable field, for example: C:UsersjetbrainsAppDataRoamingPythonPython37Scriptspipenv.exe (Windows) or /Users/jetbrains/.local/bin/pipenv (macOS).

Click OK to save the changes and complete the task.

Select Add Local Interpreter from the list of the available interpreter types.

In the left-hand pane of the Add Python Interpreter dialog, select Poetry Environment . The following actions depend on whether the virtual environment existed before.

If Poetry Environment is selected:

Select the base Python interpreter from the list, or click and find its location in your file system.

If PyCharm doesn’t detect the poetry executable, specify the following path in the Poetry executable field, replacing jetbrains with your username:

If Existing environment is selected:

Expand the Interpreter list and select any of the existing Poetry environments. Alternatively, click and specify a path to it.

Click OK to complete the task.

In the left-hand pane of the Add Python Interpreter dialog, select Conda Environment . The following actions depend on whether the Conda environment existed before.

If New Virtualenv is selected:

Specify the location of the new Conda environment in the text field, or click and find location in your file system. Note that the directory where the new Conda environment should be located, must be empty!

Select the Python version from the list.

Specify the location of the Conda executable file in the text field, or click and find location in the Conda installation directory. You’re basically looking for a path that you’ve used when installing Conda on your machine.

Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.

If you select any of the existing virtual environments from the Interpreter list, it will be reused for the current project.

Click OK to complete the task.

Select Add Local Interpreter from the list of the available interpreter types.

In the left-hand pane of the Add Python Interpreter dialog, select System Interpreter .

In the Interpreter field, type the fully-qualified path to the required interpreter executable, or click and in the Select Python Interpreter dialog that opens, choose the desired Python executable and click OK .

When configuring the base interpreter , you need to specify the path to the Python executable. If PyCharm detects no Python on your machine, it provides the following options:

Specify a path to the Python executable (in case of non-standard installation)

Download and install the latest Python versions from python.org

Install Python using the Command-Line Developer Tools (macOS only).

You will need admin privileges to install, remove, and upgrade packages for the system interpreter. When attempting to install an interpreter package through an intention action, you might receive the following error message: As prompted, consider using a virtual environment for your project.

Click OK to complete the task.

Select an option to create a new SSH configuration, then specify server information (host, port, and username).

In the next dialog window, provide the authentication details to connect to the target server.

Select Password or Key pair (OpenSSH or PuTTY) and enter your password or passphrase. If Key pair (OpenSSH or PuTTY) is selected, specify:

Private key : location of the file with a private key

Passphrase : similar to a password, it serves to encrypt the private key.

The RFC 4716 format for OpenSSH keys is not supported by PyCharm.

Click Next to proceed.

Wait until PyCharm completes the introspection of the SSH server.

In the next dialog, you can select a type of Python environment to configure on the SSH server.

You can select a new or existing venv or use a System interpreter.

You can configure the path mappings between your local project and the server. To do that, click the Browse icon in the Sync folders field and enter the path to the local project folder and the path to the folder on the remote server.

Click Create to complete adding an interpreter.

Select On Vagrant :

In the New Target: Vagrant dialog, click the browse icon next to the Vagrant Instance Folder field, and specify the desired Vagrant instance folder.

This results in showing the link to Vagrant Host URL .

In the next field, PyCharm will display the path to the Python executable. Press «Next» to proceed.

You can create a virtual environment (venv or Conda) or use a system Python interpreter for the target Vagrant instance. Note that virtual environment must be configured and available in the specified Vagrant instance folder. Otherwise, the corresponding lists will be empty.

Press Create to complete the task.

Select On WSL from the list of available interpreter types:

Wait until PyCharm detects Linux on your machine and completes introspection. Press Next to proceed:

In the left-hand pane of the dialog, select the type of the WSL interpreter you want to create: Virtual Environment or System Interpreter .

For a system interpreter, just provide the path to the Python executable in the selected Linux distribution.

For virtual environments, you can provide a path to a Python executable of an existing environment in the selected Linux distribution or create a new environment based on the specified Python.

Select On Docker from the list of the available interpreter types.

In the New Target: Docker dialog, select Pull to pull pre-built images from a Docker registry, and specify python:latest in the Image tag field. Alternatively, you can configure PyCharm to build images locally from a Dockerfile.

Optionally, specify the docker build options.

Wait for PyCharm to connect to the Docker daemon and complete the container introspection.

Next, select an interpreter to use in the Docker container. You can select any virtual environment that is already configured in the container or select a system interpreter.

Click OK to complete the task.

Select On Docker Compose from the list of the available interpreter types.

In the New Target: Docker dialog, specify the docker server and the docker-compose.yml file. Also select the service.

Wait until PyCharm creates and configures a new target:

Next, select an interpreter to use in the container. You can select any virtual environment that is already configured in the container or select a system interpreter.

Click OK to complete the task.

When a remote Python interpreter is added, at first the PyCharm helpers are copied to the remote host. PyCharm helpers are needed to run remotely the packaging tasks, debugger, tests and other PyCharm features. Next, the skeletons for binary libraries are generated and copied locally. Also all the Python library sources are collected from the Python paths on a remote host and copied locally along with the generated skeletons. Storing skeletons and all Python library sources locally is required for resolve and completion to work correctly. PyCharm checks remote helpers version on every remote run, so if you update your PyCharm version, the new helpers will be uploaded automatically and you don’t need to recreate remote interpreter. SFTP support is required for copying helpers to the server.

Setting the default interpreter

In PyCharm, you can specify an interpreter that will be automatically set for all newly created projects.

From the main menu, select File | New Projects Setup | Settings for New Projects (on Window and Linux) or File | New Projects Setup | Preferences for New Projects (on macOS).

Select Python Interpreter settings. Then either choose an existing interpreter from the Python interpreter list of click to add a new interpreter. Click OK to save the changes.

The change will become effective for all newly created projects in PyCharm.

Managing interpreter packages

For each interpreter, you can install, upgrade, and delete Python packages. By default, PyCharm uses pip to manage project packages. For Conda environments you can use the Conda package manager.

PyCharm smartly tracks the status of packages and recognizes outdated versions by showing the number of the currently installed package version (column Version ), and the latest available version (column Latest version ). When a newer version of a package is detected, PyCharm marks it with the arrow sign and suggests to upgrade it.

By default, the Latest version column shows only stable versions of the packages. If you want to extend the scope of the latest available versions to any pre-release versions (such as beta or release candidate ), click Show early releases .

You can upgrade several packages at once. Hold Cmd (macOS) or Ctrl on (Unix or Windows), left-click to select several items in the list of packages, and then click Upgrade .

See the detailed instructions:

See the following video tutorial for additional information:

Источник

Содержание:развернуть

  • Что умеет Poetry
  • Установка
  • Установка на OSX и Linux

  • Установка на Windows

  • Установка через PIP и PIPX

  • Работа с Poetry
  • Создание проекта

  • Pyproject.toml

  • Установка пакета

  • Удаление пакета

  • Poetry и виртуальное окружение
  • Конфигурация Poetry
  • Список команд
  • Сборка и настройка пакета
  • Poetry и Docker

Poetry — это инструмент для управления зависимостями и сборкой пакетов в Python.

В Poetry представлен полный набор инструментов, которые могут понадобиться для детерминированного управления проектами на Python. В том числе, сборка пакетов, поддержка разных версий языка, тестирование и развертывание проектов.

Все началось с того, что создателю Poetry Себастьену Юстасу потребовался единый инструмент для управления проектами от начала до конца, надежный и интуитивно понятный, который бы мог использоваться и в рамках сообщества. Одного лишь менеджера зависимостей было недостаточно, чтобы управлять запуском тестов, процессом развертывания и всем созависимым окружением. Этот функционал находится за гранью возможностей обычных пакетных менеджеров, таких как Pip или Conda. Так появился Python Poetry.

Что умеет Poetry

Ключевой фичей Poetry Python является полное управление библиотеками, заявленными для вашего проекта, включая их установку, обновление и публикацию.

А еще он может:

  • Создавать и упаковывать проекты с помощью одной команды.
  • Публиковать проекты в PyPI и приватных репозиториях.
  • Проверять состояния зависимостей одной командой.
  • Фиксировать версии зависимостей.
  • Управлять публикацией билдов.
  • Использовать ваши настроенные виртуальные сервера или создавать собственное виртуальное окружение для полной изоляции от вашей системы.

Функционал командной строки расширяется с помощью плагинов, а предустановленные значения при необходимости легко заменяются на свои варианты. В целом, продукт имеет юзер-френдли интерфейс.

Установка

Poetry — кроссплатформенный инструмент. Теоретически он должен одинаково работать в Linux, MacOS и Windows. Системные требования предполагают использование актуальных версий Python, поэтому начиная с версии Poetry 1.2 не поддерживаются Python 2.7 и 3.5, будьте внимательны!

Poetry создает изолированное виртуальное окружение для вашего проекта, инсталлируя все необходимое и разруливая конфликты зависимостей (если они в принципе решаемы).

По умолчанию установка происходит в домашний каталог пользователя, но это можно изменить путем переопределения переменной окружения POETRY_HOME:

POETRY_HOME=/etc/poetry

Установка на OSX и Linux

Этапы установки на Mac и Linux идентичны:

1 Проверить версию Python (в консоли python --version, и если версия Python по умолчанию 2.7, проверить python3 --version).

2 Чтобы установить актуальную версию вводим в консоль:

curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -

Если дефолтная версия языка не устраивает или если для установки хочется воспользоваться версией питона 3.x, а по умолчанию стоит 2.7, используйте команду:

curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python3 -

Обратите внимание: процесс установки может занять довольно длительное время.

Каталог bin, в который происходит установка инструмента, в Unix расположен в $HOME/.poetry/bin.

Установка на Windows

Для инсталляции Poetry:

1 Откройте Powershell (Win + X далее i, или найдите PoweShell через поиск).

2 Введите команду:

(Invoke-WebRequest -Uri https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py -UseBasicParsing).Content | python -

Перезапустите оболочку и все заработает. Папку установки для Windows вы найдете в %USERPROFILE%.poetrybin.

Для корректной работы установщик должен иметь возможность найти исполняемые файлы py.exe -3 или py.exe -2.

Установка через PIP и PIPX

Для данного варианта установки необходимо иметь на борту менеджер пакетов PIP (или PIPX).

Для установки Poetry через PIP выполните команду:

pip install --user poetry

Имейте ввиду, что зависимости пакета Poetry могут вызвать конфликт с уже установленными пакетами в вашей системе.

Команды Pipx для установки, обновления и удаления инструмента:

pipx install poetry
pipx upgrade poetry
pipx uninstall poetry

Pipx поддерживает только версии Python старше 3.6.

Работа с Poetry

Для начала убедимся, что Poetry корректно установлен, введя в терминал команду:

poetry --version

Если в ответ высветится актуальный номер версии, можно приступать к работе.

Перед работой с Poetry проверьте корректность установки командой «poetry —version»

Создание проекта

Создаем пробный проект и присваиваем ему название «project-poetry»:

poetry new project-poetry

Произойдет автоматическое создание папки проекта со следующей структурой:

project-poetry
project-poetry
__init__.py
tests
__init__.py
test_project_poetry.py
pyproject.toml
README.rst

В случае, если необходимо инициализировать Poetry-проект в уже существующем каталоге, перейдите в него и выполните команду:

poetry init

Pyproject.toml

В файле pyproject.toml содержится описание вашего Poetry-проекта — название, описание, используемый репозиторий, зависимости проекта и т.д. С помощью него легко организовать зависимости вашего проекта (pyproject.toml можно назвать преемником устаревшего requirements.txt).

Если вы знакомы с Pipenv, то наверняка заметите, что pyproject.toml очень похож на Pipfile.

После инициализации проекта, содержание файла будет следующим:

[tool.poetry]
name = "project-poetry"
version = "0.1.0"
description = ""
authors = ["Alexander <info@pythonchik.ru>"]

[tool.poetry.dependencies]
python = "^3.8"

[tool.poetry.dev-dependencies]
pytest = "^5.2"

[build-system]
requires = ["poetry-core>=1.0.0"]
build-backend = "poetry.core.masonry.api"

Разберемся, что означает каждая секция:

  • [tool.poetry] — содержит метаданные проекта, которые не относятся к пакетам зависимостей — название, описание, указание авторства и контактную информацию;
  • [tool.poetry.dependencies] — раздел содержит зависимости, необходимые для проекта;
  • [tool.poetry.dev-dependencies] — зависимости разработки (не войдут в сборку проекта, но необходимые для других аспектов — тестирования, документации и т. д.);
  • [build-system] — если вы используете Poetry для управления своим проектом, вы должны ссылаться на него в этом разделе (команды new и init автоматически добавляют информацию в раздел build-system).

📌 О дополнительных секциях файла можете прочитать в официальной документации «The pyproject.toml file«.

Все переменные могут задаваться вручную в соответствующие места Pyproject.toml, а также с помощью команды add или добавляться автоматически средствами Poetry.

Установка пакета

Теперь установим новый пакет в наш проект:

poetry add pymongo

Результат выполнения команды установки пакета «poetry add»

После установки пакета, в pyproject.toml появится новая запись:

[tool.poetry.dependencies]
python = "^3.8"
pymongo = "^3.11.2"

💭 Для добавления dev-зависимости (зависимости для разработки) необходимо добавить флаг —dev: poetry add pytest --dev.

Удаление пакета

Для удаления пакета достаточно выполнить команду:

poetry remove pymongo

Для удаления пакета выполните poetry remove «имя_пакета»

При этом запись пакета также удалится из pyproject.toml.

Poetry и виртуальное окружение

По умолчанию, Poetry автоматически создает виртуальное окружение для вашего проекта в cache-директории:

  • для Windows — C:Users<username>AppDataLocalpypoetryCachevirtualenvs;
  • для Linux — ~/.cache/pypoetry/virtualenvs;
  • для macOS — ~/Library/Caches/pypoetry/virtualenvs.

В эту директорию будут сохраняться все зависимости для проекта.

Подробнее о том, что такое виртуальное окружение и как оно работает:

Конфигурация Poetry

Конфигурация Poetry настраивается с помощью команды poetry config. После первого запуска команды, Poetry создаст файл конфигурации config.toml, в котором будут храниться все заданные параметры. Находится файл в директории:

  • для Windows — C:Users<username>AppDataRoamingpypoetry;
  • для Linux — ~/.config/pypoetry;
  • для macOS — ~/Library/Application Support/pypoetry.

Для примера, попробуем настроить Poetry так, чтобы он создавал виртуальное окружение virtualenvs не в cache-директории, а в корневом каталоге проекта. Для этого установим переменной virtualenvs.in-project значение true:

poetry config virtualenvs.in-project true

Чтобы убедиться, что значение успешно установилась, выполним команду:

poetry config virtualenvs.in-project

💭 Чтобы посмотреть все текущие параметры Poetry, используйте команду poetry config --list.

Теперь все зависимости будут устанавливаться в папку .venv в корне вашего проекта.

Если параметр нужно удалить, используйте флаг --unset:

poetry config virtualenvs.in-project --unset

📌 Подробнее о настройке конфигурации Poetry читайте тут.

Список команд

Poetry охватывает множество функций, связанных с управлением конфигурацией и публикацией пакетов:

  • shell — при первом запуске этой команды в каталоге вашего проекта Poetry создает виртуальную среду Python, которая будет связана с проектом. Вместо создания папки, содержащей библиотеки зависимостей, Poetry создает среду на глобальном системном пути. Как только эта виртуальная среда будет создана, ее можно активировать в любое время, запустив poetry shell в каталоге проекта.
  • install — устанавливает зависимости, указанные в pyproject.toml. При первой установке создается файл .lock, который содержит фактические номера версий каждого установленного пакета. Номера версий в .lock приоритетнее, чем находящиеся в pyproject.toml.
  • update — если для пакетов в pyproject.toml существуют более новые версии, они будут установлены, и .lock файл будет обновлен.
  • add — добавление зависимости к pyproject.toml. Пакет устанавливается сразу после применения команды.
  • remove — удаление библиотеки зависимостей.
  • config — пути к текущей виртуальной среде или ее переменные. Передача опции --list вернет текущие значения конфигурации.
  • check — проверяет pyproject.toml на наличие ошибок.
  • show — возвращает вывод всех пакетов, установленных в проекте, включая зависимости зависимостей.
  • run — выполняет сценарий, заданный в разделе tool.poetry.scripts в pyproject.toml.
  • build — собирает исходники и пакеты в архив.
  • publish — публикует вывод предыдущей сборки во внешнем репозитории, например, в PyPi.

Чтобы получить справку из командной строки с полным списком команд, просто вызовите poetry.

Команда «poetry» выведет весь список доступных команд

Сборка и настройка пакета

Чтобы собрать пакет, запускаем команду build.

poetry build

Building project-poetry (0.1.0)
- Building sdist
- Built project-poetry-0.1.0.tar.gz
- Building wheel
- Built project_poetry-0.1.0-py3-none-any.whl

В результате в папке dist будут сформированы пакеты.

Результат сборки пакета находится «dist»

Если мы хотим ограничить сборку определенным типом, можно просто использовать параметр -F.

poetry build -F wheel # or sdist

Чтобы развернуть пакет, нужно настроить репозитории и учетные данные. Для этого применяется команда config.

poetry config repositories.priv https://my.repository

В примере происходит настройка репозитория с именем priv и Url-адресом https://my.repository.

Сохранить учетные данные для этого репозитория также можно с помощью команды config:

poetry config http-basic.priv user password

💭 В приведенной команде user и password соответствуют имени пользователя и паролю для входа в наш частный репозиторий. Обратите внимание, если не указать пароль, то его будет предложено ввести при развертывании пакета.

Закончив настройку, мы можем просто развернуть пакет следующей командой:

poetry publish

Если использован частный репозиторий, следует указать его имя Priv с помощью опции -r.

Poetry и Docker

Использование Poetry для работы с проектом внутри Docker-контейнера иногда сопряжено со сложностями интеграции. Ключевым моментом является отключение VirtualEnv, так как он не нужен в уже изолированном докере:

poetry config virtualenvs.create false

Затем устанавливаются разные наборы зависимостей для переменной среды:

poetry install $(test "$MY_ENV" == production && echo "--no-dev")

Таким образом в $MY_ENV будет контролироваться, какой набор зависимостей следует устанавливать: все (по умолчанию) или продакшн только с --no-dev флагом.


Poetry выходит далеко за рамки стандартного менеджера зависимостей, предлагая такие функции, как создание файлов .lock, создание шаблонов проекта и множество параметров конфигурации, каждый из которых обрабатывается через простой интерфейс командной строки. Если вы не знаете, как чисто и эффективно структурировать свои проекты Python и облегчить управление ими, сделайте себе одолжение и используйте Poetry.

Понравилась статья? Поделить с друзьями:
  • Error running pod install flutter
  • Error running pod install error launching application on iphone 12 pro max
  • Error running pipenv pycharm
  • Error running org jetbrains plugins cucumber java run cucumberjvmsmformatter
  • Error running man