# sample ARAP python script showing how to
#    - send and receive ARAP variables
#    - limit execution time
#    - capture and return python console output
# updated 01Nov/2021


import time
import ARAP
import sys
from io import StringIO


# used to clear the ARAP console output variable and re-direct
# the console output to Console
ARAP.Stdout=''
old_stdout = sys.stdout
sys.stdout = Console = StringIO()


# used for time limiting execution time
# note that it does not interrupt individual function calls
# use in the format:
#   with time_limit(timeout_secs,'message'):
#       statement1()
#       statement2()      
#
   
from contextlib import contextmanager
import threading
import _thread


class TimeoutException(Exception):
   def __init__(self, msg=''):
       self.msg = msg
@contextmanager
def time_limit(seconds, msg=''):
   timer = threading.Timer(seconds, lambda: _thread.interrupt_main())
   timer.start()
   try:
       yield
   except KeyboardInterrupt:
       raise TimeoutException("Execution time limit expired: {}".format(msg))
   finally:
       # if the action ends in specified time, timer is canceled
       timer.cancel()


# the main program
def main():
     
   # set an execution time limit of 10 seconds
   
   with time_limit(10,'main loop'):
       print ("Input variable: ",ARAP.Input)


       # add your Python code here
       time.sleep(1)
       ARAP.Output="output value"


if __name__ == "__main__":
   main()
   
# restores the console output and sets the ARAP console variable
sys.stdout = old_stdout
ARAP.Stdout=Console.getvalue()