这就是我到目前为止所拥有的...
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'])
音乐播放部分效果很好,但是就时间而言,我尝试了线程和时间,但是似乎要做的只是将代码暂停给定的时间。我想在给定的时间内运行子流程,然后返回以等待运动。我还在学习。感谢您的帮助。
答案 0 :(得分:0)
创建您的subprocess
命令。我选择了Popen。
Popen不会阻塞,允许您在进程运行时与其进行交互,或者在Python程序中继续进行其他操作。调用Popen返回一个Popen对象。
您可以阅读subprocess.Popen
和subprocess.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
[kchojnowski@zabbix4-worker1 ~]$ cat log.log
11:31:48,348 root ERROR Timeout! Executed time is more than: 5