简体   繁体   中英

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. 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.

Here is my test.sh

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

Here is my python Scripts

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 . and Popen has a terminate option and it doesn't work for me (or) I'm doing something wrong here

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

PS: I don't mind to run the test.sh for like T seconds and then stop it

I use tmux for these type of processes, python has a good package libtmux which should solve your problem.

Basically you create a tmux session:

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.

To kill the tmux window use window.kill_window() there's a lot of options look at the libtmux docs.

The project aileen has some useful tmux commands if you want to see some more implementations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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