|
| 1 | +def _add_exception(return_dict, e, cmd): |
| 2 | + import subprocess |
| 3 | + |
| 4 | + return_dict['success'] = False |
| 5 | + |
| 6 | +# if isinstance(e, subprocess.CalledProcessError): |
| 7 | +# # Check if simulation terminated, and if so, get the error |
| 8 | +# return_dict['stdout'] = e.output.decode("utf-8") |
| 9 | +# output = return_dict['stdout'] |
| 10 | +# for line in output.split('\n'): |
| 11 | +# if 'terminated' in line: |
| 12 | +# # Found terminated string. Cut everything after the '|' character that OpenModelica writes. |
| 13 | +# idx=line.rfind('|') |
| 14 | +# msg=line[idx+1:].strip() |
| 15 | +# # The solver terminated. Add this information to a custom exception message. |
| 16 | +# return_dict['exception'] = f"'{' '.join(cmd)}' caused '{msg}'." |
| 17 | +# pass |
| 18 | + |
| 19 | + if not 'exception' in return_dict: |
| 20 | + # Did not find 'terminated' in message, handle exception as usual |
| 21 | + return_dict['exception'] = '{}: {}'.format(type(e).__name__, e) |
| 22 | + |
| 23 | + |
| 24 | +def _run_process(return_dict, cmd, worDir, timeout): |
| 25 | + import subprocess |
| 26 | + |
| 27 | + output = subprocess.check_output( |
| 28 | + cmd, |
| 29 | + cwd = worDir, |
| 30 | + timeout=timeout, |
| 31 | + stderr=subprocess.STDOUT, |
| 32 | + shell=False) |
| 33 | + |
| 34 | + return_dict['success'] = True |
| 35 | + if 'stdout' in return_dict: |
| 36 | + return_dict['stdout'] += output.decode("utf-8") |
| 37 | + else: |
| 38 | + return_dict['stdout'] = output.decode("utf-8") |
| 39 | + return |
| 40 | + |
| 41 | +def _simulate(model, timeout): |
| 42 | + import os |
| 43 | + import subprocess |
| 44 | + |
| 45 | + worDir = "{{ working_directory }}" |
| 46 | + return_dict = {} |
| 47 | + |
| 48 | + try: |
| 49 | + cmd = {{ cmd }} |
| 50 | + return_dict['cmd'] = ' '.join(cmd) |
| 51 | + output = _run_process(return_dict, cmd, worDir, timeout) |
| 52 | + |
| 53 | + except Exception as e: |
| 54 | + _add_exception(return_dict, e, cmd) |
| 55 | + return return_dict |
| 56 | + |
| 57 | +def run(): |
| 58 | + import os |
| 59 | + import json |
| 60 | + import traceback |
| 61 | + import sys |
| 62 | + |
| 63 | + timeout = {{ time_out }} |
| 64 | + model = "{{ model }}" |
| 65 | + result = {"model": model, |
| 66 | + "working_directory": "{{ working_directory }}", |
| 67 | + "simulation": {"success": False}} |
| 68 | + |
| 69 | + # Log file |
| 70 | + log_file = "{}_buildingspy.json".format(model.replace(".", "_")) |
| 71 | + try: |
| 72 | + os.remove(log_file) |
| 73 | + except OSError: |
| 74 | + pass |
| 75 | + |
| 76 | + # Simulate model |
| 77 | + result["simulation"] = _simulate(model, timeout) |
| 78 | + |
| 79 | + with open(log_file, "w") as log: |
| 80 | + log.write("{}\n".format(json.dumps(result, indent=4, sort_keys=False)) ) |
| 81 | + |
| 82 | +if __name__=="__main__": |
| 83 | + run() |
0 commit comments