简体   繁体   English

在Mac启动上运行python脚本

[英]running a python script on Mac boot

I'm trying to get a python script to run on startup. 我正在尝试在启动时运行python脚本。 I have the following file: com.test.service.plist : 我有以下文件:com.test.service.plist:

<?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>

copied to ~/Library/LaunchAgents/ 复制到〜/ Library / LaunchAgents /

loaded as 加载为

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

the script has 2 lines: 该脚本有两行:

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

the script runs (the file test.txt gets created with 'hello' in it) however, the app.py doesn't run. 脚本运行(文件test.txt在其中创建'hello')但是,app.py不运行。 for testing purposes, all i did inside the app.py was: 出于测试目的,我在app.py中所做的就是:

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

if i just run the appstart.sh in terminal, then python runs no problem 如果我只是在终端中运行appstart.sh,那么python运行没有问题

i followed instructions in this question already, but no luck 我已经按照这个问题的说明,但没有运气

Make sure the .plist file is chmod 644. 确保.plist文件是chmod 644。

You asked for "run on Mac boot" and "run on startup" which tells me you are in the wrong directory. 您要求“在Mac启动时运行”和“在启动时运行”,它告诉我您在错误的目录中。 LaunchAgents is for running scripts on user login. LaunchAgents用于在用户登录时运行脚本。 To run on startup the .plist file needs to be in /Library/LaunchDaemons and owned by root:wheel. 要在启动时运行,.plist文件需要位于/ Library / LaunchDaemons中并由root:wheel拥有。

If you don't need a shell to launch a shell script to launch python then I recommend a shortcut: 如果你不需要shell来启动shell脚本来启动python,那么我推荐一个快捷方式:

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

Some time ago I used cron to do just that. 前段时间我用cron来做到这一点。 You can make an entry like this 你可以这样做一个条目

@reboot /path/to/my/script

more info about cron 有关cron的更多信息

The path to my script will be the path to your appstart.sh file. 我的脚本的路径将是appstart.sh文件的路径。

So you open your terminal. 所以你打开你的终端。

You type in crontab -e (this will open a file in your default editor, problably nano) 你输入crontab -e (这将在你的默认编辑器中打开一个文件,problably nano)

You scroll down and on the bottom of the file you type @reboot /path/to/file 向下滚动并在文件的底部键入@reboot /path/to/file

Then you save and exit. 然后保存并退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM