Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- 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?
- '''
- import comtypes.client
- import time
- import sys
- import os
- def run_macro_and_print_time(macro_filename, flag_filepath):
- """
- Connects to PowerMill, executes a macro, waits for a signal file,
- and then retrieves and prints the total machining time.
- """
- # --- Cleanup from previous runs ---
- # Delete the flag file if it exists from a failed previous run
- if os.path.exists(flag_filepath):
- os.remove(flag_filepath)
- if not os.path.exists(macro_filename):
- print(f"❌ Error: Macro file not found at '{macro_filename}'")
- return
- # --- 1. Connect to PowerMill ---
- try:
- print("Connecting to PowerMill...")
- pmill = comtypes.client.GetActiveObject("PowerMill.Application")
- print("✅ Successfully connected to PowerMill.")
- except OSError:
- print("❌ Error: PowerMill is not running or could not be found.")
- return
- except Exception as e:
- print(f"An unexpected error occurred during connection: {e}")
- return
- # --- 2. Execute Macro from File ---
- try:
- with open(macro_filename, 'r') as f:
- commands = f.readlines()
- print(f"\nExecuting commands from '{macro_filename}'...")
- for command in commands:
- if command.strip():
- pmill.DoCommand(command.strip())
- print("✅ All commands sent to PowerMill.")
- except Exception as e:
- print(f"An error occurred while executing the macro: {e}")
- return
- # --- 3. Wait for PowerMill to finish by checking for the signal file ---
- print("\nWaiting for PowerMill to finish calculations...")
- start_time = time.time()
- timeout_seconds = 300 # 5 minutes timeout
- while not os.path.exists(flag_filepath):
- time.sleep(1) # Wait for 1 second before checking again
- if time.time() - start_time > timeout_seconds:
- print("❌ Timeout! PowerMill did not finish within the expected time.")
- return
- print(f"✅ PowerMill finished. Signal file found at '{flag_filepath}'.")
- os.remove(flag_filepath) # Clean up the signal file
- # --- 4. Retrieve Time from the ACTIVE NC Program ---
- print("\n--- Retrieving Machining Time ---")
- try:
- nc_program = pmill.ActiveNCProgram
- total_seconds = nc_program.TotalTime
- hours = int(total_seconds // 3600)
- minutes = int((total_seconds % 3600) // 60)
- seconds = int(total_seconds % 60)
- time_str = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
- print("==============================================")
- print(f"🕒 Total Machining Time: {time_str} (from active NC Program: {nc_program.Name})")
- print(f"(Calculated from {total_seconds:.2f} seconds)")
- print("==============================================")
- except Exception as e:
- print(f"❗️ Could not retrieve the total time from the active NC Program.")
- print(f" Reason: {e}")
- if __name__ == "__main__":
- macro_file_to_run = "test.mac"
- # Define the path for the signal file. This MUST match the path in your .mac file.
- signal_file = r"C:\temp\pmill_done.flag"
- run_macro_and_print_time(macro_file_to_run, signal_file)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement