SECCTRL-331: Python tutorial, a small PV tool in four stages
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
1 parent
ed72388f37
commit
b281b1ee78
3 files changed
+672
No files matched your search
@@ -8,3 +8,492 @@ tags:
|
||||
---
|
||||
|
||||
# PSI Python Environment
|
||||
|
||||
In this tutorial you build `pvshow`, a small Python tool that reads PVs over Channel Access and prints their value and timestamp. You start with a ten-line script and grow it in four stages into a package with a command, tests, a version tag and the files to package it. Every stage runs before you go on. The tool only reads PVs. Plan about an hour.
|
||||
|
||||

|
||||
|
||||
## Before you start
|
||||
|
||||
You need:
|
||||
|
||||
- An account on an LC machine (`<facility>-lc.psi.ch`) with RHEL9. The LC machines are the EPICS development and debugging environment that Controls IT operates, see [Development machines](../../2._Services_Portfolio/Services/02_computingandboot.md#development-machines).
|
||||
- Basic Python: functions, modules, running a script.
|
||||
- The name of a PV that you may read. Find one with the [`ioc` command](../../2._Services_Portfolio/Tools/01_ioc_utils.md#find-information): `ioc records --ioc <IOC> --name-only --limit 5` lists records of an IOC you know, and `ioc records "MTEST-.*:TEMP.*" --facility sls` finds temperature records of SLS test IOCs. Below, replace `<PV>` with its name.
|
||||
|
||||
Everything in this tutorial only reads. Do not write to PVs of a running machine while you learn; if you want to try writing, use your own test IOC.
|
||||
|
||||
Log in to the LC machine and check Python with `python3 --version`. It prints `Python 3.9` and a patch level: Python 3.9 is the system `python3` on every RHEL9 host. pip installs packages from the PSI package index `pypi.psi.ch`, which Puppet configures for pip on PSI hosts; hosts in the machine networks reach it too.
|
||||
|
||||
## Stage 1: one script
|
||||
|
||||
Create a project folder with a virtual environment (venv), activate it, and upgrade pip. The pip that a new venv brings on RHEL9 is too old to install the package of stage 2 in editable mode.
|
||||
|
||||
mkdir -p ~/git/pvshow
|
||||
cd ~/git/pvshow
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install pyepics
|
||||
|
||||
Your prompt now starts with `(.venv)`. In every new shell, run `cd ~/git/pvshow` and `source .venv/bin/activate` again. More about venvs is in [How-To: Manage Virtual Python Environments](../03_how_to/08_python_venv.md).
|
||||
|
||||
pip installs the Channel Access library `pyepics` with `numpy` and `pyparsing`; pyepics brings its own copy of the Channel Access client library. Controls also installs Channel Access libraries for the system Python as RPMs (`python3-pyepics` on the Controls consoles and the SLS and SwissFEL LC machines, `python3-CaChannel` on the Controls consoles and the LC machines of SLS, SwissFEL, HIPA, CRYO and TWLHA), but a venv does not see system packages. This tutorial uses pyepics because it exists both on the package index and as a RHEL9 RPM.
|
||||
|
||||
Create `read_pv.py`:
|
||||
|
||||
"""Read one EPICS PV over Channel Access and print its value."""
|
||||
import sys
|
||||
|
||||
import epics
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
sys.exit("usage: python3 read_pv.py <PV>")
|
||||
|
||||
name = sys.argv[1]
|
||||
value = epics.caget(name, timeout=2.0)
|
||||
if value is None:
|
||||
sys.exit(f"{name}: no connection")
|
||||
print(name, value)
|
||||
|
||||
Run it with your PV, then with a PV that does not exist:
|
||||
|
||||
python3 read_pv.py <PV>
|
||||
python3 read_pv.py TUT:DOES-NOT-EXIST; echo $?
|
||||
|
||||
The first prints the name and the value, for example `<PV> 21.5`. The second waits two seconds, prints `cannot connect to TUT:DOES-NOT-EXIST` (from pyepics) and `TUT:DOES-NOT-EXIST: no connection`, and `echo $?` prints `1`: `sys.exit()` with a text writes it to stderr and ends with exit code 1.
|
||||
|
||||
Channel Access finds a PV by searching for its name on the networks listed in the EPICS environment of the host. Puppet sets that environment up on the LC machines; on `hipa-lc9`, for example, the search goes to the HIPA CA gateway. `caq` shows what is set. If your PV does not connect, check its name and the output of `caq`. To reach PVs of another network, see [CA gateways](../../2._Services_Portfolio/Services/02_computingandboot.md#ca-gateways).
|
||||
|
||||
Put the project under Git from the start. Create `.gitignore`, so the venv stays out of Git, and commit:
|
||||
|
||||
printf '.venv/\n__pycache__/\n' > .gitignore
|
||||
git init
|
||||
git add .
|
||||
git commit -m "Stage 1: one script that reads one PV"
|
||||
|
||||
`git status` now reports a clean working tree, without `.venv`. In the following stages, commit at the end of each one in the same way.
|
||||
|
||||
## Stage 2: a package with a command
|
||||
|
||||
A script is run by its path. A package with a command is installed into the venv and run by its name, with options, a help text and exit codes that other programs can check. The finished project looks like this; in this stage you create `pyproject.toml` and the folder `pvshow/` with `__init__.py` and `cli.py`. The package folder sits directly next to `pyproject.toml` (a flat layout): nothing more to learn for a package of this size.
|
||||
|
||||

|
||||
|
||||
The command replaces the script. Remove it, create the package folder and its empty `__init__.py`, which makes the folder a package:
|
||||
|
||||
git rm read_pv.py
|
||||
mkdir pvshow
|
||||
touch pvshow/__init__.py
|
||||
|
||||
Create `pvshow/cli.py`:
|
||||
|
||||
"""pvshow: print the value and timestamp of an EPICS PV (read-only)."""
|
||||
import argparse
|
||||
import datetime
|
||||
import sys
|
||||
|
||||
import epics
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="pvshow", description="Print the value and timestamp of an EPICS PV.")
|
||||
parser.add_argument("pv", metavar="PV", help="name of the PV to read")
|
||||
parser.add_argument("--timeout", type=float, default=2.0,
|
||||
help="seconds to wait for the PV (default: %(default)s)")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
pv = epics.PV(args.pv, form="time", auto_monitor=False)
|
||||
value = None
|
||||
if pv.wait_for_connection(timeout=args.timeout):
|
||||
value = pv.get(timeout=args.timeout, use_monitor=False)
|
||||
if value is None:
|
||||
print(f"pvshow: {args.pv}: no connection within {args.timeout} s", file=sys.stderr)
|
||||
return 1
|
||||
stamp = datetime.datetime.fromtimestamp(pv.timestamp)
|
||||
print(args.pv, value, stamp.isoformat(sep=" ", timespec="milliseconds"))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
`form="time"` asks the IOC for the timestamp with the value; `auto_monitor=False` reads once instead of subscribing to changes. `main()` returns the exit code: 0 when the PV was read, 1 when it did not connect; argparse itself exits with 2 when the arguments are wrong.
|
||||
|
||||
Create `pyproject.toml` in `~/git/pvshow`:
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=64"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "pvshow"
|
||||
version = "0.1.0"
|
||||
description = "Print the value and timestamp of EPICS PVs"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
dependencies = ["pyepics"]
|
||||
|
||||
[project.scripts]
|
||||
pvshow = "pvshow.cli:main"
|
||||
|
||||
Line by line:
|
||||
|
||||
- `[build-system]`: pip builds the package with setuptools; version 64 or newer is needed for editable installs.
|
||||
- `name`, `version`, `description`: the package name, its version, one line about it.
|
||||
- `readme`: the file that describes the project.
|
||||
- `requires-python`: the Python versions the tool supports; 3.9 is the system Python on RHEL9.
|
||||
- `dependencies`: a list of the packages the tool needs. It must be a list: pip rejects `[project.dependencies]` written as a table with `` `project.dependencies` must be array ``.
|
||||
- `[project.scripts]`: the command `pvshow` calls the function `main` in the module `pvshow.cli`.
|
||||
|
||||
Create a short `README.md` (you complete it in stage 3), add `*.egg-info/` to `.gitignore` (pip writes the package metadata there), and install the project in editable mode, so the venv uses your source files directly:
|
||||
|
||||
echo "# pvshow" > README.md
|
||||
echo '*.egg-info/' >> .gitignore
|
||||
pip install -e .
|
||||
pvshow --help
|
||||
|
||||
The install ends with `Successfully installed pvshow-0.1.0`, and `pvshow --help` prints:
|
||||
|
||||
usage: pvshow [-h] [--timeout TIMEOUT] PV
|
||||
|
||||
Print the value and timestamp of an EPICS PV.
|
||||
|
||||
positional arguments:
|
||||
PV name of the PV to read
|
||||
|
||||
optional arguments:
|
||||
-h, --help show this help message and exit
|
||||
--timeout TIMEOUT seconds to wait for the PV (default: 2.0)
|
||||
|
||||
Run it:
|
||||
|
||||
pvshow <PV>
|
||||
pvshow --timeout 1 TUT:DOES-NOT-EXIST; echo $?
|
||||
|
||||
The first prints name, value and timestamp, for example `<PV> 21.5 2026-11-25 14:04:47.849`. The second prints `pvshow: TUT:DOES-NOT-EXIST: no connection within 1.0 s` and exit code `1`. `which pvshow` shows where the command lives: `~/git/pvshow/.venv/bin/pvshow`. Because the install is editable, a change in `cli.py` takes effect at the next run, without installing again. Commit the stage.
|
||||
|
||||
## Stage 3: a tool you can rely on
|
||||
|
||||
Now the tool reads several PVs at once, prints JSON for other programs, can keep running and print every change, logs what goes wrong, and has tests. The reading moves into its own module, `pvshow/reader.py`, so that it can be tested without the command line:
|
||||
|
||||
"""Read EPICS PVs over Channel Access. Read-only: nothing here writes."""
|
||||
import datetime
|
||||
import logging
|
||||
|
||||
import epics
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _result(name, value, timestamp):
|
||||
if hasattr(value, "tolist"): # numpy arrays and numbers -> plain Python
|
||||
value = value.tolist()
|
||||
stamp = datetime.datetime.fromtimestamp(timestamp)
|
||||
return {"name": name, "value": value,
|
||||
"timestamp": stamp.isoformat(sep=" ", timespec="milliseconds")}
|
||||
|
||||
|
||||
def read_pvs(names, timeout):
|
||||
"""Read each PV once. Return the results and the names that did not connect."""
|
||||
pvs = [epics.PV(name, form="time", auto_monitor=False) for name in names]
|
||||
results, failed = [], []
|
||||
for pv in pvs:
|
||||
value = None
|
||||
if pv.wait_for_connection(timeout=timeout):
|
||||
value = pv.get(timeout=timeout, use_monitor=False)
|
||||
if value is None:
|
||||
log.error("%s: no connection within %s s", pv.pvname, timeout)
|
||||
failed.append(pv.pvname)
|
||||
continue
|
||||
results.append(_result(pv.pvname, value, pv.timestamp))
|
||||
return results, failed
|
||||
|
||||
|
||||
def follow(names, on_update):
|
||||
"""Call on_update(result) on every change of the PVs.
|
||||
|
||||
Returns the PV objects: keep a reference to them as long as you follow.
|
||||
"""
|
||||
def on_change(pvname=None, value=None, timestamp=None, **kwargs):
|
||||
on_update(_result(pvname, value, timestamp))
|
||||
|
||||
def on_connection(pvname=None, conn=None, **kwargs):
|
||||
if conn:
|
||||
log.info("%s: connected", pvname)
|
||||
else:
|
||||
log.warning("%s: disconnected", pvname)
|
||||
|
||||
return [epics.PV(name, form="time", callback=on_change,
|
||||
connection_callback=on_connection) for name in names]
|
||||
|
||||
`read_pvs()` creates all PV objects first, so their searches run at the same time. `follow()` subscribes to the PVs: pyepics calls `on_change` for every new value and `on_connection` when a PV connects or disconnects.
|
||||
|
||||
Replace `pvshow/cli.py` with:
|
||||
|
||||
"""pvshow: print the value and timestamp of EPICS PVs (read-only)."""
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
from pvshow import reader
|
||||
|
||||
log = logging.getLogger("pvshow")
|
||||
|
||||
|
||||
def print_result(result, as_json):
|
||||
if as_json:
|
||||
print(json.dumps(result), flush=True)
|
||||
else:
|
||||
print(f"{result['name']:<30} {result['value']!s:>12} {result['timestamp']}",
|
||||
flush=True)
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="pvshow", description="Print the value and timestamp of EPICS PVs.")
|
||||
parser.add_argument("pvs", nargs="+", metavar="PV", help="name of a PV to read")
|
||||
parser.add_argument("--timeout", type=float, default=2.0,
|
||||
help="seconds to wait for each PV (default: %(default)s)")
|
||||
parser.add_argument("--json", action="store_true",
|
||||
help="print one JSON object per line")
|
||||
parser.add_argument("--follow", action="store_true",
|
||||
help="keep running and print every change, until Ctrl-C")
|
||||
parser.add_argument("-v", "--verbose", action="store_true", help="log more detail")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
# Results go to stdout, log messages to stderr; under systemd both reach the journal.
|
||||
logging.basicConfig(level=logging.DEBUG if args.verbose else logging.INFO,
|
||||
format="%(levelname)s %(message)s")
|
||||
|
||||
if args.follow:
|
||||
# systemd stops a service with SIGTERM: end as cleanly as with Ctrl-C.
|
||||
signal.signal(signal.SIGTERM, signal.default_int_handler)
|
||||
pvs = reader.follow(args.pvs, lambda result: print_result(result, args.json))
|
||||
log.info("following %d PV(s), stop with Ctrl-C", len(pvs))
|
||||
try:
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
|
||||
results, failed = reader.read_pvs(args.pvs, args.timeout)
|
||||
for result in results:
|
||||
print_result(result, args.json)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Results go to stdout and log messages to stderr. When the tool runs as a systemd service, both reach the journal, which is collected centrally, see [Logging](../../2._Services_Portfolio/Services/03_devops.md#what-your-software-must-do). `flush=True` writes each line at once, also when stdout is not a terminal. systemd stops a service with SIGTERM; the signal handler ends `--follow` as cleanly as Ctrl-C.
|
||||
|
||||
Create the folder `tests` with an empty `tests/__init__.py`:
|
||||
|
||||
mkdir tests
|
||||
touch tests/__init__.py
|
||||
|
||||
Then create `tests/test_pvshow.py`. The tests replace `epics.PV` with a stand-in, so they run without an EPICS network:
|
||||
|
||||
"""Tests that run without an EPICS network: the Channel Access PV class is replaced."""
|
||||
import contextlib
|
||||
import io
|
||||
import json
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
from pvshow import cli, reader
|
||||
|
||||
|
||||
class FakePV:
|
||||
"""Stands in for epics.PV: TEST:OK is connected, every other name is not."""
|
||||
values = {"TEST:OK": 21.5}
|
||||
|
||||
def __init__(self, name, **kwargs):
|
||||
self.pvname = name
|
||||
self.timestamp = 0.0
|
||||
|
||||
def wait_for_connection(self, timeout=None):
|
||||
return self.pvname in self.values
|
||||
|
||||
def get(self, timeout=None, use_monitor=None):
|
||||
return self.values.get(self.pvname)
|
||||
|
||||
|
||||
@mock.patch("pvshow.reader.epics.PV", FakePV)
|
||||
class ReadTest(unittest.TestCase):
|
||||
|
||||
def test_read_connected_and_missing(self):
|
||||
with self.assertLogs("pvshow.reader", level="ERROR"):
|
||||
results, failed = reader.read_pvs(["TEST:OK", "TEST:MISSING"], timeout=0.1)
|
||||
self.assertEqual([r["value"] for r in results], [21.5])
|
||||
self.assertEqual(failed, ["TEST:MISSING"])
|
||||
|
||||
def test_exit_code_and_json(self):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out):
|
||||
self.assertEqual(cli.main(["--json", "TEST:OK"]), 0)
|
||||
self.assertEqual(json.loads(out.getvalue())["name"], "TEST:OK")
|
||||
with self.assertLogs("pvshow.reader", level="ERROR"):
|
||||
self.assertEqual(cli.main(["--timeout", "0.1", "TEST:MISSING"]), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
Replace `README.md` with a description that states the requirements for each way of installing the tool, as every Controls Python tool does:
|
||||
|
||||
# pvshow
|
||||
|
||||
A small Python tool that reads EPICS PVs over Channel Access. It only reads, it never writes.
|
||||
|
||||
## Usage
|
||||
|
||||
pvshow [--timeout SECONDS] [--json] [--follow] [-v] PV [PV ...]
|
||||
|
||||
Reads each PV once and prints name, value and timestamp. `--json` prints one JSON object per
|
||||
line. `--follow` keeps running and prints every change until Ctrl-C. Results go to stdout, log
|
||||
messages to stderr. Exit code 0: all PVs read. 1: at least one PV did not connect. 2: wrong
|
||||
arguments.
|
||||
|
||||
## Requirements
|
||||
|
||||
- pip in a venv: Python 3.9 or newer, a current pip, and access to a package index for
|
||||
`pyepics` (it pulls in `numpy` and `pyparsing`). On PSI hosts managed by Puppet, pip uses
|
||||
the PSI package index `pypi.psi.ch`, also from the machine networks.
|
||||
- RPM: the system `python3` and the RPM `python3-pyepics`.
|
||||
|
||||
## Install for development
|
||||
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate
|
||||
pip install --upgrade pip
|
||||
pip install -e .
|
||||
|
||||
## Tests
|
||||
|
||||
The tests replace the Channel Access calls and need no EPICS network:
|
||||
|
||||
python -m unittest -v
|
||||
|
||||
Give the stage a new version: in `pyproject.toml`, change `version = "0.1.0"` to `version = "0.2.0"`. Install again, run the tests, and try the new options:
|
||||
|
||||
pip install -e .
|
||||
python -m unittest -v
|
||||
pvshow <PV> TUT:DOES-NOT-EXIST; echo $?
|
||||
pvshow --json <PV>
|
||||
pvshow --follow <PV>
|
||||
|
||||
- The tests print `test_exit_code_and_json ... ok`, `test_read_connected_and_missing ... ok` and `OK`.
|
||||
- With two PVs, the readable one is printed as a line, the other one logged as `ERROR TUT:DOES-NOT-EXIST: no connection within 2.0 s`, and the exit code is `1`.
|
||||
- `--json` prints one JSON object per line, for example `{"name": "<PV>", "value": 21.5, "timestamp": "2026-11-25 14:05:23.377"}`.
|
||||
- `--follow` logs `INFO following 1 PV(s), stop with Ctrl-C` and `INFO <PV>: connected`, then prints the current value and a new line for every change. Stop it with Ctrl-C; the exit code is `0`.
|
||||
|
||||
Commit the stage.
|
||||
|
||||
## Stage 4: ready to hand over
|
||||
|
||||
Before others use the tool, it gets a version they can ask for, a tag in Git, and the files to package it. How you package and deliver it is your choice; this stage shows two ways briefly.
|
||||
|
||||
Let the tool report its version. In `pvshow/cli.py`, add the import and the option:
|
||||
|
||||
from importlib.metadata import version
|
||||
|
||||
parser.add_argument("--version", action="version",
|
||||
version=f"%(prog)s {version('pvshow')}")
|
||||
|
||||
The import goes with the other imports; the option after `--verbose`. In `pyproject.toml`, set `version = "1.0.0"`. Add the build output to `.gitignore`, install again and check:
|
||||
|
||||
printf 'build/\ndist/\nRPMS/\n' >> .gitignore
|
||||
pip install -e .
|
||||
pvshow --version
|
||||
|
||||
It prints `pvshow 1.0.0`.
|
||||
|
||||
A wheel and a source archive for a package index. `build` creates both in `dist/`:
|
||||
|
||||
pip install build
|
||||
python -m build
|
||||
|
||||
It ends with `Successfully built pvshow-1.0.0.tar.gz and pvshow-1.0.0-py3-none-any.whl`. `pip install dist/pvshow-1.0.0-py3-none-any.whl` installs the tool in any venv; to share it, upload the two files to the package index you use, for example with `twine upload --repository-url <index URL> dist/*`.
|
||||
|
||||
An RPM for RHEL9. For an RPM, every dependency must exist as a RHEL9 `python3-*` RPM, which the RPM declares with `Requires:` instead of bundling it (`pyepics` is `python3-pyepics`); the tool must install no files to absolute system paths; and pure Python is built as `noarch`. The rules are in [Delivering your own Python software](../../2._Services_Portfolio/Services/03_devops.md#delivering-your-own-python-software). The setuptools of the RHEL9 system Python (version 53) cannot read the `[project]` table, so the spec packages the wheel from `dist/` instead of building from the source. Create `pvshow.spec`:
|
||||
|
||||
%define name pvshow
|
||||
%define version 1.0.0
|
||||
%define release 0%{?dist}
|
||||
|
||||
Name: %{name}
|
||||
Version: %{version}
|
||||
Release: %{release}
|
||||
License: MIT
|
||||
Summary: Print the value and timestamp of EPICS PVs
|
||||
Source0: %{name}-%{version}-py3-none-any.whl
|
||||
BuildArch: noarch
|
||||
Requires: python3-pyepics
|
||||
BuildRequires: python3-rpm-macros python3-pip
|
||||
|
||||
%global source_date_epoch_from_changelog 0
|
||||
|
||||
%description
|
||||
Print the value and timestamp of EPICS PVs. Read-only.
|
||||
|
||||
# Build in this directory from the wheel in dist/ (python -m build);
|
||||
# the RPM ends up in RPMS/noarch/.
|
||||
%define _topdir %(pwd)
|
||||
%define _sourcedir %{_topdir}/dist
|
||||
%define _builddir %{_topdir}
|
||||
|
||||
%prep
|
||||
%{__mkdir_p} RPMS
|
||||
|
||||
%install
|
||||
%{__python3} -m pip install --root %{buildroot} --prefix %{_prefix} --no-deps --no-index --no-compile %{SOURCE0}
|
||||
|
||||
%files
|
||||
%{_bindir}/pvshow
|
||||
%{python3_sitelib}/pvshow/
|
||||
%{python3_sitelib}/pvshow-%{version}.dist-info/
|
||||
|
||||
Put your project's licence in `License:`. On the LC machine, which has `rpm-build`, build the RPM after `python -m build` and list its content:
|
||||
|
||||
rpmbuild -bb pvshow.spec
|
||||
rpm -qlp RPMS/noarch/pvshow-1.0.0-0.el9.noarch.rpm
|
||||
|
||||
The list contains `/usr/bin/pvshow` and the modules under `/usr/lib/python3.9/site-packages/pvshow/`. If `rpmbuild` stops with "Failed build dependencies", the host lacks one of the `BuildRequires` packages.
|
||||
|
||||
Add a release section to `README.md`:
|
||||
|
||||
## Release
|
||||
|
||||
Change the version in `pyproject.toml` and in `pvshow.spec` in the same commit, then tag
|
||||
that commit with the bare version number, for example `git tag 1.0.0`.
|
||||
|
||||
Commit, then publish the repository. In Gitea, create an empty repository `pvshow` (no README, no licence) in your group's organisation; [Use Git / Gitea](../03_how_to/12_git_gitea.md) explains the Gitea side. Push, and tag the release:
|
||||
|
||||
git add .
|
||||
git commit -m "Stage 4: version 1.0.0, packaging files"
|
||||
git remote add origin https://gitea.psi.ch/<organisation>/pvshow.git
|
||||
git push -u origin HEAD
|
||||
git tag 1.0.0
|
||||
git push origin 1.0.0
|
||||
|
||||
The repository page in Gitea shows your files and the tag `1.0.0`.
|
||||
|
||||
Getting the tool onto Controls hosts is done with [Autodeploy](../../2._Services_Portfolio/Services/11_autodeploy.md); the policy for Python software on the Controls platform is in [Python software](../../2._Services_Portfolio/Services/03_devops.md#python-software).
|
||||
|
||||
## What you have learned
|
||||
|
||||
You have grown a script into a Python tool the Controls way: a package with standard metadata in `pyproject.toml` and a command, installed with pip into a venv in editable mode; output on stdout and log messages on stderr, so that it works as a service; tests that run without an EPICS network; a README with the requirements per install route; a version and a tag in Gitea; and a wheel, a source archive and an RPM spec, ready for the packaging you choose.
|
||||
|
||||
Where to go next:
|
||||
|
||||
- [How-To: Manage Virtual Python Environments](../03_how_to/08_python_venv.md): reproduce an environment on another machine, run a tool from a service, pixi as an alternative.
|
||||
- [Python software](../../2._Services_Portfolio/Services/03_devops.md#python-software): the policy and the install routes.
|
||||
- [IOC Utils](../../2._Services_Portfolio/Tools/01_ioc_utils.md): a Controls Python tool in daily use.
|
||||
- [How-To: Use Containers](../03_how_to/09_containers.md): run a Python service in a container.
|
||||
- [How-To: Build and Deploy RPMs](../03_how_to/07_build_deploy_rpms.md).
|
||||
@@ -0,0 +1,81 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 460" role="img" aria-labelledby="t d">
|
||||
<title id="t">Layout of the pvshow project and how the command finds its code</title>
|
||||
<desc id="d">The finished project folder pvshow holds pyproject.toml (name, version, dependencies, command), README.md (requirements per install route), .gitignore (keeps .venv and build output out of Git), pvshow.spec (RPM, if you choose one), the package folder pvshow with __init__.py, cli.py (main: options and output) and reader.py (reads PVs, follows changes), the folder tests with test_pvshow.py, which needs no EPICS network, and .venv, which is not in Git. The line pvshow = "pvshow.cli:main" in pyproject.toml makes pip write the script .venv/bin/pvshow, which calls main() in pvshow/cli.py.</desc>
|
||||
<style>
|
||||
text { font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; fill: #212121; }
|
||||
.mono { font-family: "JetBrains Mono", SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; }
|
||||
.h { font-size: 18px; font-weight: 600; }
|
||||
.t { font-size: 15px; }
|
||||
.cap { font-size: 15px; fill: #5f6368; }
|
||||
.code { font-size: 15px; fill: #303fa1; }
|
||||
.card { fill: #f7f8fc; stroke: #e1e4f2; stroke-width: 1.5; }
|
||||
.tile { fill: #e8eaf6; }
|
||||
.ic { fill: none; stroke: #4051b5; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.icm { fill: none; stroke: #757575; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.wire { fill: none; stroke: #9fa8da; stroke-width: 2; }
|
||||
.track { fill: none; stroke: #4051b5; stroke-width: 2.5; }
|
||||
</style>
|
||||
<defs>
|
||||
<symbol id="i-folder" viewBox="0 0 24 24"><path d="M3 7.5V18a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V9.5a2 2 0 0 0-2-2h-7l-2-2.5H5a2 2 0 0 0-2 2z"/></symbol>
|
||||
<symbol id="i-file" viewBox="0 0 24 24"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></symbol>
|
||||
<symbol id="i-link" viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/></symbol>
|
||||
<marker id="ah" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M1 1l8 4-8 4z" fill="#4051b5"/></marker>
|
||||
</defs>
|
||||
|
||||
<rect x="1" y="1" width="958" height="458" rx="10" fill="#ffffff" stroke="#e0e0e0" stroke-width="1.5"/>
|
||||
|
||||
<!-- left card: the tree -->
|
||||
<g transform="translate(24 24)">
|
||||
<rect class="card" width="520" height="412" rx="8"/>
|
||||
<rect class="tile" x="18" y="18" width="44" height="44" rx="8"/><use href="#i-folder" class="ic" x="28" y="28" width="24" height="24"/>
|
||||
<text x="74" y="46" class="h">Project <tspan class="mono" style="fill:#212121">pvshow/</tspan></text>
|
||||
|
||||
<path d="M30 80v304M30 106h14M30 138h14M30 170h14M30 202h14M30 234h14M30 350h14M30 382h14M70 250v68M70 262h12M70 290h12M70 318h12" class="wire"/>
|
||||
<use href="#i-file" class="icm" x="48" y="98" width="18" height="18"/><text x="74" y="112" class="mono code">pyproject.toml</text>
|
||||
<text x="256" y="112" class="cap">metadata and the command</text>
|
||||
<use href="#i-file" class="icm" x="48" y="130" width="18" height="18"/><text x="74" y="144" class="mono code">README.md</text>
|
||||
<text x="256" y="144" class="cap">requirements per install route</text>
|
||||
<use href="#i-file" class="icm" x="48" y="162" width="18" height="18"/><text x="74" y="176" class="mono code">.gitignore</text>
|
||||
<text x="256" y="176" class="cap">keeps .venv/ and builds out of Git</text>
|
||||
<use href="#i-file" class="icm" x="48" y="194" width="18" height="18"/><text x="74" y="208" class="mono code">pvshow.spec</text>
|
||||
<text x="256" y="208" class="cap">RPM, if you choose one (stage 4)</text>
|
||||
<use href="#i-folder" class="icm" x="48" y="226" width="18" height="18"/><text x="74" y="240" class="mono code">pvshow/</text>
|
||||
<text x="256" y="240" class="cap">the package</text>
|
||||
<use href="#i-file" class="icm" x="86" y="254" width="18" height="18"/><text x="112" y="268" class="mono code">__init__.py</text>
|
||||
<text x="256" y="268" class="cap">makes pvshow a package</text>
|
||||
<use href="#i-file" class="ic" x="86" y="282" width="18" height="18"/><text x="112" y="296" class="mono code" font-weight="600">cli.py</text>
|
||||
<text x="256" y="296" class="t">main(): options and output</text>
|
||||
<use href="#i-file" class="icm" x="86" y="310" width="18" height="18"/><text x="112" y="324" class="mono code">reader.py</text>
|
||||
<text x="256" y="324" class="cap">reads PVs, follows changes</text>
|
||||
<use href="#i-folder" class="icm" x="48" y="342" width="18" height="18"/><text x="74" y="356" class="mono code">tests/</text>
|
||||
<text x="256" y="356" class="cap">test_pvshow.py, no EPICS needed</text>
|
||||
<use href="#i-folder" class="icm" x="48" y="374" width="18" height="18"/><text x="74" y="388" class="mono code" style="fill:#757575">.venv/</text>
|
||||
<text x="256" y="388" class="cap">virtual environment, not in Git</text>
|
||||
</g>
|
||||
|
||||
<!-- right card: entry point mechanism -->
|
||||
<g transform="translate(568 24)">
|
||||
<rect width="368" height="412" rx="8" fill="#f7f8fc" stroke="#4051b5" stroke-width="2"/>
|
||||
<rect class="tile" x="18" y="18" width="44" height="44" rx="8"/><use href="#i-link" class="ic" x="28" y="28" width="24" height="24"/>
|
||||
<text x="74" y="38" class="h">How the command</text>
|
||||
<text x="74" y="60" class="h">finds your code</text>
|
||||
|
||||
<rect x="18" y="86" width="332" height="62" rx="8" fill="#ffffff" stroke="#e1e4f2" stroke-width="1.5"/>
|
||||
<text x="32" y="110" class="cap">in pyproject.toml</text>
|
||||
<text x="32" y="134" class="mono code">pvshow = "pvshow.cli:main"</text>
|
||||
|
||||
<path class="track" d="M184 152v30" marker-end="url(#ah)"/>
|
||||
<text x="196" y="173" class="cap">pip install writes</text>
|
||||
|
||||
<rect x="18" y="190" width="332" height="62" rx="8" fill="#ffffff" stroke="#e1e4f2" stroke-width="1.5"/>
|
||||
<text x="32" y="214" class="cap">a script on your PATH</text>
|
||||
<text x="32" y="238" class="mono code">.venv/bin/pvshow</text>
|
||||
|
||||
<path class="track" d="M184 256v30" marker-end="url(#ah)"/>
|
||||
<text x="196" y="277" class="cap">which calls</text>
|
||||
|
||||
<rect x="18" y="294" width="332" height="62" rx="8" fill="#ffffff" stroke="#e1e4f2" stroke-width="1.5"/>
|
||||
<text x="32" y="318" class="cap">in pvshow/cli.py</text>
|
||||
<text x="32" y="342" class="mono code">main()</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.3 KiB |
@@ -0,0 +1,102 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 470" role="img" aria-labelledby="t d">
|
||||
<title id="t">The four stages of the pvshow tool</title>
|
||||
<desc id="d">Stage 1, one script: read_pv.py reads one PV, run with python3 read_pv.py PV in a venv. Stage 2, a package with a command: pyproject.toml and pvshow/cli.py, installed with pip install -e ., run as pvshow PV with a timeout and exit codes. Stage 3, a tool you can rely on: several PVs, --json, --follow, log messages on stderr, and unit tests in tests/ that run with python -m unittest without an EPICS network. Stage 4, ready to hand over: version 1.0.0 with a tag, python -m build for a wheel and a source archive, and pvshow.spec for an RPM. How you package it is your choice; it reaches Controls hosts with autodeploy.</desc>
|
||||
<style>
|
||||
text { font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; fill: #212121; }
|
||||
.mono { font-family: "JetBrains Mono", SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace; }
|
||||
.h { font-size: 18px; font-weight: 600; }
|
||||
.t { font-size: 15px; }
|
||||
.cap { font-size: 15px; fill: #5f6368; }
|
||||
.code { font-size: 14px; fill: #303fa1; }
|
||||
.card { fill: #f7f8fc; stroke: #e1e4f2; stroke-width: 1.5; }
|
||||
.tile { fill: #e8eaf6; }
|
||||
.ic { fill: none; stroke: #4051b5; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.icm { fill: none; stroke: #757575; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.wire { fill: none; stroke: #9fa8da; stroke-width: 2; }
|
||||
.track { fill: none; stroke: #4051b5; stroke-width: 2.5; }
|
||||
</style>
|
||||
<defs>
|
||||
<symbol id="i-file" viewBox="0 0 24 24"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></symbol>
|
||||
<symbol id="i-box" viewBox="0 0 24 24"><path d="M12 3l8 4.5v9L12 21l-8-4.5v-9z"/><path d="M4 7.5l8 4.5 8-4.5M12 12v9"/></symbol>
|
||||
<symbol id="i-check" viewBox="0 0 24 24"><path d="M12 3l7 3v5c0 4.5-3 8-7 10-4-2-7-5.5-7-10V6z"/><path d="M8.5 12l2.5 2.5 4.5-5"/></symbol>
|
||||
<symbol id="i-pkg" viewBox="0 0 24 24"><rect x="3" y="7" width="18" height="13" rx="2"/><path d="M3 11h18M9 4h6l2 3H7z"/></symbol>
|
||||
<marker id="ah" viewBox="0 0 10 10" refX="8" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M1 1l8 4-8 4z" fill="#4051b5"/></marker>
|
||||
</defs>
|
||||
|
||||
<rect x="1" y="1" width="958" height="468" rx="10" fill="#ffffff" stroke="#e0e0e0" stroke-width="1.5"/>
|
||||
|
||||
<!-- track on top -->
|
||||
<path class="track" d="M143 44h204" marker-end="url(#ah)"/><path class="track" d="M377 44h204" marker-end="url(#ah)"/><path class="track" d="M611 44h204" marker-end="url(#ah)"/>
|
||||
<g font-size="15" font-weight="700" text-anchor="middle">
|
||||
<circle cx="129" cy="44" r="14" fill="#4051b5"/><text x="129" y="49.5" style="fill:#fff">1</text>
|
||||
<circle cx="363" cy="44" r="14" fill="#4051b5"/><text x="363" y="49.5" style="fill:#fff">2</text>
|
||||
<circle cx="597" cy="44" r="14" fill="#4051b5"/><text x="597" y="49.5" style="fill:#fff">3</text>
|
||||
<circle cx="831" cy="44" r="14" fill="#4051b5"/><text x="831" y="49.5" style="fill:#fff">4</text>
|
||||
</g>
|
||||
<path class="wire" d="M129 58v16M363 58v16M597 58v16M831 58v16" stroke-dasharray="3 4"/>
|
||||
|
||||
<!-- card 1 -->
|
||||
<g transform="translate(24 76)">
|
||||
<rect class="card" width="210" height="300" rx="8"/>
|
||||
<rect class="tile" x="18" y="18" width="44" height="44" rx="8"/><use href="#i-file" class="ic" x="28" y="28" width="24" height="24"/>
|
||||
<text x="74" y="38" class="h">One</text>
|
||||
<text x="74" y="60" class="h">script</text>
|
||||
<text x="18" y="100" class="mono code">read_pv.py</text>
|
||||
<text x="18" y="130" class="t">reads one PV</text>
|
||||
<text x="18" y="150" class="t">and prints it</text>
|
||||
<path d="M18 236h174" stroke="#e1e4f2" stroke-width="1.5"/>
|
||||
<text x="18" y="262" class="mono code">python3 read_pv.py</text>
|
||||
<text x="18" y="282" class="mono code"> <PV></text>
|
||||
</g>
|
||||
|
||||
<!-- card 2 -->
|
||||
<g transform="translate(258 76)">
|
||||
<rect class="card" width="210" height="300" rx="8"/>
|
||||
<rect class="tile" x="18" y="18" width="44" height="44" rx="8"/><use href="#i-box" class="ic" x="28" y="28" width="24" height="24"/>
|
||||
<text x="74" y="38" class="h">A package with</text>
|
||||
<text x="74" y="60" class="h">a command</text>
|
||||
<text x="18" y="100" class="mono code">pyproject.toml</text>
|
||||
<text x="18" y="122" class="mono code">pvshow/cli.py</text>
|
||||
<text x="18" y="152" class="t">timeout, exit codes,</text>
|
||||
<text x="18" y="172" class="t">--help</text>
|
||||
<path d="M18 236h174" stroke="#e1e4f2" stroke-width="1.5"/>
|
||||
<text x="18" y="262" class="mono code">pip install -e .</text>
|
||||
<text x="18" y="284" class="mono code">pvshow <PV></text>
|
||||
</g>
|
||||
|
||||
<!-- card 3 -->
|
||||
<g transform="translate(492 76)">
|
||||
<rect class="card" width="210" height="300" rx="8"/>
|
||||
<rect class="tile" x="18" y="18" width="44" height="44" rx="8"/><use href="#i-check" class="ic" x="28" y="28" width="24" height="24"/>
|
||||
<text x="74" y="38" class="h">A tool you</text>
|
||||
<text x="74" y="60" class="h">can rely on</text>
|
||||
<text x="18" y="100" class="mono code">pvshow/reader.py</text>
|
||||
<text x="18" y="122" class="mono code">tests/</text>
|
||||
<text x="18" y="152" class="t">several PVs, JSON,</text>
|
||||
<text x="18" y="172" class="t">follow mode, logs</text>
|
||||
<text x="18" y="192" class="t">on stderr</text>
|
||||
<path d="M18 236h174" stroke="#e1e4f2" stroke-width="1.5"/>
|
||||
<text x="18" y="262" class="mono code">python -m unittest</text>
|
||||
<text x="18" y="284" class="cap">no EPICS network needed</text>
|
||||
</g>
|
||||
|
||||
<!-- card 4 -->
|
||||
<g transform="translate(726 76)">
|
||||
<rect width="210" height="300" rx="8" fill="#f7f8fc" stroke="#4051b5" stroke-width="2"/>
|
||||
<rect class="tile" x="18" y="18" width="44" height="44" rx="8"/><use href="#i-pkg" class="ic" x="28" y="28" width="24" height="24"/>
|
||||
<text x="74" y="38" class="h">Ready to</text>
|
||||
<text x="74" y="60" class="h">hand over</text>
|
||||
<text x="18" y="100" class="t">version and tag</text>
|
||||
<text x="18" y="122" class="mono code">1.0.0</text>
|
||||
<text x="18" y="152" class="t">wheel and source</text>
|
||||
<text x="18" y="172" class="t">archive, or an RPM</text>
|
||||
<text x="18" y="194" class="mono code">pvshow.spec</text>
|
||||
<path d="M18 236h174" stroke="#e1e4f2" stroke-width="1.5"/>
|
||||
<text x="18" y="262" class="mono code">python -m build</text>
|
||||
<text x="18" y="284" class="mono code">rpmbuild -bb</text>
|
||||
</g>
|
||||
|
||||
<!-- footer -->
|
||||
<text x="480" y="420" text-anchor="middle" class="cap">Each stage runs. How you package the tool is your choice;</text>
|
||||
<text x="480" y="442" text-anchor="middle" class="cap">it reaches Controls hosts with autodeploy.</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 6.6 KiB |
Reference in new issue
Block a user