如何重定向写入 tty 的程序? [英] How to redirect a program that writes to tty?

查看:21
本文介绍了如何重定向写入 tty 的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是未重定向的输出(如果你不知道module是什么,那也无所谓):

This is the un-redirected output (if you don't know what module is, it doesn't matter much):

$ 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

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

Suppose I'd like to redirect that to a file....

$ 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' -----------------------
$

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

Hey! It is resetting my redirect. This is really annoying, and I have two questions:

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

另见这个相关问题.

有人在评论中询问,所以有些细节.这是在 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,而不是在外部程序中.

somebody asked in a comment, so some details. This is on AIX 5.3 at 64 bits. I have python 2.6.5 almost fully available. I have both gcc 4.1.1 and gcc 4.5.1 but not many libraries to link them against (the util-linux-ng library, which contains the script version mentioned in an answer fails to compile for the getopt part). I also have several version of IBM XL compiler xlc. The reason why I didn't specify in the first place is that I was hoping in some shell tricks, maybe with exec, not in an external program.

推荐答案

我首先回答第二个问题:作为一个设计选择,module 是一个 eval 并且他们采取了(有问题的)选择使用 stderr/tty 而不是stdout/stderr 使他们的设计更容易.请参阅此处.

I'm answering the second question first: as a design choice, module is an eval and they took the (questionable) choice to use stderr/tty instead of stdout/stderr to keep their side of the design easier. See here.

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

My solution, since I couldn't use any of the other recommended tools (e.g. script, expect) is the following python mini-wrapper:

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

这篇关于如何重定向写入 tty 的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆