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

134 Upvotes

49 comments sorted by

135

u/frankieinaprius 4d ago

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

36

u/benwalton 4d ago

šŸ’Æ. Make the tools quiet by default and only emit something if there is a problem.

13

u/rando1-6180 4d ago

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

12

u/N-E-S-W 3d 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

4

u/rando1-6180 3d ago

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

4

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

22

u/monkeybreath Ignoring PEP 8 4d 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.

11

u/drivingagermanwhip 3d ago edited 3d 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

6

u/2Lucilles2RuleEmAll 3d ago

I thought typer was great, but then I found cyclopts

1

u/drivingagermanwhip 3d ago

nice! I'll check it out

3

u/monkeybreath Ignoring PEP 8 3d ago

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

1

u/Spleeeee 3d ago

I’ve used typer for a while and it’s a piece of shit. I adopted it too early and thought I was getting something that wasn’t half baked with all sorts of gotchas.

I’m also part of the contributors, and I think it’s a POS.

3

u/garion911 3d ago

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

2

u/christian-mq 3d ago

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

1

u/washedFM 3d ago

That’s the next person’s job

63

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

12

u/ExceedinglyEdible 4d ago

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

2

u/bikes-n-math 3d ago edited 3d 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 3d 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?

1

u/guareber 3d ago

You're not. OP is probably thinking -lah , which a lot of us default to typing without thinking.

2

u/Deadly_chef 3d ago

ls -laht aliased to la is one of the first she'll configs I always make

2

u/guareber 2d ago

I can't believe I've never bothered to do this... Hold my zsh

5

u/RandomGgames 3d 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?

1

u/Henry_the_Butler 19h ago

I'd be interested in seeing this script or an example like it if, you have one you're willing to share.

3

u/yared12qw 3d 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

1

u/yared12qw 3d 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

4

u/mdrjevois 3d 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.

3

u/def__eq__ 4d ago

Or use click or textualize..

2

u/patryk_builds 3d 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 3d 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 3d 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 3d ago

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

1

u/Minute-Age9938 3d 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 2d 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/Wild-Pen-2027 2d ago

I usually run apps from cmd

1

u/krakenarthritis 16h ago

ā€œDoneā€ hides the most useful distinction: did it finish successfully after changing nothing, or finish successfully after changing 400 files? Counts for processed, skipped, and failed make the logs answer that at a glance.

1

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

0

u/Smort01 3d 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.

-4

u/nicksuperb 4d ago

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

1

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

1

u/yared12qw 3d ago

I'm working on a tool called V-NOC. It indexes the codebase and organizes docs, plans, and notes 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 at a time, explore its call flow, and hide everything unrelated.

It also has a CLI for coding agents to explore the code, manage the attached context, and create walkthroughs and tutorials.

It's available as a VS Code and Cursor extension and can also run standalone. Most of the core is written in Rust.

It's still early, and I'd love to get some feedback.

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

VS Code: https://marketplace.visualstudio.com/items?itemName=vnoc.vnoc

Cursor: https://open-vsx.org/extension/vnoc/vnoc

1

u/nicksuperb 3d ago

If you’ve used Jupyter this is a better next step, it runs from a single py that you make yourself and has some very flexible imports.

I don’t think anyone downvoting has actually tried it. LOL thanks Reddit.