#!/usr/bin/env python3 import requests import json import time import sys # Base URL for the API BASE_URL = "http://localhost:4200/api/script" # Arguments to pass to the script ARG1 = "hello" ARG2 = "world" def main(): print("Starting script execution...") # Start script execution and get token try: response = requests.post( BASE_URL, json={ "scriptPath": "/tmp/api_scripts/hello_test.sh", "args": [ARG1, ARG2] }, headers={"Content-Type": "application/json"} ) response.raise_for_status() # Raise exception for non-200 status codes token_data = response.json() token = token_data.get("token") if not token: print(f"Failed to get token. Response: {response.text}") sys.exit(1) print(f"Received token: {token}") print("Polling for results...") except requests.exceptions.RequestException as e: print(f"Error starting script execution: {e}") sys.exit(1) # Poll for results with timeout MAX_ATTEMPTS = 30 SLEEP_SECONDS = 1 status = "pending" for attempt in range(1, MAX_ATTEMPTS + 1): if status not in ["pending", "running"]: break print(f"Polling attempt {attempt} of {MAX_ATTEMPTS}...") try: result_response = requests.get(f"{BASE_URL}?token={token}") result_response.raise_for_status() result_data = result_response.json() status = result_data.get("status") if status in ["pending", "running"]: print(f"Script is still {status}. Waiting {SLEEP_SECONDS}s...") time.sleep(SLEEP_SECONDS) else: break except requests.exceptions.RequestException as e: print(f"Error polling for results: {e}") sys.exit(1) if status in ["pending", "running"]: print("Timeout waiting for script to complete") sys.exit(1) # Print results print(f"Script execution completed with status: {status}") print(f"Result: {json.dumps(result_data, indent=2)}") # Pretty print stdout if available if result_data.get("result", {}).get("stdout"): stdout = result_data["result"]["stdout"] print("\nScript output:") print(stdout) if __name__ == "__main__": main()