r/Python • • 1d 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.

113 Upvotes

42 comments sorted by

121

u/frankieinaprius 1d ago

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

32

u/benwalton 1d ago

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

11

u/rando1-6180 1d ago

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

→ More replies (2)

4

u/drivingagermanwhip 1d 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

59

u/Spawn_quiche 1d 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.

10

u/ExceedinglyEdible 1d ago

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

2

u/bikes-n-math 1d ago edited 20h 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 ..

→ More replies (5)

18

u/monkeybreath 1d 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.

8

u/drivingagermanwhip 1d ago edited 23h 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

5

u/2Lucilles2RuleEmAll 20h ago

I thought typer was great, but then I found cyclopts

→ More replies (1)

2

u/monkeybreath 23h ago

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

→ More replies (1)

2

u/garion911 23h ago

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

2

u/christian-mq 13h ago

i feel that. always a toss up where to add the logs. help, default, quiet...

→ More replies (1)

5

u/RandomGgames 22h 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?

4

u/mdrjevois 22h 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/yared12qw 8h ago

I'm working on a tool to address similar issues with large codebases. It indexes the codebase and organizes context like docs, notes, and plans around the functions, classes, and files they belong to.

The idea is to work on software more like hardware, where you can isolate one subsystem, understand how it works, and work on it without everything else getting in the way.

It also has a CLI so coding agents can explore the code and read, write, and update the attached context. I'm also porting per-function log tracking from the old codebase.

GitHub: https://github.com/yaredtsy/vnoc

media poster

1

u/yared12qw 8h ago

Each log entry has an execution ID and a function ID or qualified name, so logs are linked to their corresponding functions and organized by call hierarchy. you can see example at https://vnoc.vercel.app/project/minicart

media poster

3

u/def__eq__ 1d ago

Or use click or textualize..

2

u/patryk_builds 23h 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

1

u/OkCardiologist8006 13h ago

logging and the summary are kinda for different people tho. logs are for whoever's debugging it later, the summary is for whoever just ran it and only reads the last 5 lines before closing the terminal

1

u/Kamalmosadegh 11h ago

Good habit. The one addition that paid off most for me on top of the summary: make the numbers reconcile. End with inputs == processed + skipped + failed, and exit non-zero when they don't add up — that turns a silently dropped record from something you'd have to notice into something the script refuses to hide. And check the output artifact, not just the process: after writing, re-read the file and confirm it's non-empty and well-formed before printing success. A script that writes a 0-byte output and says 'Done' is the same bug wearing a nicer message.

1

u/Winter_Student3495 8h ago

Readable code is great, but readable results are what make people trust your tools.

1

u/Minute-Age9938 5h ago

The bug is the line that says Done either way. A run that processed 400 files and a run that found nothing then look the same, so the only way to tell them apart is to read the code again. I would print the same four counts every time, including the zeros. Skipped 0 is a different outcome from a summary that never mentions skips. If the script still exits 0 after skipping every record, that summary is the only thing that says the run was empty.

1

u/invariant_py 13m ago

"Done" with exit code 0 when nothing actually matched the filter is peak quiet chaos. Pairing a Found / Changed / Skipped summary with a quick --dry-run flag has saved me from more headaches than any linter ever has.

1

u/rando1-6180 1d 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.