Skip to main content
 首页 » 编程设计

python之如何在 python 中创建和销毁独立于操作系统的非阻塞子进程

2025年05月04日10think

  • 在 python 脚本中,我想生成一个在同一目录中运行文件的进程
  • 我不希望 python 脚本被新进程阻塞
  • 然后希望能够从脚本中关闭生成的进程。
  • 最重要的是,我需要它独立于操作系统。

这样做的好处是什么?

请您参考如下方法:

正如@Keith 建议的那样使用 subprocess 模块,但更具体地说是使用 Popen。例如,在 Windows 上,这会用记事本打开 myfile.txt,然后在 20 秒后终止它:

import subprocess 
import time 
 
command = "notepad myfile.txt" 
pipe = subprocess.Popen(command, shell=False) 
time.sleep(5) 
pipe.poll() 
print("%s" % pipe.returncode)   #"None" when working fine 
time.sleep(5) 
pipe.terminate() 
pipe.wait() 
print("%s" % pipe.returncode)   # 1 after termination