在命令行上自动执行只接受交互式参数的可执行文件(在执行时不能指定参数)

问题描述 投票:1回答:1

我有一个可执行文件,我可以从命令行交互运行。以下是它的外观:

C:\Users\Me> my_executable.exe  # Running the executable from CMD

Welcome! Please choose one:
0: Exit
1: Sub-task 1
2: Sub-task 2
Enter your input: 2             # I entered this interactively

Sub-task 2 chosen.
Please choose next option:
0: Return to previous menu
1: Connect to server
2: Disconnect from server
3: Call server API 1
4: Call server API 2
Enter your input: 1             # I entered this interactively

我无法在使用标志之前指定输入参数。例如,这种类型都不起作用:

C:\Users\Me> my_executable.exe 2 # Running the executable from CMD with first argument specified

Sub-task 2 chosen.
Please choose next option:
0: Return to previous menu
1: Connect to server
2: Disconnect from server
3: Call server API 1
4: Call server API 2

Enter your input: 

使用批处理文件自动执行此操作的正确方法是什么?我遇到了类似的要求in this SO thread,但区别在于可执行文件需要命令行参数(与我的情况不同)。

windows batch-file command-line
1个回答
4
投票

假设您的可执行文件读取stdin,并且不直接访问键盘,那么您可以使用重定向或管道来提供完成运行所需的所有响应。

假设你想要你指出的2,1个响应,但是在实现服务器连接之后,exe循环回到第一个菜单。假设你想退出,你还需要跟进0。

要使用重定向,您需要准备一个包含所有必需响应的文本文件,每行一个响应。

@echo off
> response.txt (
  echo 2
  echo 1
  echo 0
)
my_executable.exe < response.txt
del response.txt

或者您可能更喜欢使用FOR循环

@echo off
(for %%A in (2 1 0) do echo %%A) > response.txt
my_executable.exe < response.txt
del response.txt

如果使用管道,则可以避免使用临时文件

@echo off
(
  echo 2
  echo 1
  echo 0
) | my_executable

或者使用FOR循环

@echo off
(for %%A in (2 1 0) do echo %%A) | my_executable
© www.soinside.com 2019 - 2024. All rights reserved.