無為閣

為無為,事無事

How-to: 輸出已被redirect 到時, 想要把字串印到Terminal

最近在寫lp-cli時, 因為stdout已經用來傳遞pickle data到下一個command, 例子如下

# 找出ossug-hychen' 正在處理幾個bug
$ lp-searchbugs people ossug-hychen --status 'In Progress' | lp-print count

所以如果我想要print 一些資訊到terminal 其實是辦不的, 昨日在H4時與Thinker討論時, 他提出了一個辦法

如果要在輸出已被redirect 到時, 想要把字串印到Terminal,可以把訊息寫到 /dev/tty (等於目前的 control terminal)

1
2
3
4
5
6
7
        # Use TTY for print information or debugging message
        # Use STDOUT for printing MissionMessage
        self.tty_fd = os.open('/dev/tty', os.O_WRONLY)
          self.bk_stdout = os.dup(sys.stdout.fileno())
        os.close(sys.stdout.fileno())
        os.dup(self.tty_fd)
        self.bk_stdout = os.fdopen(self.bk_stdout, 'w')

但是這方法仍有缺點:

  1. stdout 沒辦法被rederiect,
  2. 不能用cron, 因為cron沒有tty

Comments