0

I am trying to write a bash script which launches an external python script, with some conditions.

The goal is to avoid waiting for the python script to complete, but wait a delay (eg. 30 seconds) and send the process to background if the python script is still running.

Very simplified python script example:

#!/usr/bin/python  
import time  
time.sleep(120)

In this case, I would like the bash script to launch the python script, wait for 30 seconds, and send the python process to background (like nohup example.py & would do).

In case the python script would crash during the 30 seconds delay, the error message should display on terminal.

I cannot modify the python script.

Is it possible to do it in a clean way?

I managed to do the job by using nohup / & and redirecting output of the python script to a temp file, and read this file after 30 seconds, to check if there is no error message.

But I am curious to know if there is a better way.

Thanks!

oguz ismail
  • 1
  • 16
  • 47
  • 69
Tuxman
  • 23
  • 5
  • Does this cover your goals? https://stackoverflow.com/questions/10028820/bash-wait-with-timeout – jordanm Jun 04 '20 at 21:11
  • Well, no. I don't want the process to be killed after the delay. I just want it to go in background if it is still running. This is a very specific python script, and i know it can crash only in the first seconds. then the execution time may take several days. – Tuxman Jun 04 '20 at 21:23
  • Yeah, I see you actually want to do the opposite of that accepted answer. I do think that starting in the foreground at all is going to a wrong approach. So you want something like this? `while :; do python foo.py & pid=$!; sleep 30; kill -0 $pid && break; done`. That will start foo.py, wait 30 seconds, see if it's still alive and if it's not repeat. – jordanm Jun 04 '20 at 21:28
  • You need to provide more details. Like, why do you want this to be a script and not a function defined in the `.bashrc` file? Is this going to be a part of a bigger script? Does the program to be sent to background print anything to terminal after 30 seconds? Does it have to be in the foreground within the first 30 seconds after it's invoked? Do you want to be able to interact with it in that period? And what's wrong with the nohup solution you came up with yourself? – oguz ismail Jun 05 '20 at 09:19

1 Answers1

0

The approach suggested by Jordanm (start the process in background) will provides the right direction. Consider the following bash script, which uses 2 background jobs inside bash wrapper.

#! /bin/bash

sleep 30 &
sleep_pid=$!
(python -c 'import time ; time.sleep(10)' ; kill $sleep_pid) &
if wait $sleep_pid ; then
    echo "Python continue in background ..."
else
    echo "Python Completed"
fi

As an alternative, can be implement in Python/Perl, using a single background process.

dash-o
  • 13,723
  • 1
  • 10
  • 37