文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>转载:Auto Run For Python

转载:Auto Run For Python

时间:2010-03-30  来源:broader

http://29a.ch/2009/3/17/autostart-autorun-with-python

Autostart/Autorun with Python

written by Jonas Wagner, on 10/22/09 10:00 PM.

Some time ago I wrote a little python module to automatically start programs when a user logs in. It works on Windows and Linux. On windows it creates registry entries, on linux it creates *.desktop files as defined in the Desktop Application Autostart Specification. You can use it like this:
import os
import autorun
autorun.add("myapp", os.path.abspath(__file__))
So here's the code:
#!/usr/bin/env python
"""A simple crossplatform autostart helper"""
from __future__ import with_statement

import os
import sys

if sys.platform == 'win32':
import _winreg
_registry = _winreg.ConnectRegistry(None, _winreg.HKEY_CURRENT_USER)
def get_runonce():
return _winreg.OpenKey(_registry,
r"Software\Microsoft\Windows\CurrentVersion\Run", 0,
_winreg.KEY_ALL_ACCESS)

def add(name, application):
"""add a new autostart entry"""
key = get_runonce()
_winreg.SetValueEx(key, name, 0, _winreg.REG_SZ, application)
_winreg.CloseKey(key)

def exists(name):
"""check if an autostart entry exists"""
key = get_runonce()
exists = True
try:
_winreg.QueryValueEx(key, name)
except WindowsError:
exists = False
_winreg.CloseKey(key)
return exists

def remove(name):
"""delete an autostart entry"""
key = get_runonce()
_winreg.DeleteValue(key, name)
_winreg.CloseKey(key)
else:
_xdg_config_home = os.environ.get("XDG_CONFIG_HOME", "~/.config")
_xdg_user_autostart = os.path.join(os.path.expanduser(_xdg_config_home),
"autostart")

def getfilename(name):
"""get the filename of an autostart (.desktop) file"""
return os.path.join(_xdg_user_autostart, name + ".desktop")

def add(name, application):
"""add a new autostart entry"""
desktop_entry = "[Desktop Entry]\n"\
"Name=%s\n"\
"Exec=%s\n"\
"Type=Application\n"\
"Terminal=false\n" % (name, application)
with open(getfilename(name), "w") as f:
f.write(desktop_entry)

def exists(name):
"""check if an autostart entry exists"""
return os.path.exists(getfilename(name))

def remove(name):
"""delete an autostart entry"""
os.unlink(getfilename(name))
def test():
assert not exists("test_xxx")
try:
add("test_xxx", "test")
assert exists("test_xxx")
finally:
remove("test_xxx")
assert not exists("test_xxx")

if __name__ == "__main__":
test()
相关阅读 更多 +
排行榜 更多 +
找茬脑洞的世界安卓版

找茬脑洞的世界安卓版

休闲益智 下载
滑板英雄跑酷2手游

滑板英雄跑酷2手游

休闲益智 下载
披萨对对看下载

披萨对对看下载

休闲益智 下载