better way to interrupt my python code when subprocess is running?

有些话、适合烂在心里 提交于 2020-01-15 06:53:10

问题


I recently answered a question here

The question was: how to interrupt a python script when a subprocess is running (possibly windows-specific).

I suggested to create a thread to run the subprocess on, and wait on the mainloop for CTRL+C / KeyboardInterrupt exception so the child process can be killed.

It works, but bit of a hack because I did this: Basically, I make a non-cpu active (but polling) loop which waits 100ms then checks for the shared boolean done. If the subprocess exits, the thread sets done. If CTRL+C is pressed, the main process goes in the exception handler and kills the process.

...

t = threading.Thread(target=s)
t.start()


try:
    while not done:
        time.sleep(0.1)

except KeyboardInterrupt:
    print("terminated")
    proc.terminate()
...

I wanted to improve it to use thread locks. So I rewrote it, looks clean, not so much shared variables, no more time loops, looks ideal, except that ... it doesn't work. CTRL+C is not responding while in the lock.acquire() of the main loop.

import subprocess
import threading

import time

binary_path = 'notepad'
args = 'foo.txt' # arbitrary

proc = None

lock = threading.Lock()

def s():
    call_str = '{} {}'.format(binary_path, args)
    global proc
    proc = subprocess.Popen(call_str,stdout=subprocess.PIPE)
    proc.wait()
    lock.release()

lock.acquire()

t = threading.Thread(target=s)
t.start()

try:
    lock.acquire()   # CTRL+C is inoperant here

except KeyboardInterrupt:
    print("terminated")
    proc.terminate()

I saw this question which makes me think that my time loop isn't that bad after all. The thread lock is probably executing Windows code (not Python) and not responding to CTRL+C. In that case, why can I interrupt a time.sleep() ?

Is there a way to make it work with clean OS calls ?

来源:https://stackoverflow.com/questions/39544578/better-way-to-interrupt-my-python-code-when-subprocess-is-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!