pythonpython-packagingpython-poetry

How to run a script using pyproject.toml settings and poetry?


I am using poetry to create .whl files. I have an FTP sever running on a remote host. I wrote a Python script (log_revision.py) which save in a database the git commit, few more parameters and in the end sends the .whl (that poetry created) to the remote server (each .whl in a different path in the server, the path is saved in the DB).

At the moment I run the script manually after each time I run the poetry build command. I know the pyproject.toml has the [tool.poetry.scripts] but I don't know how I can use it to run a Python script.

I tried:

[tool.poetry.scripts]
my-script = "my_package_name:log_revision.py

and then poetry run my-script but I always get an error:

AttributeError: module 'my_package_namen' has no attribute 'log_revision'

How can I run this command? As a short term option (without git and params) I tried to use poetry publish -r http://192.168.1.xxx/home/whl -u hello -p world but I get the following error:

[RuntimeError]                                 
Repository http://192.168.1.xxx/home/whl is not defined  

What am I doing wrong and how can I fix it?


Solution

  • At the moment the [tool.poetry.scripts] sections is equivalent to setuptools console_scripts.

    So the argument must be a valid module and method name. Let's imagine within your package my_package, you have log_revision.py, which has a method start(). Then you have to write:

    [tool.poetry.scripts]
    my-script = "my_package.log_revision:start"
    

    Here's a complete example:

    You should have this folder structure:

    my_package
    ├── my_package
    │   ├── __init__.py
    │   └── log_revision.py
    └── pyproject.toml
    

    The complete content of a functional pyproject.toml is:

    [tool.poetry]
    name = "my_package"
    version = "0.1.0"
    description = ""
    authors = ["Your Name <you@example.com>"]
    
    [tool.poetry.dependencies]
    python = "^3.8"
    
    [tool.poetry.scripts]
    my-script = "my_package.log_revision:start"
    
    [build-system]
    requires = ["poetry_core>=1.0.0"]
    build-backend = "poetry.core.masonry.api"
    

    and in my_package/log_revision.py:

    def start():
        print("Hello")
    

    After you have run poetry install once you should be able to do this:

    $ poetry run my-script  
    Hello
    

    You cannot pass something to the start() method directly. Instead you can use command line arguments and parse them, e.g. with python's argparse.