Python apps

Snapcraft can be used to package and distribute Python applications in a way that enables convenient installation by users.

The process of creating a snap for a Python application builds on standard Python packaging tools, making it possible to adapt or integrate an application’s existing packaging into the snap building process.

:information_source: For Python projects using pyproject.toml and PEP 517, use Snapcraft from its edge channel:
sudo snap refresh snapcraft --edge

Getting started

Snaps are defined in a single snapcraft.yaml file placed in a snap folder at the root of your project. This YAML file describes the application, its dependencies and how it should be built.

The following example shows an entire snapcraft.yaml file based on the snap of an existing project, liquidctl, a command line tool to control the power, cooling and LED status for a variety of USB-attached devices:

name: liquidctl
summary: a status and control utility to for power, cooling and LED components
description: |
     liquidctl is a command-line tool to monitor and control the fan speed,
     LED colour and pump volumes of specific power supplies, 
     motherboards, graphics cards and cooling solutions.
     The liquidctl snap unofficial and is not endorsed by the upsteam project.
version: test
base: core22
confinement: strict

parts:
  liquidctl:
    plugin: python
    source: .
    stage-packages:
       - python3-usb

apps:
  liquidctl:
    command: bin/liquidctl
    plugs:
      - raw-usb
      - hardware-observe

We’ll break this down in the following sections.

Metadata

The snapcraft.yaml file starts with a small amount of human-readable metadata, which is often already available in the project’s own packaging metadata or project README.md. This data is used in the presentation of the application in the Snap Store.

name: liquidctl
summary: a status and control utility to for power, cooling and LED components
description: |
     liquidctl is a command-line tool to monitor and control the fan speed,
     LED colour and pump volumes of specific power supplies, motherboards,
     graphics cards and cooling solutions.
     The liquidctl snap unofficial and is not endorsed by the upsteam project.
version: test

The name must be unique in the Snap Store. Valid snap names consist of lower-case alphanumeric characters and hyphens. They cannot be all numbers and they also cannot start or end with a hyphen.

The summary can not exceed 79 characters. More detail can be provided after description, where a chevron can be used to declare a multi-line description.

The version value is arbitrary. We’re calling this version test, but it could equally be a number. The output snap will include the version value in its filename. More advanced snaps set this value automatically with External metadata.

Base

The base keyword declares which base snap to use with the project. A base snap is a special kind of snap that provides a run-time environment alongside a minimal set of libraries that are common to most applications.

base: core22

This example uses core22, which is built from Ubuntu 22.04 LTS and is the currently recommended base for most snaps. See Base snaps for more details.

Security model

Snaps are containerised to ensure more predictable application behaviour and greater security. Unlike other container systems, the shape of this confinement can be changed through a set of interfaces. These are declarations that tell the system to give permission for specific tasks, such as accessing a webcam or binding to a network port.

The next section describes the level of confinement applied to the running application:

confinement: strict

Confinement determines the amount of access an application has to system resources, such as files, the network, peripherals and services. A value of strict is ideal because this isolates a snap, except for access permitted through its interfaces.

However, it is best to start creating a snap with a confinement level that provides warnings for confinement issues instead of strictly applying confinement. This is done by specifying the devmode (developer mode) confinement value. When a snap is in devmode, runtime confinement violations will be allowed but reported. These can be reviewed by running journalctl -xe.

Because devmode is only intended for development, snaps must be set to strict confinement before they can be published as “stable” in the Snap Store. Once an application is working well in devmode, you can review confinement violations, add appropriate interfaces, and switch to strict confinement.

Parts

Parts define what sources are needed to build the application. Parts can be anything: programs, libraries, or other needed assets, but for this example, we only need to use one part:

parts:
  liquidctl:
    plugin: python
    source: .
    stage-packages:
       - python3-usb

The plugin keyword is used to select a language or technology-specific plugin that knows how to perform the build steps for the project. In this example, the Python plugin is used to automate the build of this Python-based project.

The source keyword points to the source code of the Python project, which can be a local directory or remote Git repository. In this case, it refers to a local copy of the source code in a directory called liquidctl.

Apps

Apps are the commands you want to expose to users, and also the names of any background services the application provides. Each key under apps is the command name that should be made available on users’ systems.

The command specifies the path to the binary to be run. This is resolved relative to the root of the snap contents.

apps:
  liquidctl:
    command: bin/liquidctl
    plugs:
      - raw-usb
      - hardware-observe

If the command name matches the name of the snap specified in the top-level name keyword (see the Metadata section above), the binary file will be given the same name as the snap, as in this example.

If the names differ, the binary file name will be prefixed with the snap name to avoid naming conflicts between installed snaps. An example of this would be liquidctl.some-command.

The plugs section declares which interfaces an app needs to function, such as home to access local files, or network to access the network. In this case, liquidctl needs access to USB devices, which can be satisfied with the raw-usb interface for device input and output, and hardware-observe to enable the system to see which devices are connected.

Building the snap

First, clone the upstream project:

git clone https://github.com/liquidctl/liquidctl.git 

Inside this, create a snap directory and inside this create a snapcraft.yaml file that contains the above metadata.

The snap can now be built by running the snapcraft command in the project’s root directory (up one level from snap/snapcraft.yaml):

$ snapcraft
Executed: pull liquidctl
Executed: build liquidctl
Executed: stage liquidctl
Executed: prime liquidctl
Executed parts lifecycle
Generated snap metadata
Created snap package liquidctl_test_amd64.snap

The resulting snap can be installed locally. This requires the --dangerous flag because the snap is not signed by the Snap Store.

snap install liquidctl_test_amd64.snap --dangerous 

You can then try it out:

liquidctl -h

Removing the snap is simple too:

sudo snap remove liquidctl

You can also clean up the build environment, although this will slow down the next initial build:

snapcraft clean

By default, when you make a change to snapcraft.yaml, snapcraft only builds the parts that have changed. Cleaning a build, however, forces your snap to be rebuilt in a clean environment and will take longer.

Publishing your snap

To share your snaps you need to publish them in the Snap Store. First, create an account on the dashboard. Here you can customise how your snaps are presented, review your uploads and control publishing.

You’ll need to choose a unique “developer namespace” as part of the account creation process. This name will be visible by users and associated with your published snaps.

Make sure the snapcraft command is authenticated using the email address attached to your Snap Store account:

snapcraft login

Reserve a name for your snap

You can publish your own version of a snap, provided you do so under a name you have rights to. You can register a name on dashboard.snapcraft.io, or by running the following command:

snapcraft register mypythonsnap

Be sure to update the name: in your snapcraft.yaml to match this registered name, then run snapcraft again.

Upload your snap

Use snapcraft to push the snap to the Snap Store.

snapcraft upload --release=edge mypythonsnap_*.snap

If you’re happy with the result, you can commit the snapcraft.yaml to your GitHub repo and turn on automatic builds so any further commits automatically get released to edge, without requiring you to manually build locally.

Congratulations! You’ve just built and published your first Python snap. For a more in-depth overview of the snap building process, see Creating a snap.

3 Likes

@evan is there a reason this isn’t a wiki? I believe the intent of posts in this category to be wikis to facilitate crowd-sourcing.

Fixed, it’s now a wiki :slight_smile:

https://forum.snapcraft.io/t/building-a-python-snap-package/6766

We should include a prerequisite state of your project section at the beginning of this:

“You should be using setuptools in your project. You should be able to run python setup.py bdist_wheel without errors. If either of these are not true, please consult the setuptools documentation.”

@evan https://www.youtube.com/watch?v=G2y8Sx4B2Sk

It’s setuptools not setuputils

lol, and I’m not sure why it’s incorrectly wedged in my brain given no shortage of personal projects using it. Thanks, fixed.

@evan @degville Many Python applications require UTF-8 support but this requires workarounds due to the longstanding issue of poor locale support in snapd.

Many people encounter this issue and cook up their own solution to it so it might be best to document it and provide a best-practice solution.

The least intrusive and most generic solution is to add the following bits to the command part:

      LC_ALL: "C.UTF-8"
      LANG: "C.UTF-8"

This also works for non-python applications.

Where should I document this?

Also, a few more comments on this page:

It’s best to start a snap with the confinement in warning mode, rather than strictly applied. This is indicated through the devmode keyword. When a snap is in devmode, runtime confinement violations will be allowed but reported. These can be reviewed by running journalctl -xe.

  1. What is “warning mode”? Is this “devmode” confinement?
  2. It would be ideal if this part contained a link to more in-depth documentation on confinement.

It’s also useful to point to more resources about debugging the build on this page, like the “iterating without rebuilding” part of debugging: https://docs.snapcraft.io/debugging-building-snaps/6274

1 Like

This is a great guide, but I recommend linking to somewhere next at the bottom of the page. As someone reading the document, it feels slightly disorientating to be told to “Continue”, but having no indication as to where the content is that is being referred to.

Next Steps

Continue on to learn how you can bundle your app’s dependencies, such as system libraries, into this snap so your app is portable across Linux distributions.

1 Like

Which effectively disables the I18N. I have written a launcher remote part to solve this issue at my end: [OBSOLETED] The locales-launch remote part

1 Like

I confirm this fixes the issue I mentioned, with the added benefit that localization now actually works!

1 Like

I just hit this as well, a link to where you’re meant to proceed to would make this a lot less frustrating.

@timClicks @Odd_Bloke
I’ve added a possibly intended article to the page.

1 Like

When working on Ubuntu 18.04 and more, you should use the multipass VM to build the snap. You should also add base: core18 in the yaml file.

I’m trying to create my first snap and finding that it’s very difficult to figure out what I’m supposed to do to make things work as expected. Some of the documentation that I’ve read, in particular, is far less than helpful for me. On one particular document (https://snapcraft.io/docs/python-apps), I’ve decided to point out something I found that I think could be clearer to novices like myself if worded a little differently. I don’t know who updates the text of the document, but the link at the foot of it sent me to this forum.

The base keyword defines a special kind of snap that provides a run-time environment with a minimal set of libraries that are common to most applications. They’re transparent to users, but they need to be considered, and specified, when building a snap.

Does this passage tell me that “core18” is “a special kind of snap that provides a run-time environment with a minimal set of libraries that are common to most applications. They’re transparent to users, but they need to be considered, and specified, when building a snap.”?

Or does this passage tell me that, if I include “base: core18” in my app’s YAML file, then my own app is “a special kind of snap that provides a run-time environment with a minimal set of libraries that are common to most applications. They’re transparent to users, but they need to be considered, and specified, when building a snap.”?

I’d recommend altering the text to make this point more clear. Thanks!

Thanks for your feedback, and for taking the trouble to leave your comments. The documentation is generated automatically from the contents of this forum, where anyone can edit, so the docs are the result of a snap-team/community effort.

I can totally see what you mean here. I’ll reword this, and elsewhere where this paragraph is used, to make it more explicit. It should also link to our Base snap documentation, and we really should go through these tutorials to help make them easier to understand and more consistent with some of the snap/snapcraft changes that have been implemented since they were written.

Thanks again.

2 Likes

This doc assumes

  1. The developer knows what setuptools is
  2. The developer has a functioning setuptools configuration

This is not the case if a developer just created a python script and wants to put it into a snap. Maybe we need multiple tutorials for python? One for setuptools and one without setuptools?

source of this complaint

That user wrote this documentation after struggling with this page.

2 Likes

I ran into the same issues as the user you mentioned. The current docs really don’t state that using setuptools is mandatory.

Are there plans of updating these docs or is there some Bug tracker besides this thread to file feedback?

thanks for flagging this - I’ll go through the tutorial and update it.

Just noticed that the snapcraft.yaml file presented here does not exactly match what is grabbed from the git repo for this example. In the repo, confinement is “strict”, and the override-pull scriptlet does a “set-version” as well. Someone should make sure this page is sync’ed with that is in the repo.