Home > OS >  Why isn't subprocess.run working in a seperate thread?
Why isn't subprocess.run working in a seperate thread?

Time:10-09

I'm using subprocess.run() to run a .txt file containing python code. That python code may contain a while loop. I need the rest of my code to run while that is running. The obvious way to do this is using the threading module, when I put subprocess.run() in a separate thread, it returns something like Enable tracemalloc to see traceback (error) or something like that.

#.txt file
while True:
  print("Hello")
#.py file:
import subprocess
import threading as th

def thread():
  subprocess.run('python foo.txt')
th2=th.Thread(target=thread)
th2.start()
#code here

CodePudding user response:

You don't need a thread here at all, since the subprocess is, well, a separate process.

You do, however, need to switch from the blocking .run() convenience function to Popen:

import subprocess
import sys
import time
proc = subprocess.Popen([sys.executable, 'foo.txt'])
# ... do other things here...
time.sleep(1)
proc.kill()
  • Related