启动:Python通知者.通知不产生预期输出

2024-03-28 22:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

编辑:我把范围缩小到python代码中的Notifier.notify('Something')问题。当python脚本从launchd启动时,这不会产生预期的行为。我的其他python脚本工作得很好。/编辑

osx10.11.4:我正在尝试使用launchd在目录中发生变化时(例如,有人添加了一个文件)运行python3.5脚本。我使用了下面的plist文件(放在~/Library/LaunchAgents中,并加载了launchctl),它似乎与shell脚本

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.test.notifyme</string>
    <key>ProgramArguments</key>
    <array>
        <string>/path/to/notifyme.sh</string>
    </array>
    <key>WatchPaths</key>
    <array>
        <string>/path/to/NotifyMeDir</string>
    </array>
</dict>
</plist>

这是shell脚本:

#!/bin/bash
# notifyme.sh
osascript -e "tell application \"System Events\" to display notification \"Something\""

但是当我将plist文件更改为:

    <key>ProgramArguments</key>
    <array>
        <string>/path/to/notifyme.py</string>
    </array>

调用以下python程序

#!/path/to/python3.5
# notifyme.py
from pync import Notifier

Notifier.notify('Something')

当我更改NotifyMeDir目录中的文件时,我不再获得预期的输出。你知道吗

/var/日志/系统日志尝试使用launchd启动.py文件时提供以下信息:

... com.apple.xpc.launchd[1] (com.test.notifyme): Service only ran for 4 seconds. Pushing respawn out by 6 seconds.

因此,launchd在识别目录已更改方面工作正常-它只是没有执行python脚本。你知道吗

我有一个解决方法,涉及从shell脚本调用python程序。但是,只有在调用python程序后使用“osascript”执行shell命令时,这才有效。我在shell脚本和python脚本上都适当地调用了'cdmod u+x…',它们在launchd之外自己调用时都可以工作。当与“watchpath”以外的东西一起使用时(例如每15秒运行一次),它也可以正常工作。你知道吗

以下是解决方法:

#!/bin/bash
/path/to/python /path/to/notifyme.py

osascript -e "tell application \"Finder\" to activate"

如你所见,这似乎没有任何关系 我被难住了。为了调用python脚本,我希望在不需要调用shell脚本的情况下运行这个脚本。你知道吗


Tags: 文件topathkeypy脚本comstring
2条回答

不要使用time.sleep,只使用wait选项。你知道吗

官方称

The options 'wait' is a boolean for whether or not we need to wait (block) for the background process to finish

所以,你只要像我一样跑就行了

pync.notify('message', wait=True)

参考号:notify sourcecode

好的-我知道了。Pync.Notifier.notify正在对/usr/local/bin/terminal-notifier进行系统调用。程序的其余部分不会等待调用它,所以程序在系统调用完成之前就已经结束了(我猜?)。无论如何,解决方案只是确保python脚本在Notifier.notify调用之后有足够的内容,以便可以完成对/usr/local/bin/terminal-notifier的调用。在这里,time.sleep()调用是一种没有恶意的解决方法。你知道吗

解决方案:

#!/path/to/python3.5
# notifyme.py
from pync import Notifier
import time

Notifier.notify('Something')
time.sleep(0.1)

相关问题 更多 >