2017-07-13 20 views
0

コードを実行しようとしています。終了すると、何が起こったのかを示すメッセージが表示されます。これは、私が端末上で実行する場合、正常に動作します。しかし、私はそれをcronjobに追加すると何も起こらず、エラーは表示されません。 それはディスプレイセッションを失っているようですが、それを解決する方法がわかりません。ここで提示メッセージコードは次のとおりです。pythonがバックグラウンドで実行されているときにユーザーに通知する

def sendmessage(message): 
    subprocess.Popen(['notify-send', message]) 
return 

私もこのバージョンを試してみました:

def sendmessage(message): 
    Notify.init("Changes") 
    n = Notify.Notification.new(message) 
    n.show() 
return 

(また、唯一のバックグラウンドで)エラーを与える:

することはできません開いて表示:活性化 サービス 'org.freedesktop.Notifications' failed:状態で終了したorg.freedesktop.Notifications

ご迷惑をおかけして申し訳ございません。

+1

他のユーザーのXセッションでプログラムを実行するには、アクセス権が必要です。これを行う方法については、[この回答](https://stackoverflow.com/a/1584434/154762)を参照してください。 – solarc

答えて

1

システムデーモンを実行していると同様の問題が発生しました。ここでは、ネットワーク帯域幅のアップロードが超過したことをユーザーに通知する必要がありました。
プログラムはsystemdで実行されるように設計されていますが、プッシュでもupstartの下に実行されるように設計されています。

は、あなたは私の構成ファイルのうちのいくつかの走行距離を得ることができます:

systemd - bandwidth.serviceファイル

[Unit] 
Description=Bandwidth traffic monitor 
Documentation=man:bandwidth(7) 
After=graphical.target 

[Service] 
Type=simple 
Environment="DISPLAY=:0" "XAUTHORITY=/home/#USER#/.Xauthority" 
PIDFile=/var/run/bandwidth.pid 
ExecStart=/usr/bin/dbus-launch /usr/sbin/bandwidth_logd 
ExecReload=/bin/kill -HUP $MAINPID 
User=root 

[Install] 
WantedBy=graphical.target 

upstart - bandwidth.confファイルあなたにはそれに注意します

# 
# These are the scripts that run when a network appears. 
# Use this on an upstart system in /etc/init 
# test for systemd or upstart system with 
# ps -p1 | grep systemd && echo systemd || echo upstart 
# better 
# ps -p1 | grep systemd >/dev/null && echo systemd || echo upstart 
# Using upstart the script will need to daemonise which is a bugger 
# so test for it and import Daemon_server.py 
description "Bandwidth upstart events" 

start on net-device-up  # Start a daemon or run a script 
stop on net-device-down # (Optional) Stop a daemon, scripts already self-terminate. 
# Automatically restart process if crashed 
respawn 

# Essentially lets upstart know the process will detach itself to the background 
expect fork 

#Set environment variables 
env DISPLAY=":0" 
export DISPLAY 
env XAUTHORITY="/home/#USER#/.Xauthority" 
export XAUTHORITY 

script 
# You can put shell script in here, including if/then and tests. 
# replace #USER# with your name and ensure that you have .Xauthority in $HOME 

/usr/sbin/bandwidth_logd 
end script 

どちらの設定ファイルでも環境が鍵になり、#USER#は有効なユーザ名で置き換えられます。.Xauthority fil eを$ HOMEディレクトリに追加します。
Pythonコードでは、次のコマンドを使用してメッセージ(import notify2)を発行します。

def warning(msg): 
    result = True 
    try: 
     notify2.init("Bandwidth") 
     mess = notify2.Notification("Bandwidth",msg,'/usr/share/bandwidth/bandwidth.png') 
     mess.set_urgency(2) 
     mess.set_timeout(0) 
     mess.show() 
    except: 
     result = False 
    return result 
関連する問題