Search code examples
pythontypessubprocessstdoutpopen

How to get output type from Popen stdout


Am making auto-grader and i cant get output type of 'test_file' from stdout, Like my test_file return integer but stdout always as string ps. If my code is not good or there is a better way, please suggest me.

    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)

Solution

  • Just like when reading from any other type of file handle, the only possible result from reading standard output is either binary bytes, or a str, when the bytes are being decoded - either because you used text=True or its obsolescent synonym universal_newlines=True when invoking subprocess.Popen(), or because you explictily .decode() the bytes, like you do in your code.

    There are a couple of other issues with your code. You should generally avoid Popen when you can; your code simply remiplements subprocess.check_output() or its modern replacement subprocess.run() rather clunkily. Secondly, calling Python as a subprocess of Python is very often an antipattern. Unless you are seeking specifically to test that standard output from Python contains what you expect (which, as discussed above, can only be a stream of bytes or characters) you are probably better off doing an import of the code and calling the function you want to test, in which case of course it will return a native Python data type by way of its return statement, if that's how it's defined.