运行 python 带有 sudo 动作的脚本无法获得输出

Run python scripts with sudo motion can't get output

import subprocess

p = subprocess.Popen(['sudo motion'],
        shell = True,
          stdout = subprocess.PIPE,
          stdin = subprocess.PIPE)
p.wait()

stdout, stderr = p.communicate()

out = stdout.decode('utf-8')

print('-----------', out)

并且我使用“python3 sh2.py”运行 上述脚本但得到以下结果

[22636168:motion] [NTC] [ALL] conf_load: Processing thread 0 - config file /etc/motion/motion.conf
[22636168:motion] [NTC] [ALL] motion_startup: Motion 4.1.1 Started
[22636168:motion] [NTC] [ALL] motion_startup: Logging to file (/var/log/motion/motion.log)
-----------

我怎样才能得到结果

如果你想通过p.communicate()捕获stderr,你需要在你的Popen调用中将stderr设置为subprocess.PIPE(相比之下,它似乎没有就像你在使用 stdin):

p = subprocess.Popen(['sudo motion'],
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)

默认情况下,motion 作为守护进程启动,运行在后台运行。

根据正在执行的操作,您可能希望在某些事件发生时将其配置为 运行 您的脚本,使用 on_ 配置设置之一(on_event_starton_picture_save, 等等).