Search code examples
pythonsubprocesspython-multithreading

Running games using functions


My Code:

import threading
import time 
import subprocess
Thread1 = threading.Thread(target=Run_exe)

def run_exe():
    subproccess.call("game.exe")

while True:
   time.sleep(3600)
   x = int(input(""))
   if x==1:
      Thread1.start()
   else:
      Thread1.join()

My objective is the following:

  • Run the game using the Run_exe function

  • Kill thread when I exit the game

I don't want to exit game from the game itself the Python program should get an input to exit the games by killing the thread.


Solution

  • Use subprocess.Popen constructor and save the pid:

    process = subprocess.Popen("game.exe")
    pid = process.pid
    

    If you want to stop the process, call: (from this answer)

    import os
    import signal
    
    os.kill(pid, signal.SIGTERM) #or signal.SIGKILL