linux - 如何从 python 脚本暂停 bash 脚本?

标签 linux subprocess

我想从 python 脚本中暂停 bash 脚本,步骤如下:

  1. 我从 python script reader.py 启动 script writer.sh。

  2. 当 writer.sh 输出第三行时,我想使用 reader.py 中的一些命令暂停执行此脚本.

  3. 我想使用 reader.py 中的一些命令恢复 writer.sh 的执行.

这是那两个脚本,问题是writer.shreader.py 中执行 sleep 命令时不会暂停.所以我的问题是,如何暂停 writer.sh什么时候输出字符串“third”?准确的说(这是我工作中的实际问题)我要writer.sh停止因为reader.py停止读取 writer.sh 的输出.

reader.py :

import subprocess
from time import sleep

print 'One line at a time:'
proc = subprocess.Popen('./writer.sh', 
                        shell=False,
                        stdout=subprocess.PIPE,
                        )
try:                        
    for i in range(4):
        output = proc.stdout.readline()
        print output.rstrip()
        if i == 2:
            print "sleeping"
            sleep(200000000000000)
except KeyboardInterrupt:
    remainder = proc.communicate()[0]
    print "remainder:"
    print remainder

writer.sh :

#!/bin/sh

echo first;
echo second;
echo third;
echo fourth;
echo fith;

touch end_file;

相关问题是,如果 script1 输出文本行,则在 Linux 上使用管道会暂停 script1,例如script1 | script2 , 并且 script2 在读取第三行输入后暂停?

最佳答案

暂停 bash 脚本,您可以向PID 发送SIGSTOP 信号。

如果你想让它恢复,你可以发送SIGCONT信号。

您可以使用pid = proc.pid 获取子进程的pid。

参见 man 7 signal

关于linux - 如何从 python 脚本暂停 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12956259/

相关文章:

linux - SCTP RCVBUF 在 Linux 中设置不正确

python - 在 python 中替代子进程

python - 如何终止Python Popen创建的进程

linux - "#exec cgi"命令在 html 中被忽略;相同的脚本作为 "form post"命令运行

linux - 我如何判断一个进程当前是否在运行时 fork ?

php - 在Linux上使用ImageMagick命令行进行批量转换时,结果损坏

python - 使用 Python 在 Linux 和 Windows 中查找文件的最快方法是什么?

python - 在 Python 的子进程中列出超出范围的索引

python - django celery 终止任务的子进程

使用导入子进程的 Python 子进程