【问题标题】:Passing stdin for cpp program using a Python script使用 Python 脚本为 cpp 程序传递标准输入
【发布时间】:2017-09-07 09:02:11
【问题描述】:

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

 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 的代码。

【问题讨论】:

    标签: c++ python-3.x


    【解决方案1】:

    将字符串传递给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)
    

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

    【讨论】:

    • 嘿,非常感谢!有效。除了 python3 想要以这种方式打开文件之外,还有什么特别的原因将文件作为二进制而不是直接字符串打开?
    • 如答案中所述,不(这令人沮丧,因为我们只在这里处理文本)。如果这对您有用,请考虑将答案标记为已接受。
    猜你喜欢
    • 2011-09-02
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多