Build AWESOME CLIs With Click in Python

แชร์
ฝัง
  • เผยแพร่เมื่อ 2 ส.ค. 2024
  • In this video, I'll guide you through creating a Command Line Interface (CLI) tool in Python using the Click package. We'll build a simple note-taking tool that can write, read, update, and delete notes. Stick around until the end to discover some hidden features Click offers right out of the box that many people don't know about.
    🔥 GitHub Repository: git.arjan.codes/2024/python_cli
    💡 Get my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.
    📨 The Friday Loop by ArjanCodes Newsletter: thefridayloop.com
    💻 ArjanCodes Blog: www.arjancodes.com/blog
    ✍🏻 Take a quiz on this topic: www.learntail.com/quiz/faoxyu
    🎓 Courses:
    The Software Designer Mindset: www.arjancodes.com/courses/tsdm
    The Software Architect Mindset: www.arjancodes.com/courses/tsam
    Next Level Python: Become a Python Expert: www.arjancodes.com/courses/nlp
    The 30-Day Design Challenge: www.arjancodes.com/courses/30ddc
    👍 If you enjoyed this content, give this video a like. If you want to watch more of my upcoming videos, consider subscribing to my channel!
    Social channels:
    💬 Discord: discord.arjan.codes
    🐦 X: x.com/arjancodes
    🌍 LinkedIn: / arjancodes
    🕵 Facebook: / arjancodes
    📱 Instagram: / arjancodes
    ♪ Tiktok: / arjancodes
    👀 Code reviewers:
    - Yoriz
    - Ryan Laursen
    - Dale Hagglund
    - Kit Hygh
    - Alexander Milden
    - Bean
    🎥 Video edited by Mark Bacskai: / bacskaimark
    🛒 GEAR & RECOMMENDED BOOKS: kit.co/arjancodes
    🔖 Chapters:
    0:00 Intro
    0:31 Story time
    2:45 Creating the project
    4:00 Create the CLI
    4:54 Commands
    6:33 Arguments vs Options
    7:58 Creating the command
    10:40 Connecting to the Entry point
    12:16 The design of click
    14:19 Continuing the connection
    16:46 Using click context
    18:25 Adding config to our tool
    20:26 Giving the option to create the config
    22:59 Things you get for free with Click
    24:12 Final Thoughts
    24:52 Outro
    #arjancodes #softwaredesign #python
    DISCLAIMER - The links in this description might be affiliate links. If you purchase a product or service through one of those links, I may receive a small commission. There is no additional charge to you. Thanks for supporting my channel so I can continue to provide you with free content each week!

ความคิดเห็น • 87

  • @ArjanCodes
    @ArjanCodes  25 วันที่ผ่านมา

    💡 Get my FREE 7-step guide to help you consistently design great software: arjancodes.com/designguide.

  • @maleldil1
    @maleldil1 28 วันที่ผ่านมา +47

    I don't really see a point in using Click directly anymore. Typer does the same thing but better, using type hints to set up everything. It's also based on Click, so if you need something that Typer doesn't offer natively, you can use Click through Typer to do what you want. IMO, Click by itself doesn't offer enough to warrant adding a dependency, as stdlib's argparse is quite powerful and easy to use.

    • @traal
      @traal 27 วันที่ผ่านมา

      Agreed, I also use Typer for everything. And I agree that argparse is pretty great. In fact, unless I really need subcommands and composability, I personally prefer argparse over Click.
      There’s also a nice project on GitHub callled “argh” that wraps argparse with type hints, very much like Typer, but much more lightweight.

    • @SampadMohanty7
      @SampadMohanty7 19 วันที่ผ่านมา

      Or Fire by google.

  • @jurgenrusch4041
    @jurgenrusch4041 25 วันที่ผ่านมา +6

    Hi Arjan. Thanks for yet another super clear and instructive video. And,... at the right time as I am creating a CLI for various related functionalities already written in Python. So, again thanks!
    Un your video I saw you were using poetry. As this was not the main focus of this video you simply executed poetry commands. I looked back in your video history and saw that in 2023 you posted a video titled "How to Build a Complete Python Package Step-by-Step". There you used setuptools for packaging, and not (yet) poetry.
    Even after many years of Python programming I find packaging a complex topic. For my work I would very much like to use poetry for packaging and distribution.
    I would really love to see you (and your team) create an in-depth video about poetry, covering topics like a build frontend and backend.

  • @ladycoder2095
    @ladycoder2095 28 วันที่ผ่านมา

    This is absolutely fascinating! IAbout nine years back, had used click to create a command line tool which took a file list of tsv and output a combined xls file with the original tsv files as sheets 😀. This has been a nice refresher.

  • @j4g094
    @j4g094 9 วันที่ผ่านมา

    I am a DevOps Engineer. Any time I need a CLI tool to help with some task or another, I write it in Python. That is because I have yet to find anything I needed to do on my Linux servers, for which a package did not already exist. For almost all of them I use Click and Rich and when I don't, it is because I need a very quick solution without dependencies outside of the standard library.

  • @DJStompZone
    @DJStompZone 28 วันที่ผ่านมา +9

    > Also sometimes called a flag
    Correct me if I'm wrong, but my understanding is that flags are boolean values (they're either present or they aren't) and don't require any additional information, whereas options are necessarily followed by a value.
    Sometimes they can go either way, depending on context. For example, "--help" might be a flag if used by itself, or it can be an option if used like "--help ".

    • @ArjanCodes
      @ArjanCodes  28 วันที่ผ่านมา +1

      That's right, a flag is another word for a boolean option - that wasn't clear in the video.

    • @DJStompZone
      @DJStompZone 28 วันที่ผ่านมา

      Right on, cheers 🙌

  • @johnsontea8542
    @johnsontea8542 5 วันที่ผ่านมา +1

    Yes would love to see how to add pydantic to add validation to configuration values and with a logger and pytest!

  • @EusebioResende
    @EusebioResende 28 วันที่ผ่านมา +3

    Click is a great library. A couple of features I used were Multi Command Chaining and Multi Command Pipelines. May I suggest a video with some advanced features of Click. It would be awesome. Great video Arjan and thanks for sharing.

  • @riki4878
    @riki4878 28 วันที่ผ่านมา +2

    Great video Arjan :) Good job. We use click in our company everywhere. It's really nice package.

    • @ArjanCodes
      @ArjanCodes  28 วันที่ผ่านมา +1

      Glad you liked it!

  • @snakehunt89
    @snakehunt89 28 วันที่ผ่านมา +1

    I would love to see an additional video covering some more advanced usage like adding a logger for scripts or conditional parameters (like if one option/arg is supplied make another not required)

  • @bryangarcia9488
    @bryangarcia9488 25 วันที่ผ่านมา +1

    Great video. I tend to use classic argparse at my workplace but I’ll give click a try for future projects 👍

  • @PhunkyBob
    @PhunkyBob 28 วันที่ผ่านมา

    As always, thanks for sharing. ❤

    • @ArjanCodes
      @ArjanCodes  25 วันที่ผ่านมา

      Thanks for watching!

  • @alexandrodisla6285
    @alexandrodisla6285 28 วันที่ผ่านมา +9

    Click, Typer and Rich

    • @express4863
      @express4863 28 วันที่ผ่านมา

      Click and Rich are my two "go to tools" for anything CLI related. Using things like rich.Live() for updates for long running or slow application updates really improves the user experience.

    • @pranaypallavtripathi2460
      @pranaypallavtripathi2460 27 วันที่ผ่านมา

      are typer and rich also python packages for building cli tools?

    • @express4863
      @express4863 25 วันที่ผ่านมา

      @@pranaypallavtripathi2460 typer has some overlap with click. Rich is more for output to the console. Rich makes working with the console in an interactive way much easier. I use it even when I am not making a CLI application.

  • @MohsenPadidar
    @MohsenPadidar 28 วันที่ผ่านมา

    Thank you for the professional content you produce. I learned a lot from you. ❤
    Please do more rust

    • @ArjanCodes
      @ArjanCodes  25 วันที่ผ่านมา +1

      More to come!

  • @witcherek
    @witcherek 27 วันที่ผ่านมา +1

    Great job!
    Please prepare more extended example with pytest, pydantic
    It's a pleasure to learn programming with you!
    Greetings!

  • @spanomatic
    @spanomatic 27 วันที่ผ่านมา

    Thank you Iron Programmer!

    • @ArjanCodes
      @ArjanCodes  27 วันที่ผ่านมา

      You’re welcome- glad you enjoyed it!

  • @taufiqurrahmansagafkelrey2833
    @taufiqurrahmansagafkelrey2833 27 วันที่ผ่านมา

    favorit coding uncle, finally!!!

  • @realpdm
    @realpdm 22 วันที่ผ่านมา

    Thanks for sharing this. I've been using docopt for a long time and while I like it is can be very finicky to use. Click looks a lot more deterministic without all the hassle of using argparse directly. Will definitely try it with my next project.

    • @ArjanCodes
      @ArjanCodes  21 วันที่ผ่านมา

      You're welcome - glad you liked it!

  • @helboy1111
    @helboy1111 28 วันที่ผ่านมา +1

    I used to love click, but since finding out about invoke I don’t think I’ll ever create a CLI app manually anymore ^^

  • @phortheman
    @phortheman 27 วันที่ผ่านมา

    Looks cool! I usually write my more complex CLI tools in Go with Cobra which has a great interface. This looks kind of similar but for Python instead!

  • @iamrodos
    @iamrodos 28 วันที่ผ่านมา +4

    Yes to pytest. As I was watching I was thinking this video would be even better if it use TDD right from the beginning where pytest and coverage was used. Create the empty functions, write the test of expected behaviour, complete the functions, write next set of functionality, rinse and repeat. Would demonstrate a great way to "approach" development that would help a lot of people see some good technique and practices.

    • @iamrodos
      @iamrodos 28 วันที่ผ่านมา

      Great video BTW.

    • @YazzDAtlas
      @YazzDAtlas 27 วันที่ผ่านมา

      I would like to see some practical test.

    • @ArjanCodes
      @ArjanCodes  21 วันที่ผ่านมา

      Thanks! Though I agree that it is good practice to follow a TDD approach, I’m afraid that it will slow the videos down too much. But I might test it in an upcoming video 😎.

  • @adrianabreu1565
    @adrianabreu1565 23 วันที่ผ่านมา

    Would love to see the new pydantic version implement in the todo app!

  • @the.elven.archer
    @the.elven.archer 28 วันที่ผ่านมา

    I would love a guide like this but for ncurses-like applications :D

  • @klmcwhirter
    @klmcwhirter 28 วันที่ผ่านมา +3

    I looked at click sometime ago myself, but am now just using docopt (NOT docopts - with an 's'; which is for shell scripted CLI tools).
    docopt allows you to specify the CLI in the main modules docstring. You don't have to use that convention, but it is the most practical.
    The CLI documentation IS THE parser spec. Add one line of code to get the parsed CLI verbs, options, flags, etc.
    Click is intriguing, but there is too much magic and the interface still needs to be documented - which never happens in practice on a busy team.

    • @Julie9009
      @Julie9009 23 วันที่ผ่านมา

      +1 for docopt

  • @MyrLin8
    @MyrLin8 28 วันที่ผ่านมา

    LOL ok got your email, "helping students get drunk :)" hehehehe, ok not really, but the fridge issue is closely related yes? Now we'll learn how to write a CLI, since I'm going to need one soon. Bookmarked!

    • @ArjanCodes
      @ArjanCodes  28 วันที่ผ่านมา

      I remember when I was a student, I didn’t need all that much help to get drunk, haha.

  • @DiegoRoccia
    @DiegoRoccia 26 วันที่ผ่านมา

    click and rich together really help creating great CLI interfaces in python. too bad distributing python code to end users is so complicated. For this reason we recently migrated one of our internal CLIs to golang

  • @mmilerngruppe
    @mmilerngruppe 24 วันที่ผ่านมา

    21:21 environment variables sets are stored in terminal history too if they are not coming as exports from other scripts. but if they come from other scripts, they are already somewhere stored. it's a uroborus problem. may be I am complete wrong about it, I would like your opinions on it.

  • @DanielRodriguez-lu3uu
    @DanielRodriguez-lu3uu 26 วันที่ผ่านมา

    Great Tool, quick question: something that grabbed my attention was the part where you installed "notes" so you don't have to call python on shell. Is that only possible because you are using Poetry? is there another way to achieve the same result with out Poetry?

  • @mmilerngruppe
    @mmilerngruppe 24 วันที่ผ่านมา

    3:41 Arjan, what text editor do you use?

  • @AndyWallWasWeak
    @AndyWallWasWeak 27 วันที่ผ่านมา

    9:35 now we are cooking!

  • @nickeldan
    @nickeldan 28 วันที่ผ่านมา +1

    I like your keyboard! What is it?

    • @ArjanCodes
      @ArjanCodes  28 วันที่ผ่านมา +2

      I think I’m using the Nuphy Air 75 here.

  • @FragrantVagrant69
    @FragrantVagrant69 28 วันที่ผ่านมา

    I have a question, hopefully you can help. I wrote a basic gui app for a friend to help them solve a problem at work. They showed their boss and he loves i and wants to distribute it to hundreds of users across the country because it will save them hours of work every day. I packaged it using pyinstaller and windows blocks it unless you disable windows defender. They dont seem to have the option to exclude the file from defender, so i wanted to ask what would be the best way to distribute the get this app recognised that it isn't malicious? I heard that signing it doesn't guarantee that it will be trusted and its such a simple app i dont know if if its worth submitting it for review or something like that. I don't really want to rewrite it as a web app as a simple exe is sufficient for what it does . Do you have any suggestions?

    • @DJStompZone
      @DJStompZone 28 วันที่ผ่านมา +1

      My advice is not to use pyinstaller. Defender is gonna freak out every time, unless your executable is signed by a trusted certificate authority. If you want to proceed, you might consider getting your application officially signed. Otherwise, you'll need to instruct users to install and trust your certificate manually through the certificate manager in Windows, which is inadvisable unless you know exactly what you're doing.

  • @doodah120
    @doodah120 27 วันที่ผ่านมา

    I like to have my config object loaded in the top level __init__.py, that way it is globally available and doesn't need to be passed around. Is there any issue with that?

  • @shridharcs
    @shridharcs 27 วันที่ผ่านมา

    How about permission handling with click?

  • @ramukamath2110
    @ramukamath2110 28 วันที่ผ่านมา

    i dont think you need to run pip install -e . . poetry install will install current project in editable mode. you just need to activate the venv using poetry shell

  • @simonchpmnk4392
    @simonchpmnk4392 20 วันที่ผ่านมา

    @9:43
    th-cam.com/video/FWacanslfFM/w-d-xo.html
    Line 14:
    TypeError: unsupported operand type(s) for /: 'str' and 'str'
    Need to use e.g. pathlibs Path or similar.

  • @Amulya7
    @Amulya7 28 วันที่ผ่านมา

    I have heard this story before. I don't remember the title of the video.

  • @ganeshprasadrao5596
    @ganeshprasadrao5596 27 วันที่ผ่านมา

    typer ?

  • @drac8854
    @drac8854 28 วันที่ผ่านมา

    How about you remake this software in clap(rust) 🙂

  • @siestoelemento1019
    @siestoelemento1019 28 วันที่ผ่านมา

    Ok

  • @noobymemer
    @noobymemer 28 วันที่ผ่านมา

    mynotes😂

  • @moshedicker6786
    @moshedicker6786 28 วันที่ผ่านมา

    Typer

  • @rdmferreira
    @rdmferreira 28 วันที่ผ่านมา

    ok.

  • @duncangibson6277
    @duncangibson6277 28 วันที่ผ่านมา +2

    Interesting video, but...
    New users are probably at Python-101 level,
    If they read the docs, they will find command line options parsing using getopts, optparse, getopts, docopts, and maybe others. It would be interesting so see a video that compares and contrasts these different modules.
    Secondly, new users are probably not 100% conversant with @decorators, especially the multi-level decorators shown in this video, so it would also be interesting to see the basics of how users work with decorators, and maybe more importantly, how these modules create these decorators,
    Apart from that, keep up the good work 🙂

  • @user-jb2gn4yo5f
    @user-jb2gn4yo5f 27 วันที่ผ่านมา

    Call it "Arjanotes"

    • @ArjanCodes
      @ArjanCodes  27 วันที่ผ่านมา

      I like it. 😁

  • @evilprince2009
    @evilprince2009 28 วันที่ผ่านมา

    I'd rather do it using C++.

    • @hriscuvalerica4814
      @hriscuvalerica4814 28 วันที่ผ่านมา +2

      Real programmers use real programming languages like Fortran not toy language like C++

    • @PhunkyBob
      @PhunkyBob 28 วันที่ผ่านมา

      @@hriscuvalerica4814 Pfff... There is nothing better than assembly language. 😆
      How much time would last a YT video of a tutorial about making a CLI in assembly to create a notes application 🤔

    • @evilprince2009
      @evilprince2009 28 วันที่ผ่านมา

      @@hriscuvalerica4814 I request you to not consider me as a 'Real Programmer' then. Peace 🙏

  • @user-ce7vu3ct3y
    @user-ce7vu3ct3y 28 วันที่ผ่านมา +2

    Cyclopts library is much better

    • @jylpah
      @jylpah 28 วันที่ผ่านมา

      Cyclopts looks really nice! I went from ArgParse to Click to Typer. support for Literal, Union and asyncio is great. I will try this next time

    • @Schlynn
      @Schlynn 28 วันที่ผ่านมา +1

      Car to give even a single sentence for why?

    • @user-ce7vu3ct3y
      @user-ce7vu3ct3y 28 วันที่ผ่านมา

      ​@@Schlynn discord.com/channels/820628246965780520/1186057034873962627
      You can check this thread on discord, I had a long discussion with the owner of cyclopts. It will explain why it's better than other cli parsers. I've tried Argparse -> Click -> Typer -> Cyclopts. Cyclopts is the easiest to work with (has some really good features) and it's carefully maintained. This was the first reply on posted on the thread:
      I agree that typer is bloated. For example in Enum type, the keys should be the user input but in typer library it uses Enum values as user input.
      I planned on creating a PR, but I don’t like its codebase at all. Cyclopts look interesting btw,

    • @cameronball3998
      @cameronball3998 28 วันที่ผ่านมา

      haven’t had a chance to watch the video yet (on my watch later lol), but just want to throw docopt’s name here. i use docopt on all my projects now as it’s absurdly simple and my documentation becomes code. maybe for a production grade or release application i’d go with something more heavyweight, but i find for the vast majority of use cases, docopt is clean, easy, and reliable, and has the features i need (e.g., nested mutually exclusive argument groups).

  • @ssmith5048
    @ssmith5048 28 วันที่ผ่านมา

    only a sadist would create a cli tool with python - or they would build it and install it on their worst enemies system.....

    • @ArjanCodes
      @ArjanCodes  28 วันที่ผ่านมา +7

      A true sadist would then post a video about that on TH-cam, which would lead to even more CLI tools built with Python.

    • @ssmith5048
      @ssmith5048 28 วันที่ผ่านมา

      @@ArjanCodes go for it if you don`t care about runtime

    • @keeganlaporte4758
      @keeganlaporte4758 28 วันที่ผ่านมา +1

      I maintain a Python CLI tool. It is much faster. Speed, three kinds: speed of program execution, speed to develop, speed (time) to maintain issues with the program.
      My Python CLI is much faster, saving weeks in the second and third category.
      It’s unlikely that the first category will ever compensate for time lost in the latter two.
      Python is typically the faster language when you consider the real problems. If you really convinced your customer to pay the costs of premature optimization, go ahead and use cpp I guess.
      I couldn’t imagine trying to convince our customers to wait extra weeks for bug fixes and development

    • @therealslimaddy
      @therealslimaddy 28 วันที่ผ่านมา

      @@ssmith5048cli tools are very much viable in python. If it’s slow then there is a skill issue clearly.

    • @ssmith5048
      @ssmith5048 28 วันที่ผ่านมา

      @@therealslimaddy i would call it a poor decision issue to choose python for a cli tool for anything not trivial, instead write tools in c or cpp for cli tools. python for the quick and dirty scripting it is tolerably good at.

  • @johnathanrhoades7751
    @johnathanrhoades7751 28 วันที่ผ่านมา

    I love dotfiles in the $HOME/.config/ directory. Just makes it really easy to keep everything together. That or a dot file directly in the $HOME directory.