当某个文件发生更改时,如何使用macbook automator自动运行python脚本?

2024-09-30 18:28:15 发布

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

我创建了一个名为recipe\u jsonifier.py的python脚本,它在执行时打开并使用links.txt文件中的数据。目前,每次更新文本文件时,我都必须手动运行python脚本以使用文本文件中的数据。我需要使python脚本在我更改文本文件时自动运行。我没有使用Macbook自动机的经验

  1. 有没有其他方法可以让python脚本在不使用Macbook自动机的情况下自动运行

  2. 如果没有,我需要采取什么步骤才能使其工作

谢谢


Tags: 文件数据方法pytxt脚本自动机recipe
1条回答
网友
1楼 · 发布于 2024-09-30 18:28:15

您可以使用fswatch进行此操作。使用自制软件安装:

brew install fswatch

然后,如果要监视主目录中名为monitored.txt的文件,请编写以下脚本并将其另存为$HOME/monitor.sh

#!/bin/bash
fswatch -x -0 $HOME/monitored.txt | xargs -0 -n 1 -I {} say "I saw that"

然后使用以下命令使其可执行:

chmod +x $HOME/monitor.sh

并运行它以测试:

$HOME/monitor.sh

现在启动一个新终端并运行:

touch $HOME/monitored.txt
touch $HOME/monitored.txt
rm $HOME/monitored.txt

每一个命令都会产生一个单词“我看到了”


一旦你开始工作,你就需要仔细阅读launchctl。基本上,如果您希望它在系统启动后立即监视文件,则需要创建一个“LaunchDaemon”。这将是一个名为以下内容的文件:

/Library/LaunchDaemons/com.YOURNAME.monitor.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>Label</key>
    <string>com.YOURNAME.monitor</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/YOURNAME/monitor.sh</string>
    </array>
    <key>KeepAlive</key>
    <false/>
    <key>RunAtLoad</key>
    <true/>
    <key>WorkingDirectory</key>
    <string>/Users/YOURNAME</string>
    <key>UserName</key>
    <string>YOURNAME</string>
    <key>StandardOutPath</key>
    <string>/tmp/com.YOURNAME.monitor.stdout</string>
    <key>StandardErrorPath</key>
    <string>/tmp/com.YOURNAME.monitor.stderr</string>
</dict>
</plist>

然后阅读{}和{}并测试所有内容

相关问题 更多 >