在不使用stdin管道的情况下向Python子进程发送击键
我有一个Windows命令行应用程序,它将输出打印到stdout,然后无限期地等待击键结束。我使用这样的函数来处理它:在不使用stdin管道的情况下向Python子进程发送击键,python,python-2.7,subprocess,Python,Python 2.7,Subprocess,我有一个Windows命令行应用程序,它将输出打印到stdout,然后无限期地等待击键结束。我使用这样的函数来处理它: def run_command_on_windows(command): """ Run commandline program on Windows OS (current) :param command: command to run (string) :return: returns result of command """
def run_command_on_windows(command):
"""
Run commandline program on Windows OS (current)
:param command: command to run (string)
:return: returns result of command
"""
p = subprocess.Popen(['c:\\windows\\system32\\cmd.exe', '/c'] + command.split(),
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate()
p.stdin.write('\n\n')
rc = p.returncode
return output.split('\r\n')
如果我能在Popen中使用'stdin=subprocess.PIPE',一切都会很容易,但我不能,因为当我像那样重定向stdin时,应用程序会立即崩溃
p.stdin.write('\n\n')
不工作,与AttributeError崩溃
有没有办法解决这个问题?编写一个CMD脚本,并通过I/O重定向调用其中的命令。尝试
echo |……
使命令结束
您还可以尝试关闭stdin,以便命令不能等待按键:…<数字:
如果不起作用,请在文件中写一个换行符并使用…<文件
如果这也不起作用,您将不得不更改程序的源代码(它可能使用一些特殊的代码来读取键盘)或使用
p.terminate()
终止。如果试图重定向stdin,程序将崩溃,