Advertisement
m_eghlima8

Untitled

Jul 17th, 2025 (edited)
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.65 KB | Source Code | 0 0
  1. '''
  2. I want to calculate the total time of the operation with the command: nc_program = pmill.ActiveNCProgram total_seconds = nc_program.TotalTime or other commands but whatever I do I get the error: Could not retrieve the total time from the active NC Program. Reason: ActiveNCProgram Please ensure the macro ran successfully and activated an NC Program at the end. Can anyone help me?
  3. '''
  4.  
  5. import comtypes.client
  6. import time
  7. import sys
  8. import os
  9.  
  10. def run_macro_and_print_time(macro_filename, flag_filepath):
  11.     """
  12.    Connects to PowerMill, executes a macro, waits for a signal file,
  13.    and then retrieves and prints the total machining time.
  14.    """
  15.     # --- Cleanup from previous runs ---
  16.     # Delete the flag file if it exists from a failed previous run
  17.     if os.path.exists(flag_filepath):
  18.         os.remove(flag_filepath)
  19.  
  20.     if not os.path.exists(macro_filename):
  21.         print(f"❌ Error: Macro file not found at '{macro_filename}'")
  22.         return
  23.  
  24.     # --- 1. Connect to PowerMill ---
  25.     try:
  26.         print("Connecting to PowerMill...")
  27.         pmill = comtypes.client.GetActiveObject("PowerMill.Application")
  28.         print("✅ Successfully connected to PowerMill.")
  29.     except OSError:
  30.         print("❌ Error: PowerMill is not running or could not be found.")
  31.         return
  32.     except Exception as e:
  33.         print(f"An unexpected error occurred during connection: {e}")
  34.         return
  35.  
  36.     # --- 2. Execute Macro from File ---
  37.     try:
  38.         with open(macro_filename, 'r') as f:
  39.             commands = f.readlines()
  40.        
  41.         print(f"\nExecuting commands from '{macro_filename}'...")
  42.         for command in commands:
  43.             if command.strip():
  44.                 pmill.DoCommand(command.strip())
  45.         print("✅ All commands sent to PowerMill.")
  46.  
  47.     except Exception as e:
  48.         print(f"An error occurred while executing the macro: {e}")
  49.         return
  50.  
  51.     # --- 3. Wait for PowerMill to finish by checking for the signal file ---
  52.     print("\nWaiting for PowerMill to finish calculations...")
  53.     start_time = time.time()
  54.     timeout_seconds = 300  # 5 minutes timeout
  55.  
  56.     while not os.path.exists(flag_filepath):
  57.         time.sleep(1) # Wait for 1 second before checking again
  58.         if time.time() - start_time > timeout_seconds:
  59.             print("❌ Timeout! PowerMill did not finish within the expected time.")
  60.             return
  61.            
  62.     print(f"✅ PowerMill finished. Signal file found at '{flag_filepath}'.")
  63.     os.remove(flag_filepath) # Clean up the signal file
  64.  
  65.     # --- 4. Retrieve Time from the ACTIVE NC Program ---
  66.     print("\n--- Retrieving Machining Time ---")
  67.     try:
  68.         nc_program = pmill.ActiveNCProgram
  69.         total_seconds = nc_program.TotalTime
  70.        
  71.         hours = int(total_seconds // 3600)
  72.         minutes = int((total_seconds % 3600) // 60)
  73.         seconds = int(total_seconds % 60)
  74.         time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
  75.  
  76.         print("==============================================")
  77.         print(f"🕒 Total Machining Time: {time_str} (from active NC Program: {nc_program.Name})")
  78.         print(f"(Calculated from {total_seconds:.2f} seconds)")
  79.         print("==============================================")
  80.  
  81.     except Exception as e:
  82.         print(f"❗️ Could not retrieve the total time from the active NC Program.")
  83.         print(f"   Reason: {e}")
  84.  
  85. if __name__ == "__main__":
  86.     macro_file_to_run = "test.mac"
  87.     # Define the path for the signal file. This MUST match the path in your .mac file.
  88.     signal_file = r"C:\temp\pmill_done.flag"
  89.    
  90.     run_macro_and_print_time(macro_file_to_run, signal_file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement