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

2024-04-26 07:07:28 发布

您现在位置:Python中文网/ 问答频道 /正文

  • 在python脚本中,我希望生成一个进程,在同一目录中运行一个文件
  • 我不希望python脚本被新进程阻塞
  • 然后希望能够从脚本中关闭派生的进程。你知道吗
  • 在这上面我需要它是独立的。你知道吗

这样做最好的是什么?你知道吗


Tags: 文件目录脚本进程
1条回答
网友
1楼 · 发布于 2024-04-26 07:07:28

正如@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

相关问题 更多 >