Created
April 23, 2020 11:37
-
-
Save maxfischer2781/6d257dd32dfd26a4fbb65d4ee685d1cc to your computer and use it in GitHub Desktop.
Compile HTCondor if-then cases to a single if-then-else tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from typing import Dict | |
def switch(cases: Dict[str, str], default='UNDEFINED', separator='\n'): | |
# ["IfThenElse(ac, am", "IfThenElse(bc, bm", "IfThenElse(cc, cm", ...] | |
switch_expression = separator.join( | |
f"IfThenElse({condition}, {on_match}," | |
for condition, on_match in cases.items() | |
) | |
return ( | |
f"{switch_expression}{separator}{default}{')' * len(cases)}" | |
if switch_expression else default | |
) | |
if __name__ == "__main__": | |
import argparse | |
import sys | |
if sys.version_info[:2] < (3, 6): | |
print(f"Python 3.6 or newer required", file=sys.stderr) | |
sys.exit(1) | |
parser = argparse.ArgumentParser( | |
formatter_class=argparse.RawDescriptionHelpFormatter, | |
description="Compile HTCondor if-then cases to a single if-then-else tree", | |
epilog=( | |
"Example:\n" | |
""" %(prog)s 'Owner == "Bruce"' '"Batman"'""" | |
""" 'Owner == "Clark"' '"Superman"' --default '"Joker"'""" | |
), | |
) | |
parser.add_argument( | |
"cases", | |
nargs="*", | |
default=[], | |
help="pairs of condition and result", | |
) | |
parser.add_argument( | |
"--default", | |
default='UNDEFINED', | |
help="fallback if no case matches", | |
) | |
parser.add_argument( | |
"--multiline", | |
action="store_true", | |
help="whether to spread each case onto a new line", | |
) | |
settings = parser.parse_args() | |
if len(settings.cases) % 2: | |
print(f"cases must be pairs (multiple of 2)", file=sys.stderr) | |
sys.exit(1) | |
print( | |
switch( | |
cases=dict(zip(settings.cases[::2], settings.cases[1::2])), | |
default=settings.default, | |
separator='\n' if settings.multiline else ' ', | |
) | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment