【问题标题】:python: communication with console programpython:与控制台程序的通信
【发布时间】:2020-12-11 15:51:29
【问题描述】:

我有控制台程序(.exe),基本上是无限循环:

  1. 接受特殊格式的字符串输入(包含换行符)
  2. 以特殊格式打印字符串输出(包含换行符)

具体来说,控制台程序代码如下所示:

1) read integers n, m

2) n times do:

 1. reak integer k
 2. read k integers

3) m times do:

 1. read integer k
 2. read k integers

4)do whatever

5)cout n x m characters which are in ('?', '.', 'X')

6) go to (1)

这是我手动运行时的样子:

我想让 python 程序与之交互,但它不起作用,并且做出了非常奇怪的事情。

这就是我什至尝试进行 1 个输入并获取 1 个输出的方法。

import subprocess

process = subprocess.Popen("Program.exe", encoding='utf-8', stdin=subprocess.PIPE)
with open('test.txt', 'r') as file:
    test = file.read()
test = test + '\n'
print(solver.communicate(input=test))
solver.kill()

这是结果(输出是正常的,直到它开始那个奇怪的无限循环):

size:

20 rows. First quantity, then quantity of numbers:

20 columns. First quantity, then quantity of numbers:
.....XXXXX..........
.......XXXX.........
...XXX...XXX........
.XXXXXXX..XX........
.XXXXXXXX.XX........
XX.....XXX.XXXXX....
........XXXXXXXXXX..
....XXXXXXXXX.XXXXX.
...XXXXXXXXXXX..XXX.
..XXX...XXX.XXX..XXX
..XX...XXXXX.XXX..XX
..XX...XX..XXXXX..X.
...X..XX...XX.XXX...
......XX..XXX.XXX...
.....XXX..XX...XX...
.....XX..XX...XX....
.....XX.......X.....
....XXX.............
....XXX.............
....XXX.............

size: 
20 rows. First quantity, then quantity of numbers:

20 columns. First quantity, then quantity of numbers:
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????
????????????????????

size: 
20 rows. First quantity, then quantity of numbers:

20 columns. First quantity, then quantity of numbers:
????????????????????
.
and it repeats infinitely
.

问号表示有一些输入,从任何地方都需要 20 20,但我不明白它来自哪里。

我想要的是向控制台程序发送一个字符串并读回一个字符串的可靠方法。

【问题讨论】:

    标签: python-3.x io console-application


    【解决方案1】:

    我删除了控制台程序中的提示输出,它变得像不使用通信一样简单。结果如下:

    import subprocess
    
    process = subprocess.Popen("Program.exe", encoding='utf-8', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    with open('test.txt', 'r') as file:
        test = file.read()
    test = test + '\n'
    process.stdin.write(test)
    process.stdin.flush()
    ans = ""
    for line in process.stdout:
        ans = ans + process.stdout.readline()
    print(ans)
    solver.kill()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-10
      • 2022-07-07
      • 2010-12-20
      • 1970-01-01
      • 2010-11-04
      • 2013-09-08
      • 1970-01-01
      • 2010-11-20
      相关资源
      最近更新 更多