/home/alex/dev/stdin.py (1)

From RaySoft
#!/usr/bin/env python3
# ------------------------------------------------------------------------------
# stdin.py
# ========
#
# Scope     Native
# Copyright (C) 2024 by RaySoft, Zurich, Switzerland
# License   GNU General Public License (GPL) 2.0
#           https://www.gnu.org/licenses/gpl2.txt
#
# ------------------------------------------------------------------------------
#
# References:
# - http://stackoverflow.com/questions/7576525/
# - http://stackoverflow.com/questions/13442574/
#
# ------------------------------------------------------------------------------

PROGRAM_NAME = 'stdin'
PROGRAM_VERSION = '0.1'

# ------------------------------------------------------------------------------

from argparse import ArgumentParser
from sys import exit, stderr, stdin

# ------------------------------------------------------------------------------

def main():
    parser = ArgumentParser(
        description='Demo program to read from command line or standard input. '
                    'In this example URLs are read.', prog=PROGRAM_NAME,
    )
    parser.add_argument(
        '-V', '--version', action='version',
        version=f'%(prog)s {PROGRAM_VERSION}',
    )
    parser.add_argument(
        'url', metavar='URL', action='store', nargs='+',
        help='URL to be processed. Use a single dash (-) to read from stdin',
    )

    args = parser.parse_args()

    # stdin_mode = os.fstat(sys.stdin.fileno()).st_mode

    # stdin_ispipe = stat.S_ISFIFO(stdin_mode)
    # stdin_isredirect = stat.S_ISREG(stdin_mode)

    if args.url[0] == '-':
        if len(args.url) > 1:
            print('A dash (-) as value does not work with other values!',
                  file=stderr)
            return 1

        # Test if it is not a pipe or a redirect
        # if not (stdin_ispipe or stdin_isredirect):
        if stdin.isatty():
            print('A dash (-) as value only works with a redirect or a pipe!',
                  file=stderr)
            return 1

        urls = [s for s in stdin.read().split() if s]
    else:
        # Test if it is a pipe or a redirect
        # if stdin_ispipe or stdin_isredirect:
        if not stdin.isatty():
            print('Use a dash (-) to work with a redirect or a pipe!',
                  file=stderr)
            return 1

        urls = args.url

    for url in urls:
        print(url)

    return 0

# ------------------------------------------------------------------------------

if __name__ == '__main__':
    return_value = main()

    exit(return_value)

Usage

~/dev/stdin.py 'http://www.google.ch/' 'http://www.google.com/'
~/dev/stdin.py - <<<'http://www.google.ch/' 'http://www.google.com/'
~/dev/stdin.py - <"${HOME}/tmp/test_url.txt"
echo 'http://www.google.ch/' 'http://www.google.com/' | ~/dev/stdin.py -
cat "${HOME}/tmp/test_url.txt" | ~/dev/stdin.py -