如何使子流程运行一定的时间,然后返回循环并等待触发器?

时间:2019-11-29 02:07:54

标签: python python-3.x

这就是我到目前为止所拥有的...

from gpiozero import MotionSensor
import subprocess 
import threading
import time

pir = MotionSensor(4)

while True:
   pir.wait_for_motion()
print("Start Playing Music")
subprocess.call(['mplayer', '-vo', 'null', '-ao', 'alsa', '-playlist', 'myplaylist', '-shuffle'])

音乐播放部分效果很好,但是就时间而言,我尝试了线程和时间,但是似乎要做的只是将代码暂停给定的时间。我想在给定的时间内运行子流程,然后返回以等待运动。我还在学习。感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

Python 2.7-3.x

创建您的subprocess命令。我选择了Popen。

  

Popen不会阻塞,允许您在进程运行时与其进行交互,或者在Python程序中继续进行其他操作。调用Popen返回一个Popen对象。

您可以阅读subprocess.Popensubprocess.call here

您可以使用shlex模块拆分字符串命令-非常舒适。

之后,您可以在线程中调用命令。从这一刻起,您可以管理线程中调用的任务。有一个简单的示例,该如何做:

代码示例:

import logging
import shlex
import subprocess
import sys
import threading

logging.basicConfig(filename='log.log',
                    filemode='a',
                    format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                    datefmt='%H:%M:%S',
                    level=logging.INFO)

log = logging.getLogger(__name__)


def exec_cmd(command):
    try:
        cmd = subprocess.Popen(shlex.split(command),  # nosec
                               shell=False,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               universal_newlines=True)
        _thread_command(cmd)
        out, err = cmd.communicate()
        log.error(err) if err else log.info(out)

    except subprocess.CalledProcessError as su_err:
        log.error('Calledprocerr: %s', su_err)

    except OSError as os_error:
        log.error('Could not execute command: %s', os_error)


def _thread_command(task, timeout=5):
    """
    Thread. If task is longer than <timeout> - kill.
    :param task: task to execute.
    """
    task_thread = threading.Thread(target=task.wait)
    task_thread.start()
    task_thread.join(timeout)
    if task_thread.is_alive():  # do whatever you want with your task, for example, kill:
        task.kill()
        logging.error('Timeout! Executed time is more than: %s', timeout)
        sys.exit(1)


if __name__ == '__main__':
    exec_cmd('sleep 10')  # put your string command here

在Centos上测试:

[kchojnowski@zabbix4-worker1 ~]$ cat log.log
11:31:48,348 root ERROR Timeout! Executed time is more than: 5
相关问题