Skip to content

Instantly share code, notes, and snippets.

@cmccandless
Created May 9, 2018 18:27
Show Gist options
  • Save cmccandless/c059f7cd825957b62eecb463c18c702f to your computer and use it in GitHub Desktop.
Save cmccandless/c059f7cd825957b62eecb463c18c702f to your computer and use it in GitHub Desktop.
Simple loop command
#!/usr/bin/env python
from __future__ import print_function
import argparse
import subprocess
import sys
parser = argparse.ArgumentParser(
prog='loop',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument(
'-A', '--start',
type=int,
default=0,
metavar='num',
help="$SUB will be substituted for loop number",
)
parser.add_argument('-I', default='%%', dest='sub', help='substitution string')
parser.add_argument('times', type=int)
parser.add_argument('command', nargs='+')
opts = parser.parse_args()
command = ' '.join(opts.command) + '\n'
stop = opts.times + opts.start
for i in range(opts.start, stop):
p = subprocess.Popen(['bash', '--login'], stdin=subprocess.PIPE)
cmd = command.replace(opts.sub, str(i))
if opts.verbose:
print('>' + cmd, end='')
p.stdin.write(cmd)
p.stdin.flush()
p.stdin.write('exit\n')
p.wait()
if p.returncode != 0:
it = str(i - opts.start + 1)
ending = {
'1': 'st',
'2': 'nd',
}.get(it[-1], 'th')
print('{}{} iteration failed'.format(it, ending))
sys.exit(p.returncode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment