Michael Driscoll's Blog, page 4
September 9, 2024
Adding Terminal Effects with Python
The Python programming language has thousands of wonderful third-party packages available on the Python Package Index. One of those packages is TerminalTextEffects (TTE), a terminal visual effects engine.
Here are the features that TerminalTextEffects provides, according to their documentation:
Xterm 256 / RGB hex color supportComplex character movement via Paths, Waypoints, and motion easing, with support for quadratic/cubic bezier curves.Complex animations via Scenes with symbol/color changes, layers, easing, and Path synced progression.Variable stop/step color gradient generation.Path/Scene state event handling changes with custom callback support and many pre-defined actions.Effect customization exposed through a typed effect configuration dataclass that is automatically handled as CLI arguments.Runs inline, preserving terminal state and workflow.Note: This package may be somewhat slow in Windows Terminal, but it should work fine in other terminals.
Let’s spend a few moments learning how to use this neat package
InstallationThe first step to using any new package is to install it. You can use pip or pipx to install TerminalTextEffects. Here is the typical command you would run in your terminal:
python -m pip install terminaltexteffectsNow that you have TerminalTextEffects installed, you can start using it!
UsageLet’s look at how you can use TerminalTextEffects to make your text look neat in the terminal. Open up your favorite Python IDE and create a new file file with the following contents:
from terminaltexteffects.effects.effect_slide import Slidetext = ("PYTHON" * 10 + "\n") * 10
effect = Slide(text)
effect.effect_config.merge = True
with effect.terminal_output() as terminal:
for frame in effect:
terminal.print(frame)
This code will cause the string, “Python” to appear one hundred times with ten strings concatenated and ten rows. You use a Slide effect to make the text slide into view. TerminalTextEffects will also style the text too.
When you run this code, you should see something like the following:
TerminalTextEffects has many different built-in effects that you can use as well. For example, you can use Beams to make the output even more interesting. For this example, you will use the Zen of Python text along with the Beams effects:
from terminaltexteffects.effects.effect_beams import BeamsTEXT = """
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
effect = Beams(TEXT)
with effect.terminal_output() as terminal:
for frame in effect:
terminal.print(frame)
Now try running this code. You should see something like this:
That looks pretty neat! You can see a whole bunch of other effects you can apply on the package’s Showroom page.
Wrapping UpTerminalTextEffects provides lots of neat ways to jazz up your text-based user interfaces with Python. According to the documentation, you should be able to use TerminalTextEffects in other TUI libraries, such as Textual or Asciimatics, although it doesn’t specifically state how to do that. Even if you do not do that, you could use TerminalTextEffects with the Rich package to create a really interesting application in your terminal.
LinksGitHub pagePyPI page
The post Adding Terminal Effects with Python appeared first on Mouse Vs Python.
September 3, 2024
ANN: JupyterLab 101 Kickstarter
My latest Python book is now available for pre-order on Kickstarter.

JupyterLab, the latest iteration of the Jupyter Notebook, is a versatile tool for sharing code in an easily understandable format.
Hundreds of thousands of people around the world use Jupyter Notebooks or variations of the Notebook architecture for any or all of the following:
teachingpresentationslearning a computer languagenumerical simulationsstatistical modelingdata visualizationmachine learningand much more!Jupyter Notebooks can be emailed, put on GitHub, or run online. You may also add HTML, images, Markdown, videos, LaTeX, and custom MIME types to your Notebooks. Finally, Jupyter Notebooks support big data integration.
JupyterLab 101 will get you up to speed on the newest user interface for Jupyter Notebooks and the other tools that JupyterLab supports. You now have a tabbed interface that you can use to edit multiple Notebooks, open terminals in your browser, create a Python REPL, and more. JupyterLab also includes a debugger utility to help you figure out your coding issues.
Rest assured, JupyterLab supports all the same programming languages as Jupyter Notebook. The main difference lies in the user interface, which this guide will help you navigate effectively and efficiently.
After reading JupyterLab 101, you will be an expert in JupyterLab and produce quality Notebooks quickly!
What You’ll LearnIn this book, you will learn how about the following:
Installation and setup of JupyterLabThe JupyterLab user interfaceCreating a NotebookMarkdown in NotebooksMenus in JupyterLabLaunching Other Applications (console, terminal, text files, etc)Distributing and Exporting NotebooksDebugging in JupyterLabTesting your notebooksRewards to Choose FromAs a backer of this Kickstarter, you have some choices to make. You can receive one or more of the following, depending on which level you choose when backing the project:
An early copy of JupyterLab 101 + all updates including the final version (ALL BACKERS)A signed paperback copy (If you choose the appropriate perk)Get all by Python courses hosted on Teach Me Python or another site (If you choose the appropriate perk)T-shirt with the book cover (If you choose the appropriate perk)Get the book on Kickstarter today!
The post ANN: JupyterLab 101 Kickstarter appeared first on Mouse Vs Python.
August 19, 2024
How to Plot in the Terminal with Python and Textualize
Have you ever wanted to create a plot or graph in your terminal? Okay, maybe you haven’t, but now that you know you can, you want to! Python has the plotext package for plotting in your terminal. However, while that package is amazing all on its own, there is another package called textual-plotext that wraps the plotext package so you can use it in Textual!
In this tutorial, you will learn the basics of creating a plot in your terminal using the textual-plotext package!
InstallationYour first step in your plotting adventure is to install textual-plotext. You can install the package using pip. Open up your terminal and run the following command:
python -m pip install textual-plotextPip will install textual-plotext and any dependencies it needs. Once that’s done, you’re ready to start plotting!
UsageTo kick things off, you’ll create a simple Textual application with a scatter chart in it. This example comes from the textual-plotext GitHub repo. You can create a Python file and name it something like scatterplot.py and then add the following code:
from textual.app import App, ComposeResultfrom textual_plotext import PlotextPlot
class ScatterApp(App[None]):
def compose(self) -> ComposeResult:
yield PlotextPlot()
def on_mount(self) -> None:
plt = self.query_one(PlotextPlot).plt
y = plt.sin() # sinusoidal test signal
plt.scatter(y)
plt.title("Scatter Plot") # to apply a title
if __name__ == "__main__":
ScatterApp().run()
When you run this code, you will see the following in your terminal:
Plotext does more than scatterplots though. You can create any of the following:
Scatter PlotLine PlotLog PlotStem PlotBar PlotsDatetime PlotsSpecial PlotsDecorator PlotsImage Plotsand moreLet’s look at a bar plot example:
from textual.app import App, ComposeResultfrom textual_plotext import PlotextPlot
class BarChartApp(App[None]):
def compose(self) -> ComposeResult:
yield PlotextPlot()
def on_mount(self) -> None:
languages = ["Python", "C++", "PHP", "Ruby", "Julia", "COBOL"]
percentages = [14, 36, 11, 8, 7, 4]
plt = self.query_one(PlotextPlot).plt
y = plt.bar(languages, percentages)
plt.scatter(y)
plt.title("Programming Languages") # to apply a title
if __name__ == "__main__":
BarChartApp().run()
The main difference here is that you’ll be calling plt.bar() with some parameters, whereas, in the previous example, you called plt.sin()with no parameters at all. Of course, you also need some data to plot for this second example. The provided data is all made up.
When you run this example, you will see something like the following:
Isn’t that neat?
Wrapping UpYou can create many other plots with Plotext. Check out their documentation and give some of the other plots a whirl. Have fun and make cool things in your terminal today!
The post How to Plot in the Terminal with Python and Textualize appeared first on Mouse Vs Python.
August 12, 2024
Creating Progress Bars in Your Terminal with Python and Textual
The Textual package is a great way to create GUI-like applications with Python in your terminal. These are known as text-based user interfaces or TUIs. Textual has many different widgets built-in to the framework.
One of those widgets is the ProgressBar. If you need to show the progress of a download or long-running process, then you will probably want to use a progress bar or some kind of spinner widget to show the user that your application is working.
This tutorial will show you how to create a simple progress bar with Textual!
InstallationIf you do not have Textual installed yet, you can get it by using Python’s handy pip tool. Open up your terminal and run the following command there:
python -m pip install textualTextual will get installed, along with all its dependencies. You may want to create a virtual environment first and install Textual there.
Creating a ProgressBar in TextualCreating a progress bar with Textual is pretty straightforward. The following code is based on an example from the Textual documentation. The main difference is that this version uses a button to start the timer, simulating a download or some other long-running process rather than catching a key event.
You can copy this code into your favorite Python editor and give it a quick study:
# progressbar_demo.pyfrom textual.app import App, ComposeResult
from textual.containers import Center, Middle
from textual.timer import Timer
from textual.widgets import Button, ProgressBar
class Progress(App[None]):
timer = Timer
def compose(self) -> ComposeResult:
with Center():
with Middle():
yield ProgressBar()
yield Button("Start")
def on_mount(self) -> None:
"""
Set up the timer to simulate progress
"""
self.timer = self.set_interval(1 / 10, self.advance_progressbar, pause=True)
def advance_progressbar(self) -> None:
"""
Called to advance the progress bar
"""
self.query_one(ProgressBar).advance(1)
def on_button_pressed(self) -> None:
"""
Event handler that is called when button is pressed
"""
self.query_one(ProgressBar).update(total=100)
self.timer.resume()
if __name__ == "__main__":
app = Progress()
app.run()
The compose() method is kind of fun as it uses both the Center() and the Middle() containers to position the widgets in the middle of the terminal. You then set up the timer object in on_mount() and you start the timer in on_button_pressed()which is the Button widget’s event handler.
When you run this code, you will initially see what’s known as an indeterminate progress bar. What that means is that Textual doesn’t have any information about how long the progress is, so the progress bar just shows a kind of “bouncing” or “cycling” progress:
When you press the “Start” button, you will see the progress bar go from 0-100%, and the text fields to the right will update as well:
If you want to make your progress bar stand out, add a gradient. A gradient will make the colors of the progress bar change over time and make the widget look neat!
Wrapping UpAdding a progress bar or simply showing some kind of informational widget that lets the user know your application is working is always a good idea. You don’t want the user to think the application has crashed or frozen. The user might be forced to close the application and lose their information after all!
Fortunately, Textual makes adding a progress bar easy. Not only is it easy, but the progress bar is easy to update so you can accurately give the user a sense of when the work will be done. Give it a try and see what you think!
Related ReadingWant to learn more about Textual? Check out the following articles:
An Intro to Textual – Creating Text User Interfaces with Python
Textual 101 – Using the TabbedContent Widget
Using CSS to Style a Python TUI with Textual
The post Creating Progress Bars in Your Terminal with Python and Textual appeared first on Mouse Vs Python.
August 5, 2024
Create Amazing Progress Bars in Python with alive-progress
Have you ever needed a progress bar in your Python command-line application? One great way of creating a progress bar is to use the alive-progress package created by Rogério Sampaio de Almeida! Alive progress provides multiple different types of progress bars in your terminal or IPython REPL session. The alive progress package will work with any iterable, from lists to querysets, and more.
Let’s spend a little time learning how the alive-progress package works!
InstallationInstalling the alive-progress package is easy using the pip installer utility. Here is the command you should use in your terminal:
python -m pip install alive-progressPip will install the package and any dependencies it needs. The pip tool shouldn’t take very long to install alive-progress.
Example UsageThe alive-progress package comes with a great demo that you can use to see all the different types of progress bars that the package supports. Open up a Python REPL and run the following code:
from alive_progress.styles import showtimeshowtime()
When you run this code, you will see something similar to the following:
There is another alive-progress demo that is a little different from the one above. You don’t need to use a Python REPL to run it though. Instead, you can open up your terminal application and run the following command:
python -m alive_progress.tools.demoWhen you run this command, you will see something like this:
https://www.blog.pythonlibrary.org/wp-content/uploads/2024/08/alive_demo.mp4The alive-progress GitHub page also shows several different code examples that demonstrate how to use alive-progress in your code. Here is one of the examples:
from alive_progress import alive_barimport time
for x in 1000, 1500, 700, 0:
with alive_bar(x) as bar:
for i in range(1000):
time.sleep(.005)
bar()
Here you loop over four different integer values and create a progress bar for each of them. Then you loop over a range of one thousand and the progress bars will run through to completion.
When you run this code in your terminal, you will see this output:
Check out the GitHub repository for more fun examples!
Wrapping UpThe alive-progress package is lots of fun. You can add progress bars to any of your regular Python scripts and see them visually in your applications. This can be especially useful for command-line utilities that you create as they will show the user how far along they are in processing the data.
Download the package and start tinkering today!
The post Create Amazing Progress Bars in Python with alive-progress appeared first on Mouse Vs Python.
August 1, 2024
Displaying Pandas DataFrames in the Terminal
Have you ever wanted to show a pandas DataFrame in your terminal? Of course, you have! All you need is the textual-pandas package!
Yes, you can also view a pandas DataFrame in a REPL, such as IPython or Jupyter Notebook, but you can write a TUI application with textual-pandas and use that to display pandas DataFrames!
There are other ways to load a pandas DataFrame in your terminal, but this handy package makes it very simple! Let’s find out how!
InstallationYour first step is to install the textual-pandas package. The most common method of installing a Python package is using pip.
Open up your terminal and run the following command:
python -m pip install textual-pandasPip will install the textual-pandas package and any dependencies that it needs. Once that has finished successfully, you can learn how to use this package!
UsageUsing the textual-pandas package takes only a small amount of code. Open up your favorite Python editor, create a new Python file, and add this code that is from the textual-pandas documentation:
from textual.app import Appfrom textual_pandas.widgets import DataFrameTable
import pandas as pd
# Pandas DataFrame
df = pd.DataFrame()
df["Name"] = ["Dan", "Ben", "Don", "John", "Jim", "Harry"]
df["Score"] = [77, 56, 90, 99, 83, 69]
df["Grade"] = ["C", "F", "A", "A", "B", "D"]
class PandasApp(App):
def compose(self):
yield DataFrameTable()
def on_mount(self):
table = self.query_one(DataFrameTable)
table.add_df(df)
if __name__ == "__main__":
app = PandasApp()
app.run()
This code will create a simple pandas DataFrame. Then, you will make a small Textual application that loads a table widget. In this case, you can use the custom widget to load the DataFrame.
When you run this code, you will see the following in your terminal:
Doesn’t that look nice? Now try adding your own DataFrame and re-run the code with your data!
Wrapping UpThe textual-pandas package makes displaying pandas DataFrames in your terminal easy. If you know much about the Textual package, you could even create a DataFrame editor in your terminal.
Give it a try and let me know what you come up with!
The post Displaying Pandas DataFrames in the Terminal appeared first on Mouse Vs Python.
July 23, 2024
ANN: ObjectListView3 for wxPython
ObjectListView is a third-party wxPython widget that wraps the wx.ListCtrl. I have used it for over 10 years in quite a few different GUI applications because it works much nicer than wx.ListCtrl does. Unfortunately, ObjectListView was never integrated into wxPython core like some other amazing third-party packages were, and so it has become broken over the past couple of years such that you can’t use it with the latest version of Python / wxPython.
So, I decided to fork the project, as its defects were simple enough that I could resolve them quickly. The new version of ObjectListView is now called ObjectListView3.
You can get the new version of ObjectListview here:
ObjectListView3 on the Python Packaging IndexObjectListView3 on GitHubNote that this version of ObjectListView works with Python 3.11+ and wxPython 4.2+. It may work with earlier versions as well.
InstallationIf you’d like to install ObjectListView3, you can use Python’s pip to do so like this:
python -m pip install ObjectListView3Now let’s see how an example of using ObjectListView!
Sample UsageThe following is an application that starts out by listing two books in an ObjectListView3 widget. When you press the “Update OLV” button, it will add three more books to the ObjectListView3 widget.
This demonstrates how to create the ObjectListview3 widget and update it after the application is running:
import wxfrom ObjectListView3 import ObjectListView, ColumnDefn
class Book(object):
"""
Model of the Book object
Contains the following attributes:
'ISBN', 'Author', 'Manufacturer', 'Title'
"""
def __init__(self, title, author, isbn, mfg):
self.isbn = isbn
self.author = author
self.mfg = mfg
self.title = title
class MainPanel(wx.Panel):
def __init__(self, parent):
super().__init__(parent=parent, id=wx.ID_ANY)
self.products = [
Book("wxPython in Action", "Robin Dunn", "1932394621", "Manning"),
Book("Hello World", "Warren and Carter Sande", "1933988495", "Manning"),
]
self.dataOlv = ObjectListView(
self, wx.ID_ANY, style=wx.LC_REPORT | wx.SUNKEN_BORDER
)
self.setBooks()
# Allow the cell values to be edited when double-clicked
self.dataOlv.cellEditMode = ObjectListView.CELLEDIT_SINGLECLICK
# create an update button
updateBtn = wx.Button(self, wx.ID_ANY, "Update OLV")
updateBtn.Bind(wx.EVT_BUTTON, self.updateControl)
# Create some sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
mainSizer.Add(self.dataOlv, 1, wx.ALL | wx.EXPAND, 5)
mainSizer.Add(updateBtn, 0, wx.ALL | wx.CENTER, 5)
self.SetSizer(mainSizer)
def updateControl(self, event):
"""
Update the ObjectListView
"""
product_dict = [
{
"title": "Core Python Programming",
"author": "Wesley Chun",
"isbn": "0132269937",
"mfg": "Prentice Hall",
},
{
"title": "Python Programming for the Absolute Beginner",
"author": "Michael Dawson",
"isbn": "1598631128",
"mfg": "Course Technology",
},
{
"title": "Learning Python",
"author": "Mark Lutz",
"isbn": "0596513984",
"mfg": "O'Reilly",
},
]
data = self.products + product_dict
self.dataOlv.SetObjects(data)
def setBooks(self, data=None):
self.dataOlv.SetColumns(
[
ColumnDefn("Title", "left", 220, "title"),
ColumnDefn("Author", "left", 200, "author"),
ColumnDefn("ISBN", "right", 100, "isbn"),
ColumnDefn("Mfg", "left", 180, "mfg"),
]
)
self.dataOlv.SetObjects(self.products)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(
self,
parent=None,
id=wx.ID_ANY,
title="ObjectListView Demo",
size=(800, 600),
)
panel = MainPanel(self)
class OLVDemoApp(wx.App):
def __init__(self, redirect=False, filename=None):
super().__init__(redirect, filename)
def OnInit(self):
# create frame here
frame = MainFrame()
frame.Show()
return True
def main():
"""
Run the demo
"""
app = OLVDemoApp()
app.MainLoop()
if __name__ == "__main__":
main()
When you initially run this code, you will see the following application:
When you press the “Update OLV” button, the application will update to look like the following:
The ObjectListView3 widget makes working with tabular data easy in wxPython. You also get nice editing, sorting and more from this widget via different mixins or styles. Give ObjectListView3 a try when you create your next wxPython GUI application.
The post ANN: ObjectListView3 for wxPython appeared first on Mouse Vs Python.
July 15, 2024
Creating Images in Your Terminal with Python and Rich Pixels
A newer Python package called Rich Pixels allows you to create images in your terminal and display them. Darren Burns, one of the team members from the Textual project, created this package.
Anyway, let’s find out how to use Rich Pixels!
InstallationYou can install Rich Pixels using Python’s pip utility. Here’s how:
python -m pip install rich-pixelsOnce you have Rich Pixels installed, you can try it out!
Displaying Images in the TerminalRich Pixels lets you take a pre-existing image and show it in your terminal. The higher the image’s resolution, the better the output will be. However, if your image has too many pixels, it probably won’t fit in your terminal, and much of it will be drawn off-screen.
For this example, you will use the Python Show Podcast logo and attempt to draw it in your terminal.
Open up your favorite Python editor and add the following code to it:
from rich_pixels import Pixelsfrom rich.console import Console
console = Console()
pixels = Pixels.from_image_path("python_show200.jpg")
console.print(pixels)
For this example, you will use a square image that is 200×200 pixels. You can run the code like this in your terminal:
python pixels.py
When you execute the command above, you will see something like this in your terminal:
As you can see, the image is a little pixelated and gets cut off at the bottom. Of course, this all depends on your monitor’s resolution.
Here’s what happens when you use an image that is 80×80 pixels:
You can also. use the Pillow package to create an image object and pass that the Rich Pixels too. Here’s how that might look:
with Image.open("path/to/image.png") as image:pixels = Pixels.from_image(image)
You can create or draw your images using Pillow. There is some coverage of this topic in my article, Drawing Shapes on Images with Python and Pillow which you could then pass to Rich Pixels to display it.
Wrapping UpRich Pixels is a fun way to add extra pizzazz to your terminal applications. Rich Pixels can also be used in a Textual application. While there probably aren’t a lot of use cases for this package, it’s a lot of fun to play around with.
Give it a try, and let me know what you create!
The post Creating Images in Your Terminal with Python and Rich Pixels appeared first on Mouse Vs Python.
June 18, 2024
How to Publish a Python Package to PyPI
Do you have a Python package that you’d like to share with the world? You should publish it on the Python Package Index (PyPI). The vast majority of Python packages are published there. The PyPI team has also created extensive documentation to help you on your packaging journey. This article does not aim to replace that documentation. Instead, it is just a shorter version of it using ObjectListView as an example.
The ObjectListView project for Python is based on a C# wrapper .NET ListView but for wxPython. You use ObjectListView as a replacement for wx.ListCtrl because its methods and attributes are simpler. Unfortunately, the original implementation died out in 2015 while a fork, ObjectListView2 died in 2019. For this article, you will learn how I forked it again and created ObjectListView3 and packaged it up for PyPI.
Creating a Package StructureWhen you create a Python package, you must follow a certain type of directory structure to build everything correctly. For example, your package files should go inside a folder named src. Within that folder, you will have your package sub-folder that contains something like an __init__.py and your other Python files.
The src folder’s contents will look something like this:
package_tutorial/| -- src/
| -- your_amazing_package/
| -- __init__.py
| -- example.py
The __init__.py file can be empty. You use that file to tell Python that the folder is a package and is importable. But wait! There’s more to creating a package than just your Python files!
You also should include the following:
A license fileThe pyproject.toml file which is used for configuring your package when you build it, among other thingsA README.md file to describe the package, how to install it, example usage, etcA tests folder, if you have any (and you should!)Go ahead and create these files and the tests folder. It’s okay if they are all blank right now. At this point, your folder structure will look like this:
package_tutorial/| -- LICENSE
| -- pyproject.toml
| -- README.md
| -- src/
| -- your_amazing_package/
| -- __init__.py
| -- example.py
| -- tests/Picking a Build Backend
The packaging tutorial mentions that you can choose various build backends for when you create your package. There are examples for the following:
HatchlingsetuptoolsFlitPDMYou add this build information in your pyproject.toml file. Here is an example you might use if you picked setuptools:
[build-system]requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
This section in your config is used by pip or build. These tools don’t actually do the heavy lifting of converting your source code into a wheel or other distribution package. That is handled by the build backend. You don’t have to add this section to your pyproject.toml file though. You will find that pip will default to setuptools if there isn’t anything listed.
Configuring MetadataAll the metadata for your package should go into a pyproject.toml file. In the case of ObjectListView, it didn’t have one of these files at all.
Here’s the generic example that the Packaging documentation gives:
[project]name = "example_package_YOUR_USERNAME_HERE"
version = "0.0.1"
authors = [
{ name="Example Author", email="author@example.com" },
]
description = "A small example package"
readme = "README.md"
requires-python = ">=3.8"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[project.urls]
Homepage = "https://github.com/pypa/sampleproject"
Issues = "https://github.com/pypa/sampleproject..."
Using this as a template, I created the following for the ObjectListView package:
[project]name = "ObjectListView3"
version = "1.3.4"
authors = [
{ name="Mike Driscoll", email="mike@somewhere.org" },
]
description = "An ObjectListView is a wrapper around the wx.ListCtrl that makes the list control easier to use."
readme = "README.md"
requires-python = ">=3.9"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
[project.urls]
Homepage = "https://github.com/driscollis/ObjectL..."
Issues = "https://github.com/driscollis/ObjectL..."
Now let’s go over what the various parts are in the above metadata:
name – The distribution name of your package. Make sure your name is unique!version – The package versionauthors – One or more authors including emails for eachdescription – A short, one-sentence summary of your packagereadme – A path to the file that contains a detailed description of the package. You may use a Markdown file here.requires-python – Tells which Python versions are supported by this packageclassifiers – Gives an index and some metadata for pipURLs – Extra links that you want to show on PyPI. In general, you would want to link to the source, documentation, issue trackers, etc.You can specify other information in your TOML file if you’d like. For full details, see the pyproject.toml guide.
READMEs and LicensesThe README file is almost always a Markdown file now. Take a look at other popular Python packages to see what you should include. Here are some recommended items:
How to install the packageBasic usage examplesLink to a guide or tutorialAn FAQ if you have oneThere are many licenses out there. Don’t take advice from anyone; buy a lawyer on that unless you know a lot about this topic. However, you can look at the licenses for other popular packages and use their license or one similar.
Generating a PackageNow you have the files you need, you are ready to generate your package. You will need to make sure you have PyPA’s build installed.
Here’s the command you’ll need for that:
python3 -m pip install --upgrade buildNext, you’ll want to run the following command from the same directory that your pyproject.toml file is in:
python3 -m buildYou’ll see a bunch of output from that command. When it’s done, you will have a dist A folder with a wheel (*.whl) file and a gzipped tarball inside it is called a built distribution. The tarball is a source distribution , while the wheel file is called a built distribution. When you use pip, it will try to find the built distribution first, but pip will fall back to the tarball if necessary.
Uploading / Publishing to PyPIYou now have the files you need to publish to share your package with the world on the Python Package Index (PyPI). However, you need to register an account on TestPyPI first. TestPyPI is a separate package index intended for testing and experimentation, which is perfect when you have never published a package before. To register an account, go to https://test.pypi.org/account/register/ and complete the steps on that page. It will require you to verify your email address, but other than that, it’s a very straightforward signup.
To securely upload your project, you’ll need a PyPI API token. Create one from your account and make sure to set the “Scope” to the “Entire account”. Don’t close the page until you have copied and saved your token or you’ll need to generate another one!
The last step before publishing is to install twine, a tool for uploading packages to PyPI. Here’s the command you’ll need to run in your terminal to get twine:
python3 -m pip install --upgrade twineOnce that has finished installing, you can run twine to upload your files. Make sure you run this command in your package folder where the new dist folder is:
python3 -m twine upload --repository testpypi dist/*You will see a prompt for your TestPyPI username and/or a password. The password is the API token you saved earlier. The directions in the documentation state that you should use __token__ as your username, but I don’t think it even asked for a username when I ran this command. I believe it only needed the API token itself.
After the command is complete, you will see some text stating which files were uploaded. You can view your package at https://test.pypi.org/project/example...
To verify you can install your new package, run this command:
python3 -m pip install --index-url https://test.pypi.org/simple/ --no-deps example-package-nameIf you specify the correct name, the package should be downloaded and installed. TestPyPI is not meant for permanent storage, though, so it will likely delete your package eventually to conserve space.
When you have thoroughly tested your package, you’ll want to upload it to the real PyPI site. Here are the steps you’ll need to follow:
Pick a memorable and unique package nameRegister an account at https://pypi.org. You’ll go through the same steps as you did on TestPyPIBe sure to verify your emailCreate an API key and save it on your machine or in a password vaultUse twine to upload the dist folder like this: python -m twine upload dist/*Install the package from the real PyPI as you normally wouldThat’s it! You’ve just published your first package!
Wrapping UpCreating a Python package takes time and thought. You want your package to be easy to install and easy to understand. Be sure to spend enough time on your README and other documentation to make using your package easy and fun. It’s not good to look up a package and not know which versions of Python it supports or how to install it. Make the process easy by uploading your package to the Python Package Index.
The post How to Publish a Python Package to PyPI appeared first on Mouse Vs Python.
June 3, 2024
Python Logging Book Released!
The latest Python book from Michael Driscoll is now out. You can get Python Logging today on any of your favorite platforms! The Kindle version of the book is only 99 cents for a limited time!
What does every new developer do when they are first learning to program? They print out strings to their terminal. It’s how we learn! But printing out to the terminal isn’t what you do with most professional applications.
In those cases, you log in. Sometimes, you log into multiple locations at once. These logs may serve as an audit trail for compliance purposes or help the engineers debug what went wrong.
Python Logging teaches you how to log in the Python programming language. Python is one of the most popular programming languages in the world. Python comes with a logging module that makes logging easy.
What You’ll LearnIn this book, you will learn how about the following:
Logger objectsLog levelsLog handlersFormatting your logsLog configurationLogging decoratorsRotating logsLogging and concurrencyand more!Where to PurchaseYou can get Python Logging at the following websites:
Gumroad (PDF and epub)Leanpub (PDF and epub)Amazon (Kindle and paperback)Download the CodeYou can get the code for the book from GitHub:
https://github.com/driscollis/pythonlogging
The post Python Logging Book Released! appeared first on Mouse Vs Python.