简体   繁体   English

如何将 Python 文件中的内容写入 crontab 文件?

[英]How can I write something into crontab file from Python file?

I try to write from a Python file cronjobs into crontab.我尝试将 Python 文件 cronjobs 写入 crontab。 When calling the Python file which contains the code for writing into crontab from another Python file via sudo I expect that the cronjob gets added to the crontab file but instead I get this error:当调用包含通过 sudo 从另一个 Python 文件写入 crontab 的代码的 Python 文件时,我希望 cronjob 被添加到 crontab 文件中,但我得到了这个错误:

PermissionError: [Errno 1] Operation not permitted: '/usr/bin/crontab'

File 1文件 1

with open('/usr/bin/crontab', 'w') as f2:
    f2.write("Hello World")

File 2文件 2

import os
command = "python3 /Users/myUser/Projects2022/CronjobManager/File1.py"
os.popen("sudo -S %s"%(command), 'w').write('password')

The binary (executable program) for adding cronjobs is stored in /usr/bin/crontab .用于添加 cronjobs 的二进制文件(可执行程序)存储在/usr/bin/crontab中。 That binary actually writes your crontab entries in a file whose location is dependent on your OS.该二进制文件实际上将您的crontab条目写入一个文件,该文件的位置取决于您的操作系统。

On macOS, the file is in /var/at/tabs/USERNAME , on some systems it is in /var/spool/cron/XXX .在 macOS 上,该文件位于/var/at/tabs/USERNAME中,在某些系统中它位于/var/spool/cron/XXX中。

You can, and should, no more overwrite the executable at usr/bin/crontab than you can, or should, overwrite /usr/bin/wc您可以,也不应该覆盖usr/bin/crontab中的可执行文件,就像您可以或不应该覆盖/usr/bin/wc


What I am saying is that you need to differentiate between:我的意思是你需要区分:

  • the program /usr/bin/crontab and程序/usr/bin/crontab
  • the table it writes to in /var/spool/cron/XXX它写入/var/spool/cron/XXX中的表

What you might want to do is:你可能想要做的是:

  • extract the user's current crontab to a temporary file, ie crontab -l > TEMPORARYFILE将用户当前的 crontab 提取到一个临时文件中,即crontab -l > TEMPORARYFILE
  • edit or append to that file编辑或 append 到该文件
  • re-load that file back to the system, ie crontab TEMPORARYFILE将该文件重新加载回系统,即crontab TEMPORARYFILE

There's a good description of the tempfile module here .此处tempfile模块有很好的描述。

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

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