Terminate exe from python

  Kiến thức lập trình

I have a python code that opens an exe file, passes some commands and produces output. Problem is that the exe still opened and the Jupiter notebook cell keeps running even after the last command is executed. I want an edit that terminates the exe and stops the cell from running after the output is generated.
I have tried this, but it requires a specific time after which it stops the cell which of course is not efficient because it doesn’t guarantee the process to be done.

# Path to the executable
exe_path = r"C:tempPipelineAutomate_LiDAR_processingAutomate_LiDAR_Processing_V2.2.exe"

# Start the executable process
process = subprocess.Popen(exe_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

commands = [
    "1n",
    "C:\tempPipelineAutomate_LiDAR_processingTemplatesReconstructionPWMMS_HAHDL32EFn",
    "C:\tempPipelinehdl32e_front_leftn",
    "C:\tempPipelineCode\20231101_Transit_US231_Trajectory_TC_revised.txtn",
    "test_outputn",
    "C:\tempPipelineoutput_folder_2n"
    
]

# Start the executable process
process = subprocess.Popen(exe_path, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

# Send commands to the executable
for command in commands:
    process.stdin.write(command)
    process.stdin.flush()

# Wait for the process to finish with a timeout of 60 seconds
try:
    output, error = process.communicate(timeout=30)
except subprocess.TimeoutExpired:
    # Handle timeout if necessary
    print("Timeout expired. Process might still be running.")

# Terminate the executable process
process.terminate()

LEAVE A COMMENT