如何通过 cron 中的 python 脚本写入文件
how to write to a file via a python script in cron
我尝试使用 cron 每分钟写入一个文件,这是我的脚本:
#!/usr/bin/env python
from datetime import datetime
with open('test.txt', 'a') as f:
a = 'date {!s}'.format(datetime.now())
print a
f.write('date {!s} \n'.format(datetime.now()))
print 'done'
然后我做了
chmod +x /tmp/test.py
然后我为 root 添加了 cron
sudo crontab -e
进入 cron
*/1 * * * * /tmp/test.py
在 postfix 中我每分钟都会看到这个,表明脚本 运行 没有错误
From root@tawanda.robot Wed Apr 15 22:56:01 2015
Return-Path: <root@tawanda.robot>
X-Original-To: root
Delivered-To: root@tawanda.robot
Received: by tawanda-lx2 (Postfix, from userid 0)
id 48CA79A13DF; Wed, 15 Apr 2015 22:56:01 +0200 (SAST)
From: root@tawanda.robot (Cron Daemon)
To: root@tawanda.robot
Subject: Cron <root@tawanda-lx2> /tmp/test.py
Content-Type: text/plain; charset=ANSI_X3.4-1968
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
Message-Id: <20150415205601.48CA79A13DF@lx2>
Date: Wed, 15 Apr 2015 22:56:01 +0200 (SAST)
date 2015-04-15 22:56:01.246885
done
但是如果我打开 /tmp/test.txt
它是空的,如果我手动 运行 test.py
它会按预期写入文件
我该如何解开这个谜团
您在哪里搜索 test.txt
?因为您以 root 用户身份添加脚本 test.txt
应该出现在 /root
目录(用户主目录)中。
我尝试使用 cron 每分钟写入一个文件,这是我的脚本:
#!/usr/bin/env python
from datetime import datetime
with open('test.txt', 'a') as f:
a = 'date {!s}'.format(datetime.now())
print a
f.write('date {!s} \n'.format(datetime.now()))
print 'done'
然后我做了
chmod +x /tmp/test.py
然后我为 root 添加了 cron
sudo crontab -e
进入 cron
*/1 * * * * /tmp/test.py
在 postfix 中我每分钟都会看到这个,表明脚本 运行 没有错误
From root@tawanda.robot Wed Apr 15 22:56:01 2015
Return-Path: <root@tawanda.robot>
X-Original-To: root
Delivered-To: root@tawanda.robot
Received: by tawanda-lx2 (Postfix, from userid 0)
id 48CA79A13DF; Wed, 15 Apr 2015 22:56:01 +0200 (SAST)
From: root@tawanda.robot (Cron Daemon)
To: root@tawanda.robot
Subject: Cron <root@tawanda-lx2> /tmp/test.py
Content-Type: text/plain; charset=ANSI_X3.4-1968
X-Cron-Env: <SHELL=/bin/sh>
X-Cron-Env: <HOME=/root>
X-Cron-Env: <PATH=/usr/bin:/bin>
X-Cron-Env: <LOGNAME=root>
Message-Id: <20150415205601.48CA79A13DF@lx2>
Date: Wed, 15 Apr 2015 22:56:01 +0200 (SAST)
date 2015-04-15 22:56:01.246885
done
但是如果我打开 /tmp/test.txt
它是空的,如果我手动 运行 test.py
它会按预期写入文件
我该如何解开这个谜团
您在哪里搜索 test.txt
?因为您以 root 用户身份添加脚本 test.txt
应该出现在 /root
目录(用户主目录)中。