简体   繁体   English

脚本执行时间[编辑]

[英]Time of script execution [EDIT]

I read a serial port and send data to python, I want this chain to work for 10 seconds. 我读取了一个串行端口并将数据发送到python,我希望此链能够工作10秒钟。 The code below does not work: 下面的代码不起作用:

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

[UPDATE] eg bash_test.py [更新]例如bash_test.py

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

You can use timeout : 您可以使用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简单示例:

timeout 3 sleep 10

The command here is sleep 10 but timeout will kill it after 3 seconds. 这里的命令是sleep 10但是timeout将在3秒后将其杀死。

Try adding & sign after your sudo 尝试在sudo之后添加并签名

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

The following code open a "sub-bash" environment where the actual command is running. 下面的代码打开运行实际命令的“ sub-bash”环境。 In this way it can run in background. 这样,它可以在后台运行。 There could be some problem if you are using threads or multiprocessing in the python script. 如果您在python脚本中使用线程或多处理,可能会有一些问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM