我有一个用java编写的控制台实用程序,它检查一些远程数据,向用户输出可能的选项,然后等待用户输入选择其中一个选项。该实用程序使用命令行参数来确定要检查的数据以及向用户显示的内容。我希望看到使用不同参数多次运行此实用程序的输出以找到最佳解决方案。如果我手动完成,我的工作流程看起来像这样
./command arg1 arg2
*waits several seconds for the output
*analyses output
*if found the desired option chooses it by typing its value
*else presses ^C and carries on searching
./command args2 arg1
*...
./command arg1 arg3
*...
手动操作很烦人,更改实用程序的源代码是有问题的,因此我想使用Python自动化它
我发现执行shell命令并捕获其输出有几个选项,但我找不到如何注册回调以捕获shell命令开始等待用户输入的时刻
他是我的代码意图
import itertools
some_args = ['ARG1', 'ARG2', 'ARG3']
def execute(comb):
# execute ./command comb[0] comb[1]
# is it possible to have something like this?
# register_on_input_waiting(do_something_with_output)
pass
def do_something_with_output(output):
# TODO: gather all the output, analyze it in code, and present best option to the user
pass
for comb in itertools.combinations(some_args, 2):
comb_rev = comb[::-1]
execute(comb)
execute(comb_rev)
答案 0 :(得分:1)
实际上我找到了一种方法,如何检查程序是否等待输入。然而,它不是平台可压缩的,在我看来,这比工程更加黑客攻击。
在X86 64 Linux系统上,我可以运行:
gdb <my_program>
(gdb) catch syscall read
(gdb) command 1
>if $rdi != 0
>continue
>end
>end
(gdb) run
现在gdb每次都会中断程序,它会尝试从stdin读取。我很确定,gdb有python接口。
注意,这适用于X86 64架构和Linux。其他操作系统可能有不同的系统调用,$ rdi是特定于体系结构的。
答案 1 :(得分:0)
如果您的程序是交互式的,那么自动化它的最佳方法是使用pexpect
(pythons期望实现)。
然后,您可以通过以下方式开始您的流程:
p = pexpect.spawn("...")
如果您知道问题,程序会询问,您可以过滤它们:
pat = [ "Please enter (.+): ", ...]
ind = p.expect(pat)
if ind == 0:
print("User asked for " + p.match.group(1))
一般情况下,当程序需要输入时,无法找到时刻。