[英]How to stop a shell script (running a infinite loop ) from python?
我有一个shell脚本(下面显示的test.sh->示例),它具有一个infinte while循环并将一些数据打印到屏幕上。 我正在从python调用我的所有.sh脚本,我需要先停止test.sh,然后再调用其他命令(我正在使用python 2.7),并且linux系统位于专用硬件上,无法安装任何python模块。
这是我的test.sh
#!/bin/sh
while :
do
echo "this code is in infinite while loop"
sleep 1
done
这是我的python脚本
import subprocess as SP
SP.call(['./test.sh']) # I need to stop the test.sh in order for python to
# go and execute more commands and call
# another_script.sh
# some code statements
SP.call(['./another_script.sh'])
好吧,快速的Google搜索使我了解了子流程调用和Popen模块。 Popen有一个终止选项,它对我不起作用(或)我在这里做错了
cmd=['test.sh']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.terminate()
高度赞赏我如何从python停止test.sh的任何其他建议
PS:我不介意将test.sh运行T秒钟然后停止它
我将tmux用于这些类型的进程,python有一个很好的软件包libtmux ,可以解决您的问题。
基本上,您创建一个tmux会话:
import libtmux
server = libtmux.Server()
session = server.new_session(session_name='my_session_name')
然后创建一个窗口以在其中运行命令
window = session.new_window(attach=False, window_name='my_window_name')
command = './my_bash_file.sh'
window.select_pane('0').send_keys(command, enter=True)
您可以在此命令之后立即运行后续命令。 要从bash终端访问tmux会话,请使用tmux attach -t my_session_name
您将进入一个tmux窗口,该窗口运行您的bash脚本。
要杀死tmux窗口,请使用window.kill_window()
有很多选项可以查看libtmux文档。
如果您想了解更多实现,项目aileen有一些有用的tmux命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.