在Mac上为Python3脚本打开文件(例如右键单击/打开)事件

发布于 2025-01-24 09:33:07 字数 1567 浏览 3 评论 0原文

我希望我的python3脚本对开放文件事件做出反应。有什么方法可以实现吗?以下python3脚本被命名为示例

#!/path/to/python3

from PyQt5.QtWidgets import QApplication, QWidget

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   widget.setWindowTitle("Simple example")
   widget.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

我生成了以下目录,以形成a Bundle

example.app/
-- Contents/
   -- Info.plist
   -- MacOS/
      -- example

info.plist文件:

<?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>CFBundleExecutable</key>
    <string>example</string>
</dict>
</plist>

但是,尽管我可以通过它执行它,例如,双击.app文件本身,但我无法对“打开文件”做出反应。

以下Apple脚本包装器起作用,但非常丑陋:

on open theDroppedItems
    repeat with a from 1 to length of theDroppedItems
        set theCurrentDroppedItem to item a of theDroppedItems
        set posixfile to (POSIX path of theCurrentDroppedItem)
        # display dialog posixfile
        do shell script "/path/to/python3 /path/to/python3script " & posixfile
    end repeat
end open

它将打开文件“转换为命令行”参数。据说,qt 可以工作

I would like my python3 script to react to an open file event. Is there any way to achieve that? The following python3 script is named example

#!/path/to/python3

from PyQt5.QtWidgets import QApplication, QWidget

def window():
   app = QApplication(sys.argv)
   widget = QWidget()

   widget.setWindowTitle("Simple example")
   widget.show()
   sys.exit(app.exec_())

if __name__ == '__main__':
   window()

I generated the following directories to form a bundle:

example.app/
-- Contents/
   -- Info.plist
   -- MacOS/
      -- example

The Info.plist file:

<?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>CFBundleExecutable</key>
    <string>example</string>
</dict>
</plist>

However, while I can execute it by, e.g., double clicking the .app file itself, I could not have it react to 'open file'.

The following apple script wrapper works, but is quite ugly:

on open theDroppedItems
    repeat with a from 1 to length of theDroppedItems
        set theCurrentDroppedItem to item a of theDroppedItems
        set posixfile to (POSIX path of theCurrentDroppedItem)
        # display dialog posixfile
        do shell script "/path/to/python3 /path/to/python3script " & posixfile
    end repeat
end open

It 'converts' open file to a command line argument. Supposedly, Qt could work and Tk as well (l.90), but I could not find a simple example implementing it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文