如何从 Popen stdout 获取输出类型

How to get output type from Popen stdout

我正在制作自动评分器,但我无法从标准输出中获取 'test_file' 的输出类型, 就像我的 test_file return 整数但标准输出总是字符串 ps。如果我的代码不好或者有更好的方法,请给我建议。

    def check_output(test_file, result_file, in_type, out_type, input):
        if check_type(in_type, input):
            process1 = Popen(["python", test_file], stdin=PIPE, stdout=PIPE, stderr=PIPE)
            process1.stdin.write(str(input).encode())
            stdout = process1.communicate()[0]
            output1 = stdout.decode()
            print("Test: " + output1)
            if check_type(output1, out_type):
                print("YES")
    
    
    def check_type(type1, type2):
        return type(type1) == type(type2)

就像从任何其他类型的文件句柄读取时一样,读取标准输出的唯一可能结果是二进制 bytesstr,当字节被解码时 - 要么因为您在调用 subprocess.Popen() 时使用了 text=True 或其过时的同义词 universal_newlines=True,或者因为您明确地 .decode() bytes,就像您在代码中所做的那样。

您的代码还有其他几个问题。您通常应该尽可能避免使用 Popen;您的代码只是相当笨拙地重新部署 subprocess.check_output() 或其现代替代品 subprocess.run() 。其次,调用 Python 作为 Python 的子进程通常是一种反模式。除非您正在寻求专门测试 Python 的标准输出包含您期望的内容(如上所述,它只能是字节流或字符流),否则您最好做一个 import代码并调用您要测试的函数,在这种情况下,它当然会通过其 return 语句 return 原生 Python 数据类型,如果它是这样定义的。