2014-03-12 46 views
4

運行Python腳本,我試圖讓一個Python腳本在啓動時運行。我有以下文件:com.test.service.plist:在Mac啓動

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC -//Apple Computer//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.service</string> 
    <key>ProgramArguments</key> 
    <array> 
     <string>/bin/sh</string> 
     <string>/var/www/html/app/appstart.sh</string> 
    </array> 
    <key>RunAtLoad</key> 
    <true/> 
</dict> 
</plist> 

複製到〜/庫/ LaunchAgents/

加載

launchctl load -w ~/Library/LaunchAgents/com.test.service.plist 

腳本有2行:

/usr/bin/python /var/www/html/app/app.py 
echo "hello" >> /var/www/html/app/test.txt 

腳本運行(文件test.txt被創建爲'hello') 然而,th e app.py不會運行。出於測試目的,我所做的app.py裏面是:

import os 
os.system("echo 'python' >> /var/www/html/app/test.txt") 

,如果我只是運行終端appstart.sh,那麼Python運行沒有問題

我跟着this question說明了,但沒有運氣

+0

爲什麼你'app.py'腳本做同樣的事情bash腳本? – dopatraman

+0

,因爲我不想在這裏粘貼200行代碼,這是一個測試腳本是否運行的非常快速簡單的方法。 – andrei

回答

1

前一段時間我用cron來做到這一點。你可以這樣

@reboot /path/to/my/script

more info about cron

到我的腳本的路徑條目將是路徑到appstart.sh文件。

所以你打開你的終端。

您在crontab -e輸入(這將在默認編輯器中打開一個文件,problably納米)

您向下滾動,並在該文件的底部,你鍵入@reboot /path/to/file

然後保存並退出。

+0

我知道他們建議不要使用cron的蘋果網站,但它似乎是在OS的唯一可靠的任務調度十,謝謝你的回答。 – andrei

1

確保的.plist文件是搭配chmod 644

您提出要「在Mac啓動時運行」和「啓動時運行」,它告訴我,你是在錯誤的目錄。 LaunchAgents用於在用戶登錄時運行腳本。 要在啓動時運行,.plist文件需要位於/ Library/LaunchDaemons中,並由root:wheel擁有。

如果你不需要一個shell啓動一個shell腳本來運行Python那麼我建議一個快捷方式:

<key>ProgramArguments</key> 
<array> 
    <string>/usr/bin/python</string> 
    <string>/var/www/html/app/app.py</string> 
</array> 
+0

在我的情況下,它實際上並不重要,用戶登錄運行是也沒關係,但既不是那些工作對我來說 – andrei