r/Python • • 6h ago

Discussion I've started treating the output of my little Python scripts as a user interface

I inherited a bunch of internal Python scripts at work last year. Most of them were perfectly readable, did their job and had been running for years without any major issues.

The annoying part was figuring out what they'd actually done.

One would print "Done" whether it processed 400 files or found nothing to process. Another would silently skip invalid records. To understand the result of a successful run I sometimes had to read the source code.

I've since developed a habit of ending even fairly trivial scripts with a small summary of what was found, what changed, what was skipped and why.

It's probably the smallest change I've made to my coding habits with the biggest practical payoff. Especially when revisiting something I wrote six months ago.

I think we spend a disproportionate amount of time making Python code pleasant for other developers to read compared to making Python programs pleasant for other people to actually run.

67 Upvotes

26 comments sorted by

68

u/frankieinaprius 6h ago

This is what logging is for. And by using log levels appropriately, you control how verbose you want the output to be.

17

u/benwalton 6h ago

💯. Make the tools quiet by default and only emit something if there is a problem.

6

u/rando1-6180 5h ago

Definitely the way to go. It's an unwritten UNIX thing.

4

u/N-E-S-W 3h ago

I'd say that the half-a-century full of writings about the Philosophy of Unix are the inspiration for the Zen of Python.

https://en.wikipedia.org/wiki/Unix_philosophy

1

u/rando1-6180 3h ago

Right on! ESR wrote about this too. I have my 3 WR Stevens books somewhere in my basement.

1

u/drivingagermanwhip 4h ago

I have a typer-di thing I made a while ago that handles verbosity flags and it's easy to just tack that onto every script

34

u/Spawn_quiche 6h ago

"Successfully processed 0 records" and "Failed to find any records to process" are two very different outcomes that an alarming number of scripts consider identical.

4

u/ExceedinglyEdible 5h ago

ls in an empty directory yields a blank line and it's not an error

2

u/bikes-n-math 5h ago edited 24m ago

ls -A certainly does, but ls does not.

edit: I stand corrected. ls in an empty directory prints nothing by default. I was thinking of ls -a that prints . and ..

2

u/MrSlaw 2h ago

ls -A certainly does, but ls does not.

Am I missing something here?

user@mercury:~# mkdir /mnt/user/appdata/new
user@mercury:~# ls /mnt/user/appdata/new
user@mercury:~# ls -A /mnt/user/appdata/new

Both ls -A , and plain ls return blank lines on an empty directory?

10

u/monkeybreath Ignoring PEP 8 5h ago

Normalize responding appropriately to --help for each app. I rarely run my apps from the command line, but I really should document what they do better.

5

u/drivingagermanwhip 4h ago edited 3h ago

typer works really nicely for this. It's surprisingly easy to make scripts into a python package. Slap typer on it and you've got a very cromulent CLI

https://typer.tiangolo.com/

EDIT: Looking at the docs apparently you can also just call your scripts using typer and it will turn your main entry point into a CLI. Don't know if that was always there but it's pretty neat

2

u/monkeybreath Ignoring PEP 8 3h ago

Oh, good tip. That would certainly ease making CLI apps. https://typer.tiangolo.com/

•

u/2Lucilles2RuleEmAll 38m ago

I thought typer was great, but then I found cyclopts

•

u/drivingagermanwhip 35m ago

nice! I'll check it out

2

u/garion911 3h ago

I use docopt for this. http://docopt.org/

1

u/washedFM 5h ago

That’s the next person’s job

3

u/mdrjevois 2h ago

I call this DBAJTY, in the spirit of DRY and YAGNI. "Don't Be A Jerk To Yourself." So often you are your own end user. Be kind! Don't leave em guessing.

2

u/RandomGgames 2h ago

Over the years I’ve made myself a base script I build all new scripts from. It’s not crazy complicated, but sets up logging and as configurable, so I can customize it per script as I want. Might be something to look into?

3

u/def__eq__ 6h ago

Or use click or textualize..

2

u/patryk_builds 3h ago

Agree, and done after processing zero items is the worst case of it. a run that did nothing and a run that did everything shouldn't look the same. test runners have the same problem: a pass with zero tests collected looks identical to a real pass unless the count is printed.

A few things in the same spirit that cost almost nothing:

- Treat zero as suspicious. if the script expected input and found none, say so loudly, and consider a non-zero exit code. whatever calls the script (cron, ci) only sees the exit code

- Count the skips by reason. skipped 12: 9 missing date, 3 duplicate id" is far more useful than a total, and it's just a Counter

- Summary to stdout, diagnostics to stderr, so the summary can be piped or saved without noise

- A --dry-run flag that prints the same summary without changing anything. the summary code is already there, so it's nearly free

- Print what the script was pointed at: the input path, the date range, the environment. half of "why did it do nothing is it looked in the wrong folder The six months later point is the real one. the person running it is usually future you, with no memory of what done was supposed to mean

2

u/rando1-6180 5h ago

This is an excellent practice that depends on your need, environment and budget. The scripts you inherited might have been written in a pinch.

Making scripts "fit for human consumption" is very valuable because it reduces cognitive burden for you and anyone else succeeding you. Institutional knowledge transfer is a thorn in the side of many teams. This is one way to reduce that burden.

If you pursue this, I suggest starting the script with a context report. It provides things like run timestamp, the exact command run, any arguments and any options, and any defaults. If you are processing sequence, provide a row count.

Then enumerate the steps, as a section in your output, as you are executing with whatever details belong to that step.

Alternatively, you can use the logger, which structures messages into info, warning and error. It provides some scaffolding that helps you cleanly format and organize your messages. Be ready to manage logging from modules you import though.

Consider writing script level docstrings with example usage.

Be mindful of your exit code. 0 means all good and non-zero is the error code for your error classifications (e.g. 1 is operational like file doesn't exist, 2 is validation/business logic error).

Lastly, you can elevate by providing a curated experience by providing suggested next commands. Make them copy/paste ready. This will help you when you need to revisit a bunch of related scripts.

I think we can give ourselves and ops folks a better experience.

1

u/Smort01 5h ago

I started reading from an online API, and putting every shit In a try/except clause with readable error handling saved me so many headdaches.

-3

u/nicksuperb 5h ago

Try marimo and make yourself a nice playbook.
https://marimo.io/

•

u/drivingagermanwhip 44m ago

oh nice. Probably not what op wanted hence downvotes but I hadn't heard of this. Jupyter seems cool at first but tends to end up with a load of clutter from the three times you actually used the files. This seems better for the interactive explainer situation which is what you tend to want longer term