【问题标题】:python script to add specified file to crontabpython脚本将指定文件添加到crontab
【发布时间】:2021-12-29 18:17:38
【问题描述】:

我想创建自动将指定文件添加到树莓派上的 crontab 的 python 脚本。
这些方面的东西:
(shurley 我的命令不起作用,这只是我希望它如何工作的提示)

file = "/home/pi/test/python_script.py &"
def add_to_crontab(file):
   system("echo @reboot python {} >> crontab -e".format(file))

【问题讨论】:

    标签: python cron


    【解决方案1】:

    >> 用于重定向到文件,而不是命令。使用| 传递到命令。

    crontab -e 用于交互式编辑 crontab。要自动编辑它,您需要将当前 crontab 提取到文件中,将新行附加到文件中,然后从该文件更新 crontab。

    from tempfile import NamedTemporaryFile
    import os
    
    def add_to_crontab(file):
        with os.popen("crontab -l", "r") as pipe:
            current = pipe.read()
        current += f"@reboot python {file}\n"
        with NamedTemporaryFile("w") as f:
            f.write(current)
            f.flush()
            system(f"crontab {f.name}")
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 2017-07-01
      • 2018-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多