簡體   English   中英

如何從python停止shell腳本(運行無限循環)?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM