Robert
Robert

Reputation: 31

How to pause bash script from python script?

I want to pause bash script from python script, the steps look like this:

  1. I start script writer.sh from python script reader.py.

  2. When writer.sh outputs third line I want executing of this script to be paused using some command in reader.py.

  3. I want to resume execution of writer.sh using some command in reader.py.

Here are those two scripts, the problem is that writer.sh doesn't pause when sleep command is executed in reader.py. So my question is, how can I pause writer.sh when it outputs string "third"? To be exact (this is my practical problem in my job) I want writer.sh to stop because reader.py stopped reading output of 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;

Related question is, will using pipes on Linux pause script1, if script1 outputs lines of text, e.g. script1 | script2, and script2 pauses after reading third line of input?

Upvotes: 3

Views: 486

Answers (1)

Gilles Quénot
Gilles Quénot

Reputation: 184965

To pause the bash script, you can send the SIGSTOP signal to the PID.

If you want it to resume, you can send the SIGCONT signal.

You can get the pid of the subprocess with pid = proc.pid.

See man 7 signal

Upvotes: 1

Related Questions