Search code examples
pythoncron

python script to add specified file to crontab


I want to create python script that automatically adds specified file to crontab on raspberry pi.
Something along these lines:
(shurley my command doesn't work, it's just a hint on how i want it to work)

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

Solution

  • >> is for redirecting to a file, not a command. Use | to pipe to a command.

    crontab -e is for editing the crontab interactively. To edit it automatically, you need to extract the current crontab to a file, append the new line to the file, then update the crontab from that file.

    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}")