在OS X上的后台运行Python [英] Running Python in background on OS X

查看:110
本文介绍了在OS X上的后台运行Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以让我的Python脚本(带有无穷的"while"循环)在OS X的后台运行?另外,出于相同的目的,是否可以在USB驱动器上使用自动运行"的python脚本?

Is there any way to keep my Python script (with an endless 'while' loop) running in the background on OS X? Also, for the same purpose, is there any way to have "autorun" python script on a USB drive?

推荐答案

如果您希望脚本作为自动启动的守护进程运行,则可以使用

If you want to have the script running as a daemon process which starts automatically, you can use launchctl and a plist file.

例如,Bob有一个简单的python脚本,该脚本每秒在其主目录中的文件中写入"foo"一词:

For example, Bob has a simple python script which writes the word 'foo' to a file every second in his home directory:

#!/usr/bin/env python
import os
import time

while True:
  os.system('echo " foo" >> /Users/bob/foostore.txt')
  time.sleep(1)

要使其作为守护进程运行,请创建一个包含以下内容的plist文件~/Library/LaunchAgents/com.bobbob.osx.test.plist:

To have it run as a daemon process, create a plist file, ~/Library/LaunchAgents/com.bobbob.osx.test.plist, with the contents:

<?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.bobbob.osx.test</string>
    <key>Program</key>
    <string>/Users/bob/pyfoo.py</string>
    <key>KeepAlive</key>
    <true/>
  </dict>
</plist>

然后使用launchctl从终端加载plist:

Then use launchctl to load the plist from a terminal:

launchctl load ~/Library/LaunchAgents/com.bobbob.osx.test.plist

这将加载该脚本并立即在<key>Program</key>下的<string>元素中运行程序.您还可以使用带有<string>元素数组的<ProgramArguments>节点为程序指定参数.有关更多信息,请参见

This will load that script and immediately run the program in the <string> element beneath <key>Program</key>. You can also specify arguments for the program using a <ProgramArguments> node with an array of <string> elements. For more information see the launchd.plist man page

如果要删除脚本,可以使用launchctl的卸载命令:

If you want to remove the script, you can use the unload command of launchctl:

launchctl unload ~/Library/LaunchAgents/com.bobbob.osx.test.plist

脚本中使用的标签可以是任何东西,但是在您的系统上应该是唯一的,因此Apple通常使用反向域名.

The Label used in the script can be anything, but it should be unique on your system, so Apple generally uses a reversed domain name.

对于执行脚本的老师来说,我认为没有任何办法.

As for autorunning a script, I don't think there's any way to do that.

这篇关于在OS X上的后台运行Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆