[英]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:我的意思是你需要区分:
/usr/bin/crontab
and/usr/bin/crontab
和/var/spool/cron/XXX
/var/spool/cron/XXX
中的表What you might want to do is:你可能想要做的是:
crontab -l > TEMPORARYFILE
crontab -l > TEMPORARYFILE
crontab TEMPORARYFILE
crontab TEMPORARYFILE
There's a good description of the tempfile
module here .此处对
tempfile
模块有很好的描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.