简体   繁体   English

启动时自动运行Python脚本-Ubuntu 16.04

[英]Run Python Script Automatically at Startup - Ubuntu 16.04

I'm on Ubuntu 16.04.1, and I have a python script to download image files from websites, the codes are as follows: 我在Ubuntu 16.04.1上,我有一个python脚本可以从网站下载图像文件,代码如下:

import sys
import os
import time
import json
import shlex, subprocess
import signal
import random

R = 0
r = 0

targets = ['192.0.78.13', '134.109.133.7', '216.58.212.227', '54.246.159.107', '185.60.216.35', '98.136.103.24']

if __name__ == "__main__":
    while True:
        cmd = 'wget -A pdf,jpg,png -m -p -E -k -K -np --delete-after '
        R = random.randint(0,5)
        cmd += targets[R]

        args = shlex.split(cmd)
        p = subprocess.Popen(args, shell=False)

        time.sleep(2.0)
        # killing all processes in the group
        os.kill(p.pid, signal.SIGTERM)
        if p.poll() is None:  # Force kill if process
            os.kill(p.pid, signal.SIGKILL)
        r = random.randint(3,20)
        time.sleep(r-1)

it run perfectly with command "python webaccess.py", now I want to run it automatically on startup in the background. 它可以使用命令“ python webaccess.py”完美运行,现在我想在后台启动时自动运行它。 I've tried two methods but all of them are fail (the scripty does not run): 我尝试了两种方法,但是所有方法都失败了(脚本无法运行):

  1. Use crontab using the guide here: Run Python script at startup in Ubuntu 使用crontab的指南: 在Ubuntu中启动时运行Python脚本

@reboot python /bin/web1.py & @reboot python /bin/web1.py&

  1. Edit the rc.local using the guide here: https://askubuntu.com/questions/817011/run-python-script-on-os-boot 使用此处的指南编辑rc.local: https//askubuntu.com/questions/817011/run-python-script-on-os-boot

python /bin/web1.py & python /bin/web1.py&

Is there any way to solve this? 有什么办法解决这个问题?

Thank you in advance. 先感谢您。

your rc.local method should work, check using your full python path. 您的rc.local方法应该可以使用,请使用完整的python路径进行检查。 if that is default /usr/bin/python /use/bin/python your_file_py 如果是默认的/ usr / bin / python / use / bin / python your_file_py

also you said you verified python webaccess.py do verify it from outside the folder of script. 您还说过,您已验证python webaccess.py确实是从脚本文件夹之外进行验证的。 also note that scrips in rc.local are executed by root so check path_to_python python_file from root # 还请注意,rc.local中的脚本是由root执行的,因此请从root#检查path_to_python python_file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM