weider weider - 16 days ago 6
Linux Question

Time of script execution [EDIT]

I read a serial port and send data to python, I want this chain to work for 10 seconds. The code below does not work:

sudo cat -v /dev/pts/2 | python3 bash_test.py
pid=$!
sleep 10
kill -9 $pid


[UPDATE]
e.g bash_test.py

import sys
for line in sys.stdin:
print(line,'\n')

Answer

You can use timeout :

sudo bash -c "cat -v /dev/pts/2 | timeout 10 python3 bash_test.py"

Command info:

NAME
       timeout - run a command with a time limit

SYNOPSIS
       timeout [OPTION] DURATION COMMAND [ARG]...
       timeout [OPTION]

Simple example for timeout:

timeout 3 sleep 10

The command here is sleep 10 but timeout will kill it after 3 seconds.