如何在python中停止另一个已经运行的脚本? [英] How to stop another already running script in python?

查看:800
本文介绍了如何在python中停止另一个已经运行的脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种方法可以在python中启动另一个脚本:

There is a way to start another script in python by doing this:

import os

os.system("python [name of script].py")

那我怎么能停止另一个已运行的脚本?我想通过使用名称来停止脚本。

So how can i stop another already running script? I would like to stop the script by using the name.

推荐答案

import 更常见另一个脚本然后调用它的函数和方法。

It is more usual to import the other script and then invoke its functions and methods.

如果这对你不起作用,例如另一个脚本不是以有利于导入的方式编写的,那么你可以使用 子流程 模块启动另一个流程。

If that does not work for you, e.g. the other script is not written in such a way that is conducive to being imported, then you can use the subprocess module to start another process.

import subprocess

p = subprocess.Popen(['python', 'script.py', 'arg1', 'arg2'])
# continue with your code then terminate the child
p.terminate()

有许多可能的方法来控制子进程并与之交互,例如你可以捕获它的stdout和sterr,并发送它输入。请参阅 Popen() 文档。

There are many possible ways to control and interact with the child process, e.g. you can can capture its stdout and sterr, and send it input. See the Popen() documentation.

这篇关于如何在python中停止另一个已经运行的脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆