简体   繁体   English

如何从python停止shell脚本(运行无限循环)?

[英]How to stop a shell script (running a infinite loop ) from python?

I have a shell script (test.sh -> example shown below) which has a infinte while loop and prints some data to screen. 我有一个shell脚本(下面显示的test.sh->示例),它具有一个infinte while循环并将一些数据打印到屏幕上。 I am calling all my .sh scripts from python and I need to stop the test.sh before calling my other commands I am using python 2.7 and linux system is on propritary hardware where I cannot install any python modules. 我正在从python调用我的所有.sh脚本,我需要先停止test.sh,然后再调用其他命令(我正在使用python 2.7),并且linux系统位于专用硬件上,无法安装任何python模块。

Here is my test.sh 这是我的test.sh

#!/bin/sh
while :
do
        echo "this code is in infinite while loop"
        sleep 1
done

Here is my python Scripts 这是我的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'])


Well, quick google search made me look into subprocess call and Popen modules . 好吧,快速的Google搜索使我了解了子流程调用和Popen模块。 and Popen has a terminate option and it doesn't work for me (or) I'm doing something wrong here Popen有一个终止选项,它对我不起作用(或)我在这里做错了

cmd=['test.sh']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
p.terminate()

Any other suggestions on how I can stop the test.sh from python are highly appreciated 高度赞赏我如何从python停止test.sh的任何其他建议

PS: I don't mind to run the test.sh for like T seconds and then stop it PS:我不介意将test.sh运行T秒钟然后停止它

I use tmux for these type of processes, python has a good package libtmux which should solve your problem. 我将tmux用于这些类型的进程,python有一个很好的软件包libtmux ,可以解决您的问题。

Basically you create a tmux session: 基本上,您创建一个tmux会话:

import libtmux
server = libtmux.Server()
session = server.new_session(session_name='my_session_name')

then you create a window to run the command in 然后创建一个窗口以在其中运行命令

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)

You'll be able to run subsequent commands right after this one. 您可以在此命令之后立即运行后续命令。 To access the tmux session from your bash terminal use tmux attach -t my_session_name you'll then be in a tmux window, the one which ran your bash script. 要从bash终端访问tmux会话,请使用tmux attach -t my_session_name您将进入一个tmux窗口,该窗口运行您的bash脚本。

To kill the tmux window use window.kill_window() there's a lot of options look at the libtmux docs. 要杀死tmux窗口,请使用window.kill_window()有很多选项可以查看libtmux文档。

The project aileen has some useful tmux commands if you want to see some more implementations. 如果您想了解更多实现,项目aileen有一些有用的tmux命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM