[关闭]
@JaySon 2017-04-16T15:27:34.000000Z 字数 1317 阅读 3431

Linux 输入输出重定向 && 定时任务crontab

Blog Linux


输入输出重定向

写程序的时候, 一般都会遇到 stdin, stdout, stderr 三个默认文件描述符(file descriptor).

名称 类型 文件描述符 操作
stdin 标准输入 standard input 0 <,<<
stdout 标准输出 standard output 1 >,>>
stderr 标准错误输出 standard error output 2 2>,2>>

平时运行小型的程序, 都通过直接打印到屏幕上看输出就好, 但是在下面两种状况, 通常都会需要用到输出重定向
* 输出很多的时候, 特别是在debug的时候, 通过重定向到文件, 然后对log进行搜索
* 配置好定时任务运行, 当想查看定时任务的运行日志的时候, 查看脚本的运行状况

下面是一段用于测试的Python程序

  1. ~ > cat test.py
  2. #!/usr/bin/env python
  3. #encoding=utf-8
  4. from __future__ import print_function
  5. import sys
  6. if __name__ == '__main__':
  7. print("Output to stdout")
  8. print("Output to stderr", file=sys.stderr)
  1. # 把stdout重定向
  2. python test.py > test.log
  3. # 把stderr绑定到stdout中
  4. python test.py > test.log 2>&1
  5. # 与上一个命令同样效果
  6. python test.py &> test.log
  7. # stdout重定向到 /dev/null (Linux下特殊的"黑洞"设备描述符, 相当于抛弃所有stdout输出)
  8. python test.py > /dev/null

定时任务crontab

文件内容格式

crontab文件每一行的格式:M H D m d cmd
M: 分钟(0-59)。
H:小时(0-23)。
D:天(1-31)。
m: 月(1-12)。
d: 一星期内的天(0~6,0为星期天)。
cmd要运行的程序,程序被送入sh执行,这个shell只有USER,HOME,SHELL这三个环境变量

命令

crontab -e : 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数
来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
crontab -r : 删除目前的crontab !!!慎用!!!
crontab -l : 列出目前的crontab内容

注: crontab -r这一命令比较坑爹, r在e旁边, 一个不小心可能会按错吧crontab清空, (曾经不小心按错导致清空了服务器上的crontab, 一个晚上都在找crontab的备份来进行还原)在编辑crontab时谨慎一些.
目前我编辑crontabb之前, 都先使用crontab -l先把当前的crontab打印到标准输出, 然后再编辑, 这样即使编辑错了, 还能根据打印到屏幕的内容来进行恢复

定时任务example

一般运行定时任务, 还会把脚本的log记录下来, 后面好回溯定时任务执行得是否正确, 一般写成下面的形式

  1. 0 1 * * * /path/to/script &> /path/to/script/log &
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注