0

I need to open and close a application on a Windows machine using Python. I tried (opening the calculator):

import subprocess, time
p = subprocess.Popen(["calc"])
time.sleep(2)
p.terminate()

also using

p.kill()

does not work.

However, it seems that while the (python internal) subprocess is terminated, the application still remains visible on the screen (the calculator window does not close).

How can I open and close some application (including the actual visible window)?

Peter
  • 2,120
  • 2
  • 19
  • 33
  • Maybe this one: https://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true – learner Oct 21 '22 at 13:13
  • Not a windows user, but since you are using pid. Try p.kill() might work. – spramuditha Oct 21 '22 at 13:15
  • `p.kill` does not close the window, regardless if opened with `shell=True` argument or not. – Peter Oct 21 '22 at 13:20
  • A `p.wait()` after `p.terminate()` may also help. Ref.: https://stackoverflow.com/questions/41961430/how-to-cleanly-kill-subprocesses-in-python – learner Oct 21 '22 at 13:20
  • No does not work either, I checkt the `p.wait()` command as well. This is why I'm puzzled, nothing seen elsewhere worked so far. `p.wait()` seems to ensure clean termination of the (internal) process, but visible window is unaffected (on my machines) – Peter Oct 21 '22 at 13:21
  • try ```os.kill(pid, signal.SIGTERM)``` or ```os.kill(pid, signal.SIGKILL)``` – spramuditha Oct 21 '22 at 13:33
  • Sorry for asking to just try stuff. . . I do remember I dealt with something like this a long time ago. It wasn't a hard solution. But can't pinpoint. :) – spramuditha Oct 21 '22 at 13:35
  • I also tried with `import signal` `signal.SIGTERM` but no success. Your line throws an error "an integer is required (got type SubprocessPopen)" – Peter Oct 21 '22 at 13:49
  • I tried `os.system("taskkill /f /im Calculator.exe")` and it successfully closes the task with the corresponding name... It might be a good starting point to generalize it using the child process pid... – learner Oct 21 '22 at 14:06

1 Answers1

0

I was able to close the window in the foreground using the win32 library:

import subprocess, time
import win32gui, win32con

for x in range(2):
    # Open calculator
    p = subprocess.Popen(["calc"], stdout=subprocess.PIPE, shell=True)
    time.sleep(3)
    # Terminate subprocess
    p.terminate() 
    # Close window in foreground unsing win32
    handler = win32gui.GetForegroundWindow()
    win32gui.PostMessage(handler,win32con.WM_CLOSE,0,0)
    time.sleep(3)
Peter
  • 2,120
  • 2
  • 19
  • 33