3

I have a bash file in which I execute a python code in a for loop several times. I want to set a timeout so that if the python code takes more than a certain time then we go to the next iteration. How can I add timeout to my bash code line when compiling and running the python file? This is the current line I use for running the python code:

python hw.py

I want to have something like this:

python hw.py timeout=120
USC.Trojan
  • 391
  • 5
  • 14
  • You want the logic in `bash` or in `python`? – Inian Feb 16 '17 at 09:17
  • I need it in bash, I am not able to edit the python file, I am giving different inputs to the python file each time in a for loop and want it to kill python with a timeout limit. – USC.Trojan Feb 16 '17 at 22:41

2 Answers2

7

You can use the timeout command in bash:

timeout 120 python hw.py

That will kill the python process if it executes for more that 120 seconds.

oliv
  • 12,690
  • 25
  • 45
0

Assume you want the argument to be parsed into the Python script.

Try argparse:

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--timeout', help='timeout of script',action = 'store')
    args = parser.parse_args()

Parse args.timeout to the script that you need.

from time import time 
start = time()
for loop: # the for loop you mentioned

    if (time() - start) > timeout:
        break
Alex Fung
  • 1,996
  • 13
  • 21