【问题标题】:Start Python scripts with launchctl (OSX)使用 launchctl (OSX) 启动 Python 脚本
【发布时间】:2016-02-08 15:33:03
【问题描述】:

我有一个非常简单的测试脚本,我希望我的计算机每 60 秒运行一次 - time_test_script.py。该脚本只是保存一个.txt 文件,名称为当前时间,并将一些文本写入文件。该文件位于/Users/me/Documents/Python 目录中。

import datetime
import os.path
path = '/Users/me/Desktop/test_dir'
name_of_file = '%s' %datetime.datetime.now()
completeName = os.path.join(path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = 'test'
file1.write(toFile)
file1.close()
print datetime.datetime.now()

我还有一个.plist 文件——test.plist 位于/Library/LaunchAgents 目录中。

test.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.test</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/me/Documents/Python/time_test_script.py</string>
    </array>
    <key>StartInterval</key>
    <integer>60</integer>
</dict>
</plist>

如果我手动运行脚本,它可以正常工作,即在指定目录中创建一个.txt 文件。但是,当我尝试从终端启动 launchctl 时,没有任何反应。

 $ launchctl load /Library/LaunchAgents/test.plist 
 $ launchctl start com.test

我做错了什么?

【问题讨论】:

    标签: python macos terminal launchctl


    【解决方案1】:

    如果您在不使用python scriptname.py 的情况下运行脚本,则需要将脚本标记为可执行(来自命令行的chmod a+x scriptname.py)并且第一行应该告诉系统使用哪个解释器,在这种情况下将是#!/usr/bin/python

    例如:

    Sapphist:~ zoe$ cat >test.py
    print "Hello World"
    Sapphist:~ zoe$ ./test.py
    -bash: ./test.py: Permission denied
    

    只设置执行位:

    Sapphist:~ zoe$ cat >test.py
    print "Hello World"
    
    Sapphist:~ zoe$ chmod a+x test.py
    Sapphist:~ zoe$ ./test.py
    ./test.py: line 1: print: command not found
    

    同时使用解释器和执行位:

    Sapphist:~ zoe$ cat >test.py
    #!/usr/bin/python
    print "Hello World!"
    
    Sapphist:~ zoe$ chmod a+x test.py
    Sapphist:~ zoe$ ./test.py
    Hello World!
    Sapphist:~ zoe$
    

    【讨论】:

      猜你喜欢
      • 2013-06-09
      • 1970-01-01
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多