Dav*_*ide 3 bash redirect stderr pty
这是未重定向的输出(如果你不知道是什么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
Run Code Online (Sandbox Code Playgroud)
假设我想将其重定向到文件....
$ 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
$
Run Code Online (Sandbox Code Playgroud)
好吧,它必须在 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' -----------------------
$
Run Code Online (Sandbox Code Playgroud)
嘿! 它正在重置我的重定向.这真烦人,我有两个问题:
另请参阅此相关问题.
编辑:有人在评论中提问,所以有些细节.这是在AIX 5.3上的64位.我有几乎完全可用的python 2.6.5.我有gcc 4.1.1和gcc 4.5.1但没有很多库可以链接它们(util-linux-ng库,其中包含答案中提到的脚本版本无法为getopt部分编译).我还有几个版本的IBM XL编译器xlc.我之前没有说明的原因是我希望有一些shell技巧,可能是exec,而不是外部程序.
试试这个:
script -q -c 'module help null' /dev/null > aaa.txt
Run Code Online (Sandbox Code Playgroud)
这适用于shell脚本(非交互式)使用
$ script --version
script (util-linux-ng 2.16)
Run Code Online (Sandbox Code Playgroud)
您也可以使用expect.
另请参阅:捕获直接重定向到/ dev/tty.
我首先回答第二个问题:作为一种设计选择,模块是一个 eval,他们选择使用 stderr/tty 而不是 stdout/stderr 来让他们的设计更容易。看这里。
由于我无法使用任何其他推荐的工具(例如脚本、expect),我的解决方案是以下 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
Run Code Online (Sandbox Code Playgroud)