title: Python 3 Stopping subprocess by sending Ctrl C
body: <p>I have some GPU test software i'm trying to automate using python3, The test would normally be run for 3 minutes then cancelled by a user using ctrl+c generating the following output</p>
  
  <p><a href="https://i.stack.imgur.com/VrMEQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VrMEQ.png" alt="GPU test output"></a></p>
  
  <p>After exiting with ctrl+c the test can then be run again with no issue</p>
  
  <p>When trying to automate this with subprocess popen and sending SIGINT or SIGTERM i'm not getting the same as if keyboard entry was used. The script exits abruptly and on subsequent runs cant find the gpus (assume its not unloading the driver properly)</p>
  
  <pre><code>from subprocess import Popen, PIPE
  from signal import SIGINT
  from time import time
  
  
  def check_subproc_alive(subproc):
      return subproc.poll() is None
  
  def print_subproc(subproc, timer=True):
      start_time = time()
      while check_subproc_alive(subproc):
          line = subproc.stdout.readline().decode('utf-8')
          print(line, end="")
          if timer and (time() - start_time) &gt; 10:
              break
  
  
  subproc = Popen(['./gpu_test.sh', '-t', '1'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=False)
  
  print_subproc(subproc)
  
  subproc.send_signal(SIGINT)
  
  print_subproc(subproc, False)
  </code></pre>
  
  <p>How can I send ctrl+c to a subprocess as if a user typed it?</p>
  
  <p>**UPDATE</p>
  
  <pre><code>import subprocess
  
  
  def start(executable_file):
      return subprocess.Popen(
          executable_file,
          stdin=subprocess.PIPE,
          stdout=subprocess.PIPE,
          stderr=subprocess.PIPE
      )
  
  
  def read(process):
      return process.stdout.readline().decode("utf-8").strip()
  
  
  def write(process):
      process.stdin.write('\x03'.encode())
      process.stdin.flush()
  
  def terminate(process):
      process.stdin.close()
      process.terminate()
      process.wait(timeout=0.2)
  
  
  process = start("./test.sh")
  write(process)
  for x in range(100):
      print(read(process))
  terminate(process)
  </code></pre>
  
  <p>Tried the above code and can get characters to register with dummy sh script however sending the \x03 command just sends an empty char and doesn't end script</p>