#!/usr/bin/env python

"""Performs several runs of Veros back to back, using the previous run as restart input.

Intended to be used with scheduling systems (e.g. SLURM or PBS).
"""

import argparse
import subprocess
import shlex
import sys

def parse_cli():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("IDENTIFIER", help="base identifier of the simulation")
    parser.add_argument("N_SUBMITS", type=int, help="total number of resubmits")
    parser.add_argument("LENGTH_PER_RUN", type=float, help="length (in seconds) of each run")
    parser.add_argument("VEROS_CMD", help="the command that is used to call veros")
    return parser.parse_args()

def call_veros(cmd, name, n, runlen):
    identifier = "{name}.{n:0>4}".format(name=name, n=n)
    prev_id = "{name}.{n:0>4}".format(name=name, n=n-1)
    args = "-s identifier \"{name}\" -s restart_output_filename \"{{identifier}}.restart.h5\" -s runlen {runlen}" \
            .format(name=identifier, runlen=runlen)
    if n:
        args += " -s restart_input_filename \"{prev_id}.restart.h5\"".format(prev_id=prev_id)
    sys.stdout.write(" >>> " + cmd + " " + args + "\n")
    sys.stdout.flush()
    subprocess.check_call(shlex.split(cmd) + shlex.split(args))

if __name__ == "__main__":
    args = parse_cli()
    for n in range(args.N_SUBMITS):
        call_veros(args.VEROS_CMD, args.IDENTIFIER, n, args.LENGTH_PER_RUN)

@@ -601,16 +601,34 @@
 OS_CMD%22,
+ type=shlex.split,
  help=%22t
@@ -664,16 +664,154 @@
 ll veros
+ (in quotes)%22)%0A    parser.add_argument(%22-n%22, %22--start-n%22, metavar=%22N%22, type=int, default=0, help=%22re-start from resubmit run with number N
 %22)%0A    r
@@ -1003,12 +1003,16 @@
 s = 
+%5B
 %22-s
- 
+%22, %22
 iden
@@ -1021,23 +1021,30 @@
 fier
- %5C%22%7Bname%7D%5C%22 -s 
+%22, identifier, %22-s%22, %22
 rest
@@ -1062,20 +1062,20 @@
 filename
- %5C%22%7B
+%22, %22
 %7Bidentif
@@ -1078,17 +1078,16 @@
 ntifier%7D
-%7D
 .restart
@@ -1093,84 +1093,47 @@
 t.h5
-%5C%22 -s runlen %7Brunlen%7D%22 %5C%0A            .format(name=identifier, runlen=
+%22, %22-s%22, %22runlen%22, %22%7B%7D%22.format(
 runlen)
+%5D
 %0A   
@@ -1159,13 +1159,16 @@
  += 
-%22 -s 
+%5B%22-s%22, %22
 rest
@@ -1189,10 +1189,11 @@
 name
+%22,
  
-%5C
 %22%7Bpr
@@ -1213,10 +1213,8 @@
 t.h5
-%5C%22
 %22.fo
@@ -1234,16 +1234,17 @@
 prev_id)
+%5D
 %0A    sys
@@ -1262,40 +1262,51 @@
 te(%22
+%5Cn
  %3E%3E%3E 
-%22 + cmd + %22 %22 + args + %22%5Cn%22
+%7B%7D%5Cn%5Cn%22.format(%22 %22.join(cmd + args))
 )%0A  
@@ -1326,16 +1326,29 @@
 flush()%0A
+    try:%0A    
     subp
@@ -1369,43 +1369,122 @@
 all(
-shlex.split(cmd) + shlex.split(args
+cmd + args)%0A    except subprocess.CalledProcessError:%0A        raise RuntimeError(%22Run %7B%7D failed, exiting%22.format(n
 ))%0A%0A
@@ -1622,16 +1622,31 @@
 IFIER, n
+ + args.start_n
 , args.L

add restart mechanism to resubmit script