将输出重定向到 Windows 中另一个命令的命令行参数 [英] Redirecting output to a command-line argument of another command in Windows
问题描述
我如何在 Windows 中使用脚本/命令的输出作为另一个脚本的参数?(管道 | 在这里不起作用,因为其他脚本不会从标准输入中读取)
How can I, in Windows, use the output of a script/command as an argument for another script? (A pipe | will not work here, since that other script doesn't read from the standard input)
太清楚了:我有需要参数 arg 的另一个脚本,例如:
Too clarify: I have AnotherScript that needs an argument arg, e.g.:
AnotherScript 12
现在我希望参数(示例中为 12)来自脚本的输出,称为 ScriptB.所以我想要一些类似
now I want the argument (12 in the example) to come from the output of a script, call it ScriptB. So I would like something along the lines of
AnotherScript (ScriptB)
AnotherScript 实际上是一个需要参数的 python 脚本,而 ScriptB 是一个产生一些数字的 cygwin bash 脚本,所以我想使用它的方式是这样的:
The AnotherScript is actually a python script that requires an argument, and ScriptB is a cygwin bash script that produces some number, so the way I would like to use it is something like:
c:\Python26\python.exe AnotherScript (c:\cygwin|bin|bash --login -i ./ScriptB)
感谢您的回答.但是,考虑到需要费力的for"构造,我重写了 AnotherScript 以从标准输入中读取.这似乎是一个更好的解决方案.
Thanks for the answers. However, given the laborious 'for' construct required, I've rewritten AnotherScript to read from the standard input. That seems like a better solution.
推荐答案
注意:所有这些都要求命令位于批处理文件中.因此双 %
符号.
Note: All this requires the commands to be in a batch file. Hence the double %
signs.
您可以使用 for
命令来捕获命令的输出:
You can use the for
command to capture the output of the command:
for /f "usebackq delims=" %%x in (`ScriptB`) do set args=%%x
然后您可以在另一个命令中使用该输出:
then you can use that output in another command:
AnotherScript %args%
这将导致 %args%
包含来自 ScriptB
输出的最后一行.如果它只返回一行,您可以将其合并为一行:
This will cause %args%
to contain the last line from ScriptB
's output, though. If it only returns a single line you can roll this into one line:
for /f "usebackq delims=" %%x in (`ScriptB`) do AnotherScript %%x
在批处理文件之外使用时,您必须使用 %x
而不是 %%x
.
When used outside a batch file you have to use %x
instead of %%x
.
然而,如果 ScriptB
返回多行,AnotherScript
会为每一行运行.您可以通过在第一次循环迭代后中断来规避这一点——尽管只能在批处理文件中进行:
However, if ScriptB
returns more than one line, AnotherScript
runs for each of those lines. You can circumvent this—though only within a batch file—by breaking after the first loop iteration:
for /f "usebackq delims=" %%x in (`ScriptB`) do AnotherScript %%x & goto :eof
这篇关于将输出重定向到 Windows 中另一个命令的命令行参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!