使用launchctl(OSX)启动Python脚本

2024-04-28 23:47:07 发布

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

我有一个非常简单的测试脚本,我希望我的计算机每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

^{pr2}$

如果我手动运行脚本,它可以正常工作,即在指定的目录中创建一个.txt文件。但是,当我试图从终端启动launchctl时,什么都没有发生。在

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

我做错什么了?在


Tags: 文件pathnametestimport目录txt脚本
1条回答
网友
1楼 · 发布于 2024-04-28 23:47:07

如果不使用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

只需设置执行位:

^{pr2}$

有解释器和执行位:

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$

相关问题 更多 >