【发布时间】: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循环中,我无权更改该脚本..唯一的选择是解决方法