File: xlargs.py
   1 #!/usr/bin/python3
   2 
   3 # The MIT License (MIT)
   4 #
   5 # Copyright © 2024 pacman64
   6 #
   7 # Permission is hereby granted, free of charge, to any person obtaining a copy
   8 # of this software and associated documentation files (the “Software”), to deal
   9 # in the Software without restriction, including without limitation the rights
  10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 # copies of the Software, and to permit persons to whom the Software is
  12 # furnished to do so, subject to the following conditions:
  13 #
  14 # The above copyright notice and this permission notice shall be included in
  15 # all copies or substantial portions of the Software.
  16 #
  17 # THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23 # SOFTWARE.
  24 
  25 
  26 from itertools import islice, chain
  27 from subprocess import call
  28 from sys import argv, exit, stderr, stdin, stdout
  29 
  30 
  31 info = '''
  32 xlargs [args...]
  33 
  34 
  35 Similar to `xargs`, eXtra Lines ARGuments takes each line from standard-input
  36 and uses it to extend the cmd/arg list given as cmd-line arguments, running
  37 the resulting extended command.
  38 
  39 This tool is a very convenient way to pass filepaths which may have spaces in
  40 them to another app/tool.
  41 '''
  42 
  43 
  44 if len(argv) < 2 or argv[1] in ('-h', '--h', '-help', '--help'):
  45     print(info.strip())
  46     exit(0)
  47 
  48 
  49 try:
  50     args = chain(
  51         islice(argv, 1, None),
  52         (extra.rstrip('\r\n').rstrip('\n') for extra in stdin),
  53     )
  54     exit(call(args, stdin=stdin, stdout=stdout, stderr=stderr))
  55 except BrokenPipeError:
  56     stderr.close()
  57     exit(0)
  58 except KeyboardInterrupt:
  59     stderr.close()
  60     exit(1)