python - Python:如何从另一个脚本终止脚本的功能
问题描述
我有一个脚本,它从库main.py
中调用一个函数。fun
我只想退出fun
继续脚本main.py
,为此目的使用另一个脚本kill_fun.py
。
我尝试使用不同的 bash 命令(使用 os.system)与ps
,但它给我的 pid 仅指main.py
.
例子:
-main.py
from lib import fun
if __name__ == '__main__':
try:
fun()
except:
do_something
do_something_else
-lib.py
def fun():
do_something_of_long_time
-kill_fun.py
if __name__ == '__main__':
kill_only_fun
解决方案
fun
您可以通过在不同的进程中运行来做到这一点。
from time import sleep
from multiprocessing import Process
from lib import fun
def my_fun():
tmp = 0
for i in range(1000000):
sleep(1)
tmp += 1
print('fun')
return tmp
def should_i_kill_fun():
try:
with open('./kill.txt','r') as f:
read = f.readline().strip()
#print(read)
return read == 'Y'
except Exception as e:
return False
if __name__ == '__main__':
try:
p = Process(target=my_fun, args=())
p.start()
while p.is_alive():
sleep(1)
if should_i_kill_fun():
p.terminate()
except Exception as e:
print("do sth",e)
print("do sth other thing")
杀fun
_echo 'Y' > kill.txt
或者您也可以编写一个 python 脚本来编写文件。
解释
这个想法是从fun
不同的过程开始。p
是您可以控制的进程处理程序。然后,我们放一个循环来检查文件kill.txt
,看看是否有kill命令'Y'。如果是,则调用p.terminate()
. 然后该进程将被终止并继续执行下一步操作。
希望这可以帮助。
推荐阅读
- r - 如何在 flexdashboard 中删除或隐藏此输出窗口?
- c# - 如何根据 Unity 的文件夹结构设置命名空间
- jquery - 禁用基于 Radio selected 的 SELECT 选项不适用于 jquery 3.4.1
- javascript - 如何将结果从猫鼬分组为较小的子数组
- python - pyspark matplotlib 与 Zeppelin 的集成
- javascript - 如何在 Flow 中正确输入渲染道具?
- python - 为 python smtplib 获取“网络无法访问”
- r - 在与 map_df 循环中的其他表堆叠之前将 HTML_tables 转换为字符
- oauth-2.0 - 使用 Azure AD 通过 OAuth2 对 Azure API 管理进行身份验证
- html - Ajax,旧值先出现,然后新值出现