【问题标题】:How to stop a shell script (running a infinite loop ) from python?如何从 python 停止 shell 脚本(运行无限循环)?
【发布时间】:2019-07-16 14:49:41
【问题描述】:

我有一个 shell 脚本(如下所示的 test.sh -> 示例),它有一个无限的 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'])


好吧,快速的谷歌搜索让我研究了 subprocess call 和 Popen modules 。并且 Popen 有一个终止选项,它对我不起作用(或)我在这里做错了

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

非常感谢任何其他关于如何从 python 中停止 test.sh 的建议

PS:我不介意运行 test.sh 大约 T 秒然后停止它

【问题讨论】:

  • 你确定你需要停止你的shell进程吗?也许您只想在另一个线程中运行?
  • “终止”调用向子进程发送 SIGTERM 信号。如果您进一步搜索,您可能会在类似 Linux 的系统上找到“kill”,它会向孩子发送 SIGKILL。但是,除非脚本有什么不寻常的地方可以忽略这些信号,否则 SIGTERM 应该可以工作。
  • 来自代码中的 cmets:“我需要停止 test.sh 以便 python 执行更多命令并调用 another_script.sh”。如果你想阻止它,为什么首先打电话给test.sh?你不需要它的结果吗?另请参阅关于使用不同线程的第一条评论。
  • 换句话说:你的实际用例是什么来停止脚本,而不是等待它完成和它的结果?
  • @00 'test.sh' 是来自上游代码的 shell 脚本,类似于启动脚本,每 1 秒显示一次特定结果。我可以使用不同的命令集获得这些结果(一旦设置了初始化变量)。这些结果每秒更新一次并保持在一个while循环中,我无权更改该脚本..唯一的选择是解决方法

标签: python shell sh


【解决方案1】:

我对这些类型的进程使用 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,然后您将进入一个运行 bash 脚本的 tmux 窗口。

要杀死 tmux 窗口,请使用 window.kill_window(),查看 libtmux 文档有很多选项。

如果您想查看更多实现,aileen 项目有一些有用的 tmux 命令。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2020-12-21
    • 2018-11-19
    • 1970-01-01
    相关资源
    最近更新 更多