【问题标题】:Run a bash file with python scripts automatically from a server从服务器自动运行带有 python 脚本的 bash 文件
【发布时间】:2019-12-19 12:11:25
【问题描述】:

我有一个“自动化”文件夹,其中包含处理 Web 自动化任务并提取文本和 Excel 文件的 Python 脚本。这些文本和 Excel 文件临时存储在“自动化”中。

目前我每周从位于同一目录中的 bash 包装文件运行脚本 3 次,但我希望它自动从服务器运行,以便在我运行时执行不使用我的电脑。

您将如何完成这项工作?谢谢

【问题讨论】:

  • 你有jenkines吗?你用什么操作系统?
  • 你试过 crontabs 吗?
  • 如果它只依赖于时间 - 一个 cron 作业。如果还有其他限制,从使用 celery (celeryproject.org) 到编写您自己的 systemd 服务,更多涉及的解决方案(更多花里胡哨)是可能的。
  • 尝试使用谷歌搜索设置 cron 作业,这就是您所需要的。
  • here 是 Luke Smith 关于 cronjobs 的视频。我相信他很好地解释了这些事情。祝你好运。

标签: python server automation


【解决方案1】:

(1) 首先您可以将以下内容放入名为 wrapper.py的文件中:

import time, sys

log, flush = sys.stdout.write, sys.stdout.flush

while True:
    log("I am waking up, let's run the scripts\n")

    # ****************************** #
    # call your python scripts here
    # example:
    # import script1, script2
    # script1.some_function1()
    # script2.some_function2()
    # ****************************** #


    log("Done for today, I will go to sleep for 1/3 a week (56 hours)\n")
    flush()

    #(60 seconds/minute)x(60 minutes/hour)x(24 hours/day) x 3 days = 259200 seconds
    hibernation = 259200 

    time.sleep(hibernation)  # sleep for 3 days = 259200 seconds


(2) 然后要将其作为守护程序启动,请在终端中运行以下命令:

nohup python wrapper.py >> logfile.log 2>&1 &


nohup
“no hangup”,即使在您关闭终端(或退出 shell)后,python 进程也会继续运行

>>
将输出发送到名为 logfile.log 的文件

2>&1
将 stdout 和 stderr 都发送到 logfile.log

&
将正在运行的进程发送到后台,并将 shell 控制权交还给您

请注意,您只运行一次 nohup 命令(除非服务器重新启动,否则您将再次运行它。如果这种情况经常发生,您可以通过将 nohup 命令放入可执行 bash 中来自动重新启动脚本,然后为该脚本创建一个 cron 作业)。

【讨论】:

    【解决方案2】:

    我想你想创建一个文件,在你希望的特定时间启动 bash 文件。我认为这个脚本会帮助你:

    from datetime import datetime
    import os
    # the list below should be supplied with the times when you want to launch your bash script
    times = [ "write times in the format(no whitespaces, only colons): day(lowercase):hour:minutes",  "day(lowercase):hour:minutes"]
    path = r"Path/of/executable/bash/file"      # this is the bash file that runs your other python scripts
    while(True):
        now=datetime.now()
        nowtime=now.strftime("%H:%M")
        today=now.strftime("%A")
        today=today.lower()
        time=today+":"+nowtime   # this line would bring it into the correct format
    
        for eachtime in times:      # These three lines would check if the current time is correct to launch the bash script
            if time = eachtime:
                os.system("cd "+path+"\r\n <command to execute bash>")      # If it is correct then execute the bash file.
    

    您可以启动此脚本并让它永远运行.. 它会在正确的时间自动启动 bash 文件..

    希望能解决你的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      相关资源
      最近更新 更多