c++ - 使用 Python 脚本为 cpp 程序传递标准输入

标签 c++ python-3.x

我正在尝试编写一个 python 脚本,它 1)编译一个cpp文件。 2) 读取必须输入到 cpp 文件的文本文件“Input.txt”。 3) 将输出与“Output.txt”文件进行比较,如果所有测试用例都成功通过则打印“通过”,否则打印“失败”。 `

 import subprocess
 from subprocess import PIPE
 from subprocess import Popen
 subprocess.call(["g++", "eg.cpp"])
 inputFile = open("input.txt",'r')
 s = inputFile.readlines()
 for i in s :
     proc = Popen("./a.out", stdin=int(i), stdout=PIPE)
     out = proc.communicate()
     print(out)

`

对于上面的代码,我得到这样的输出,

(b'32769', None)
(b'32767', None)
(b'32768', None)
Traceback (most recent call last):
  File "/home/zanark/PycharmProjects/TestCase/subprocessEg.py", line 23, in <module>
    proc = Popen("./a.out", stdin=int(i), stdout=PIPE)
ValueError: invalid literal for int() with base 10: '\n'

PS :- eg.cpp 包含将“Input.txt”中的数字增加 2 的代码。

最佳答案

改为将字符串传递给 communicate,并以二进制形式打开文件(否则 python 3 不会喜欢它/您必须将字符串编码为 bytes ):

 with open("input.txt",'rb') as input_file:
    for i in input_file:
     print("Feeding {} to program".format(i.decode("ascii").strip())
     proc = Popen("./a.out", stdin=PIPE, stdout=PIPE)
     out,err = proc.communicate(input=i)
     print(out)

也不要将文件的输入转换为整数。将其保留为字符串(不过我怀疑您必须过滤掉空行)

关于c++ - 使用 Python 脚本为 cpp 程序传递标准输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46092169/

相关文章:

python - 通过 Python 节点将字典从 LabVIEW 传递到 Python 脚本

html - 提高 BeautifulSoup 解析速度

python - 打字机-cli : How to use custom data type with typer

c++ - 对角矩阵的特征使用

c++ - 顶点着色器进出?

c++ - LLVM IO 错误 - 写入 bc 文件时出错

c++ - makefile中的多种编译模式

python - 无法在 Windows 中为 Python 3.x 安装 Pillow - 需要 Zlib

python - 如何检测并打印句子中每个元音后面的第一个字母?

c++ - 为什么我的 visual studio .obj 文件比输出的 .exe 文件大?