Create python script that runs at startup [closed]

。_饼干妹妹 提交于 2019-11-29 09:01:48

Question 1 is easy:

How to find out which OS a computer is running on in Python?

That's sys.platform:

if sys.platform.startswith('win') or sys.platform.startswith('cygwin'):
    do_windows_stuff()
elif sys.platform.startswith('darwin'):
    do_osx_stuff()
elif sys.platform.startswith('linux'):
    do_linux_stuff()
else:
    raise Exception("Nobody's written the stuff for {}, sorry".format(sys.platform))

The second part is also easy, but not in the way you wanted to hear:

How to make a script run at startup (Linux, Mac OSX, Windows)

You don't. Not from within the script. You use some kind of installer (or package postflight script, or whatever).

Adding things that run at startup requires root/admin rights. Your script (hopefully) is not running with such rights. Therefore, it can't do it. Yes, it's possible to elevate privileges in various ways, but that almost certainly isn't what you want to do inside a script that's going to end up running at startup.

So, how does your installer do it then?

OS X: You need to create a Launch Daemon, with an accompanying launchd plist. This is described in Creating Launch Daemons and Agents. You shouldn't be trying to do this if you haven't read that article, and you'll already know how if you have read that article, so there's not much else to say.

Windows: The official way to do this is explained in Run and RunOnce Registry Keys. Again, you shouldn't do this without reading this article, and after reading the article it's pretty obvious, except for two things: First, out of the four keys, it's the HKLM Run key. Second, in modern Windows, this doesn't actually run at startup, but at the first login after startup; if that's not acceptable, look into RunServices instead.

Linux: What's an installer? And were you expecting one way to do it for every distro family? This primer gives you most of the information you need, except for knowing exactly what you want to do on each distro. In general, if you just want your script to run once and quit, and there's an rc.local.d, and you just need to drop a link in there. Otherwise, you either need to create an rc.d script, install it to the right place, and run the right chkconfig command, or you need to edit rc.local to run your script. But the simplest thing is: just put English text in the INSTALL file telling people to do it. Eventually, when someone decides to make a DEB for Ubuntu or an RPM for Redhat or whatever, they'll do the right thing for their distro, and either submit a patch to you or maintain it separately.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!