Skip to content

Instantly share code, notes, and snippets.

@agateau
Created April 16, 2020 10:58
Show Gist options
  • Save agateau/8ae2d87ace86e6a22b760caed4d00645 to your computer and use it in GitHub Desktop.
Save agateau/8ae2d87ace86e6a22b760caed4d00645 to your computer and use it in GitHub Desktop.
Cat log-rotated log files passed as arguments in the right order, unpacking them with zcat, bzcat or xzcat if necessary.
#!/usr/bin/env python3
"""
Cat log-rotated log files passed as arguments in the right order, unpacking
them with zcat, bzcat or xzcat if necessary.
"""
import argparse
import os
import subprocess
import sys
ARCHIVE_CATS = {
"gz": "zcat",
"bz2": "bzcat",
"xz": "xzcat",
}
def get_log_order(filename):
lst = filename.split(".")
if lst[-1] in ARCHIVE_CATS:
del(lst[-1])
try:
# Return a negative value, so that foo.log.2 is sorted *before*
# foo.log.1
return -int(lst[-1])
except ValueError:
# Not a number, assume this is foo.log
return 0
def cat(filename):
ext = os.path.splitext(filename)[1]
cat_cmd = ARCHIVE_CATS.get(ext[1:], "cat")
subprocess.run([cat_cmd, filename])
def main():
parser = argparse.ArgumentParser()
parser.description = __doc__
parser.add_argument("files", nargs="+")
args = parser.parse_args()
files = sorted(args.files, key=get_log_order)
for file in files:
cat(file)
return 0
if __name__ == "__main__":
sys.exit(main())
# vi: ts=4 sw=4 et
@tmonjalo
Copy link

Thanks for sharing.
I am curious how many lines it would be as a shell script?
Any volunteer for a language contest? :-)

@agateau
Copy link
Author

agateau commented Apr 16, 2020

Probably less, but this one could be less lines if it were not pep8 compliant and did not have a proper argument parser... (yes, this thing supports -h and --help). I usually give up on shell scripts when it's time to do arithmetic, but give it a try, I am curious to see what you come up with :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment