简体   繁体   English

通知发送在使用 sudo 运行的 python 脚本中不起作用

[英]Notify-send not working in python script run with sudo

I'm writing a python script that is run with sudo permissions.我正在编写一个使用 sudo 权限运行的 python 脚本。 At some point, I would like to send a notification to the user.在某些时候,我想向用户发送通知。 I have noticed that notify-send does not work as a root user, so I tried to run it as the actual user by doing su $SUDO_USER -c notify-send ... , but this does not work either.我注意到 notify-send 不能以 root 用户身份运行,因此我尝试通过执行su $SUDO_USER -c notify-send ...以实际用户身份运行它,但这也不起作用。

The first of the following functions works when run without sudo privileges.以下函数中的第一个在没有 sudo 权限的情况下运行时起作用。 None of them work when run with sudo.使用 sudo 运行时,它们都不起作用。 Any idea why?知道为什么吗?

def notify(message):

    subprocess.run(['notify-send', '-i', 'utilities-terminal', 'Notification Title', message],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE,
                   check=True)


def notifySudo(message):

    subprocess.run(['su', os.environ['SUDO_USER'], '-c', 'notify-send', '-i', 'utilities-terminal', 'Notification Title', message],
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE,
                   check=True)

So after a bit of research, I've found the solution:所以经过一番研究,我找到了解决方案:

import os

def notify(title, message):

    userID = subprocess.run(['id', '-u', os.environ['SUDO_USER']],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            check=True).stdout.decode("utf-8").replace('\n', '')


    subprocess.run(['sudo', '-u', os.environ['SUDO_USER'], 'DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/{}/bus'.format(userID), 
                    'notify-send', '-i', 'utilities-terminal', title, message],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    check=True)

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

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