我创建了一个名为recipe_jsonifier.py的python脚本,该脚本会在执行时打开并使用links.txt文件中的数据。当前,每次我更新文本文件时,都必须手动运行python脚本以使用文本文件中的数据。我需要这样做,以便每当我对文本文件进行更改时,python脚本都会自动运行。我没有使用Macbook Automator的经验。
还有其他方法可以使python脚本在不使用Macbook自动器的情况下自动运行吗?
如果没有,我需要采取什么步骤才能使其正常工作?
谢谢!
您可以使用fswatch
。用homebrew:
brew install fswatch
然后,如果要监视HOME目录中名为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>
然后读取launchctl load
和launchctl start
并进行全部测试。