我试图自动执行用C++编写的交互式命令行工具。process.communicate和getche()失败
启动时,二进制等待字母S,Q或P(状态,退出或暂停)。它采用了非标准的msvcrt函数“getche”获取击键(而不是得到()为例),而无需按下回车键的用户。
我尝试以标准方式与进程进行通信(写入stdin并使用process.communicate []),但它没有得到输入。尝试不同的事情了几个小时后,我创建了两个小样本项目在Visual Studio中复制的问题,并确保我理智(ISH)。
这是用来调用二进制的python脚本:
import subprocess
import time
cmd = ["test-getch.exe"]
process = subprocess.Popen(cmd, stderr = subprocess.PIPE, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
i = process.stdin
#msvcrt.ungetch('s')
i.write("S\n")
print process.communicate()[0]
i.close()
time.sleep(3)
print "DONE"
这是两个二进制文件。这第一个我可以与之通信:
#include "stdafx.h"
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
char response [2];
printf("Enter \"s\":\n");
gets(response);
printf("You entered %s", response);
return 0;
}
这一次,我不能沟通:
#include "stdafx.h"
#include <conio.h>
int _tmain(int argc, _TCHAR* argv[])
{
int response;
printf("Enter \"a\":\n");
response = getche();
printf("You entered %c", response);
return 0;
}
看来,getche()不标准输入听,可能监听某种键盘事件。任何人都知道如何处理这个问题?
编辑: 我还应该提到我发现了使用IDA Pro捕获输入的方法。我没有写我尝试自动化的原始二进制文件。它是一个封闭的源代码工具,所以我没有办法重新编写它如何接受输入而不修补二进制文件。
我实际上选择了一个相当疯狂的解决方案......我知道pydbg相当不错,它似乎附加到过程并通过过程工具调用我需要的功能。这完全是过分的,但我可以在之后脱离这个过程。并让它正常运行。
[1] Pydbg:http://pedram.redhive.com/PyDbg/docs/
使用'process.communicate( “S \ n” 个)的''代替i.write()'。如果使用'.communicate()',请不要触摸'process.stdin'。虽然它不会帮助你的情况。 – jfs