Simple question:
Is there some code or function I can add into most scripts that would let me know its “running”?
So after you execute foo.py most people would see a blinking cursor. I currently am running a new large script and it seems to be working, but I wont know until either an error is thrown or it finish(might not finish).
I assume you could put a simple print "foo-bar"at the end of each for loop in the script?
Any other neat visual read out tricks?
The
print "foo-bar"trick is basically what people do for quick&dirty scripts. However, if you have lots and lots of loops, you don’t want to print a line for each one. Besides the fact that it’ll fill the scrollback buffer of your terminal, on many terminals it’s hard to see whether anything is happening when all it’s doing is printing the same line over and over. And if your loops are quick enough, it may even mean you’re spending more time printing than doing the actual work.So, there are some common variations to this trick:
To print a word without a newline, you just
print 'foo',. To print a character with neither a newline nor a space, you have tosys.stdout.write('.'). Either way, people can see the cursor zooming along horizontally, so it’s obvious how fast the feedback is.If you’re got a
for n in …loop, you can printn. Or, if you’re progressively building something, you can printlen(something), oroutfile.ftell(), or whatever. Even if it’s not objectively meaningful, the fact that it’s constantly changing means you can tell what’s going on.The easiest way to not print all the time is to add a counter, and do something like
counter += 1; if counter % 250 == 0: print 'foo'. Variations on this include checking the time, and printing only if it’s been, say, 1 or more seconds since the lastprint, or breaking the task into subtasks and printing at the end of each subtask.And obviously you can mix and match these.
But don’t put too much effort into it. If this is anything but a quick&dirty aid to your own use, you probably want something that looks more professional. As long as you can expect to be on a reasonably usable terminal, you can print a
\rwithout a\nand overwrite the line repeatedly, allowing you to draw nice progress bars or other feedback (alacurl,wget,scp, and other similar Unix tools). But of course you also need to detect when you’re not on a terminal, or at least write this stuff tostderrinstead ofstdout, so if someone redirects or pipes your script they don’t get a bunch of garbage. And you might want to try to detect the terminal width, and if you can detect it and it’s >80, you can scale the progress bar or show more information. And so on.This gets complicated, so you probably want to look for a library that does it for you. There are a bunch of choices out there, so look through PyPI and/or the ActiveState recipes.