Python and Pynotify error "gio.Error: Connection Closed"

326 Views Asked by At

i'm new on python and pynotify i want to create a notify message that shows me a notification with python and pynotify but i have a problem, all examples i use on tutorials found on internet.

ex.

#!/usr/bin/python
import sys
import pynotify

if __name__ == "__main__":
    if not pynotify.init("icon-summary-body"):
        sys.exit(1)

    n = pynotify.Notification(
        "Hi There",
        "welcome to stackoverflow!",
        ##dont remove the below line
    "notification-message-im")
    n.show()

or

#!/usr/bin/env python

import os
import pynotify

pynotify.init("random information")
s = os.popen("fortune -n 100 -s","r").read()
n = pynotify.Notification("Fortune",s)
n.show()

gives me always the same error

** (icmp.py:13188): WARNING **: Connection Closed
Traceback (most recent call last):
  File "icmp.py", line 14, in <module>
    n.show()
gio.Error: Connection Closed

What does it mean??

Thanks

3

There are 3 best solutions below

0
On

To me the only way for now to use notification while using sudo python is by calling notify-send with subprocess:

Desktop environment: xfce4

WIP method (Insecure): sudo -Eu root python2.7

import os, subprocess

SudoUser = os.environ['SUDO_USER']

DBUSAddress = "DBUS_SESSION_BUS_ADDRESS={}".format(os.environ['DBUS_SESSION_BUS_ADDRESS'])

NotiCommand='{} notify-send "Welcome" "{}"'.format(DBUSAddress, SudoUser)

CompleteCall = 'sudo -u {} {}'.format(SudoUser, NotiCommand)

subprocess.call(CompleteCall, shell=True)

There you go! In my case this problem is the result of the tight security in Arch based distros as debian base distros are more flexible or actually insecure. Because this is more like a hack and it uses "shell=True" it's not recommended.

0
On

Sometimes this can happen when there is too long of a gap between calling .init() and creating the notification. There is a timeout, and when you call pynotify.init() that can elapse. If you make sure you call it again immediately before issuing the notification, you should quell this error.

0
On

Well, I am responding you a year after posting this question. You may have already got the solution. So I will answer for other people facing the problem.

I was working on one project which uses Pynotify and I encountered the same problem. After a lot of research I found out that I was calling my script with root user. If you are also running your script with root user, then it may be the problem. The problem is that root does not have a dbus session running. I guess it does not even own XScreen. I assume you want to use Dbus session that belongs to the logged in user.

Solution 1: Use gksu. GUI applications should be started with gksu, not su or sudo.

Solution 2: Add following to your script.

import os
os.environ['DISPLAY'] = ':0.0'

Solution 3: Add root user to dbus group. [Not Verified]

I hope it helps.