【问题标题】:How to redirect a program that writes to tty?如何重定向写入 tty 的程序?
【发布时间】:2010-10-29 21:36:17
【问题描述】:

这是未重定向的输出(如果你不知道module 是什么,那没关系):

$ module help null

----------- Module Specific Help for 'null' -----------------------

        This module does absolutely nothing.
        It's meant simply as a place holder in your
        dot file initialization.

        Version 3.2.6

假设我想将它重定向到一个文件......

$ module help null > aaa.txt 

----------- Module Specific Help for 'null' -----------------------

        This module does absolutely nothing.
        It's meant simply as a place holder in your
        dot file initialization.

        Version 3.2.6

$ cat aaa.txt
$

嗯,一定是stderr

$ module help null 2> aaa.txt 
        This module does absolutely nothing.
        It's meant simply as a place holder in your
        dot file initialization.

        Version 3.2.6

$ cat aaa.txt 

----------- Module Specific Help for 'null' -----------------------
$

嘿!它正在重置我的重定向。这真的很烦人,我有两个问题:

  1. 如何实现我想要的,即将所有内容重定向到我的文件中
  2. 他们为什么要做这么奇怪的事情?

另请参阅this 相关问题。

编辑:有人在评论中询问,所以有些细节。这是在 64 位的 AIX 5.3 上。我的 python 2.6.5 几乎完全可用。我同时拥有 gcc 4.1.1 和 gcc 4.5.1,但链接它们的库并不多(util-linux-ng 库,其中包含答案中提到的脚本版本,无法为 getopt 部分编译)。我也有几个版本的 IBM XL 编译器 xlc。 我一开始没有指定的原因是我希望在一些 shell 技巧中,可能使用 exec,而不是在外部程序中。

【问题讨论】:

    标签: bash redirect stderr pty


    【解决方案1】:

    试试这个:

    script -q -c 'module help null' /dev/null > aaa.txt
    

    这适用于使用

    的 shell 脚本(非交互式)
    $ script --version
    script (util-linux-ng 2.16)
    

    您也可以使用expect

    另见:Catching a direct redirect to /dev/tty

    【讨论】:

      【解决方案2】:

      我首先回答第二个问题:作为一种设计选择,模块是一个评估,他们选择了(有问题的)选择使用 stderr/tty 而不是 stdout/stderr 以使他们的设计更容易。见here

      我的解决方案,因为我不能使用任何其他推荐的工具(例如脚本,期望)是以下 python 迷你包装器:

      import pty, os
      
      pid, fd = pty.fork()
      if pid == 0: # In the child process execute another command
          os.execv('./my-progr', [''])
          print "Execv never returns :-)"
      else:
          while True:
              try:
                  print os.read(fd,65536),
              except OSError:
                  break
      

      【讨论】:

        【解决方案3】:

        看起来module 正在写入/dev/tty,它始终是与进程关联的控制台。如果是这样,那么我认为您对此无能为力。通常,这样做是为了保证该人看到消息(假设程序是交互式调用的)。

        【讨论】:

        • 好吧,问题是程序没有以交互方式调用。 script 是一种可行的解决方法,但(至少我拥有的版本)只能交互地工作
        • 我的建议是获取支持 -c 的脚本版本。
        • 不幸的是,在这个平台 (AIX) 上这并不容易。我正在尝试,但我想这将是太多的努力。调查期望也。
        • 那么你应该在你的问题中指定你的限制。例如,你能编译 C 代码吗?你有 Python 吗?
        猜你喜欢
        • 2017-02-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多