在 Ubuntu 中启动时运行 Python 脚本 [英] Run Python script at startup in Ubuntu
问题描述
我有一个需要在启动时运行的简短 Python 脚本 - Ubuntu 13.10.我已经尝试了我能想到的一切,但无法让它运行.脚本:
I have a short Python script that needs to run at startup - Ubuntu 13.10. I have tried everything I can think of but can't get it to run. The script:
#!/usr/bin/python
import time
with open("/home/username/Desktop/startup.txt", 'a') as f:
f.write(str(time.time()) + " It worked!")
(实际脚本有点不同,因为我只是将其用于测试目的,但您明白了.)
(The actual script is a bit different, as I'm just using this for testing purposes, but you get the idea.)
我已经尝试了以下所有方法,但没有成功:
I've tried all of the following, with no luck:
将命令
python startuptest.py
放在crontab
中,作为@rebootpython/home/username/Documents/startuptest.py
,作为普通用户和sudo
Put the command
python startuptest.py
incrontab
, as@reboot python /home/username/Documents/startuptest.py
, both as the regular user and assudo
将命令 python/home/username/Documents/startuptest.py
放在 /etc/rc.local
打开 Ubuntu 的启动应用程序并将命令放在那里
Opened Ubuntu's Startup Applications and put the command there
完成上述所有操作,将命令放入shell脚本中并改为调用该 shell 脚本
Done all of the preceding, putting the command into a shell script and calling that shell script instead
没有任何效果.我觉得我错过了一些简单的东西.有任何想法吗?(如果我只是从终端运行命令,脚本运行良好.)
Nothing works. I get the feeling I'm missing something simple. Any ideas? (The script runs fine if I just run the command from a terminal.)
推荐答案
说明
将python文件复制到/bin:
Instructions
Copy the python file to /bin:
sudo cp -i/path/to/your_script.py/bin
添加新的 Cron 作业:
Add A New Cron Job:
sudo crontab -e
滚动到底部并添加以下行(在所有
#'s
之后):Scroll to the bottom and add the following line (after all the
#'s
):@reboot python/bin/your_script.py &
&"行尾表示该命令在后台运行,不会停止系统启动.
The "&" at the end of the line means the command is run in the background and it won’t stop the system booting up.
测试一下:
sudo reboot
将此文件添加到您的桌面:test_code.py(运行它以检查它是否适合您)
Add this file to your Desktop: test_code.py (run it to check that it works for you)
from os.path import expanduser import datetime file = open(expanduser("~") + '/Desktop/HERE.txt', 'w') file.write("It worked! " + str(datetime.datetime.now())) file.close()
运行以下命令:
Run the following commands:
sudo cp -i ~/Desktop/test_code.py/bin
sudo crontab -e
添加以下行并保存:
@reboot python/bin/test_code.py &
现在重新启动您的计算机,您应该会在桌面上找到一个新文件:
HERE.txt
Now reboot your computer and you should find a new file on your Desktop:
HERE.txt
这篇关于在 Ubuntu 中启动时运行 Python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!