TCL 脚本 - exec 将文本刷新到我的标准输出 [英] TCL script - exec flush the text to my stdout

查看:113
本文介绍了TCL 脚本 - exec 将文本刷新到我的标准输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不等待"结果 exec 返回的情况下将 exec 命令的 stdout刷新"到我脚本的 stdout?

How can I "flush" the stdout of the exec command to my script's stdout without "waiting" for the resulting exec to return?

例如在以下脚本中,我希望 git clone 输出立即出现在我的脚本上下文中:

For instance in the following script I would like the git clone output to appear immediately in my script context:

#!/usr/bin/tclsh

# git outputs progress of the clone download but it isn't visible in this script's context. How can I flush it? 
exec git clone /path/to/some/repo.git

我猜我需要某种 pipe "|"tee 和文件重定向的组合.似乎无法正确处理.

I'm guessing I need some sort of combination of pipe "|" and tee and file redirection. Can't seem to get it right.

推荐答案

要立即获得输出,您需要将子命令作为管道打开.正确的(而不是非常显而易见的,对此我们深表歉意)方法是使用 open |[list ...] 的这种结构:

To get the output immediately, you need to open the subcommand as a pipeline. The correct (and not quite obvious, for which we apologise) way to do that is with this construction of open |[list …]:

set mypipeline [open |[list git clone /path/to/some/repo.git]]

# Now to read it by line; we'll just print it out with a line number to show off
set linenum 0
while {[gets $mypipeline line] >= 0} {
    puts "Line [incr linenum]: $line"
}

# Close the pipe now we're at EOF
close $mypipeline

但是请注意,某些程序(我不知道 git 是否是其中之一)在管道中运行时会改变它们的行为,缓冲它们的输出直到它们具有完整的缓冲区值.(当输出不是到终端时,这是默认情况下 C 运行时工作方式的一部分.)如果这是一个问题,您将不得不使用 Expect 运行.这是一个足够大的主题,您应该寻找(并在必要时询问)一个单独的问题;唉,这在复杂性上是一个很大的变化.

Be aware however that some programs (I don't know if git is one) change their behaviour when run in a pipeline, buffering their output until they have a full buffer's worth. (It's part of how the C runtime works by default when output isn't to a terminal.) If that's a problem, you will have to run using Expect. That's a large enough topic that you should look for (and ask if necessary) a separate question; it's quite a step change in complexity, alas.

另请注意,git 可能会写入其标准错误(如本问题所述,从 PHP exec() 函数读取 git push 的输出),因此您可能需要将标准错误合并到捕获的标准输出中(如 exec 手册页).

Also be aware that git might well write to its standard error (as noted in this question, Reading output of git push from PHP exec() function) so you might need to merge standard error into the captured standard out (as tersely documented on the exec manual page).

set output [exec git clone /path/to/some/repo.git 2>@1]

set mypipeline [open |[list git clone /path/to/some/repo.git 2>@1]]
# ...

也可以做读/写管道,但更复杂.

It's possible to do read/write pipes as well, but rather more complex.

这篇关于TCL 脚本 - exec 将文本刷新到我的标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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