为什么subprocess.run不在单独的线程中工作?



我正在使用subprocess.run()运行一个包含python代码的.txt文件。该python代码可能包含while循环。我需要我的其余代码在运行时运行。显而易见的方法是使用threading模块,当我将subprocess.run()放在一个单独的线程中时,它会返回类似Enable tracemalloc to see traceback(错误(之类的东西。

#.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

这里根本不需要线程,因为子流程是一个单独的流程。

但是,您确实需要从阻止.run()便利功能切换到Popen:

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

最新更新