【问题标题】:Redirect DOS Output Only if there is Output仅当有输出时才重定向 DOS 输出
【发布时间】:2012-08-14 19:43:48
【问题描述】:

我在 Windows 机器上运行的批处理文件 (.bat) 中有一系列行,例如:

start /b prog.exe cmdparam1 cmdparam2 > test1.txt
start /b prog.exe cmdparam1 cmdparam2 > test2.txt

有时 proj.exe 不返回任何内容(空)而不是有用的数据。在那些情况下,我不想生成文本文件,这在批处理文件方面很容易做到吗?当前的行为是始终创建一个文本文件,在空输出的情况下它只是一个空白文件。

【问题讨论】:

  • 只需[删除所有长度为零的文件][1]。您可以将这些命令与“开始”命令交错。 IE。类似:[1]:stackoverflow.com/questions/4176962/…
  • @jpe - 如果您想完全在 DOS 中处理它,这似乎是唯一可能的答案。您应该将其作为答案发布,以便将其标记为“正确”。
  • Stack Overflow 将我的答案更改为评论,因为它太短了。所以我详细说明了一点:)
  • 澄清一下,通常我会对prog.exe 进行更改,但我没有编写它并且无法访问它的源代码。所以一些 DOS 命令是我所有可用的 atm。

标签: batch-file dos


【解决方案1】:

jpe 解决方案要求您的父批次知道启动的进程何时完成,然后才能检查输出文件的大小。您可以使用 START /WAIT 选项,但您会失去并行运行的优势。

如果另一个进程已经将输出重定向到同一个文件,您可以使用重定向到文件将失败的事实。当您的父批次可以成功重定向到它们时,您就知道启动的进程已全部完成。

您可能应该将标准错误重定向到您的输出文件以及标准输出

@echo off

::start the processes and redirect the output to the ouptut files
start /b "" cmd /c prog.exe cmdparam1 cmdparam2 >test1.txt 2>&1
start /b "" cmd /c prog.exe cmdparam1 cmdparam2 >test2.txt 2>&1

::define the output files (must match the redirections above)
set files="test1.txt" "test2.txt"

:waitUntilFinished 
:: Verify that this parent script can redirect an unused file handle to the
:: output file (append mode). Loop back if the test fails for any output file.
:: Use ping to introduce a delay so that the CPU is not inundated.
>nul 2>nul ping -n 2 ::1
for %%F in (%files%) do (
  9>>%%F (
    rem
  )
) 2>nul || goto :waitUntilFinished

::Delete 0 length output files
for %%F in (%files%) do if %%~zF==0 del %%F

【讨论】:

  • stdin0stdout1stderr2。出于好奇,9>>%%F (9 部分是做什么的?
  • 它是 CMD.EXE 可用的最高编号的未使用文件句柄。文件被创建,发送到该文件句柄的任何输出都将在文件中结束,但在正常情况下当然不会有任何输出。它应该适用于任何文件句柄 1-9,但我只是谨慎行事。
【解决方案2】:

只需delete all files with zero length。编辑:为了适应在等待prog.exe 终止之前返回没有/WAIT 标志的start 的事实,您可以为您的prog.exe 创建以下包装脚本progwrapper.bat

prog.exe "%1" "%2" > "%3"
if %~z3==0 del "%3"

然后从您的主脚本中调用包装器:

start /b progwrapper.bat cmdparam1 cmdparam2 > test1.txt
start /b progwrapper.bat cmdparam1 cmdparam2 > test2.txt

等等

如果 prog.exe 是一个 GUI 应用程序,那么您应该在 progwrapper.bat 中有一个start /B /WAIT prog.exe

【讨论】:

  • 这行得通,唯一的问题是我必须在我的starts 上添加一个/wait 标志,否则我会在它们生成之前尝试删除。
  • @user17753 - 是的,您的父批次必须知道何时检查文件大小。我正在研究一个允许多个程序并行运行并且在所有程序都完成之前不检查大小的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
  • 1970-01-01
相关资源
最近更新 更多