簡體   English   中英

如何從 Popen 標准輸出中獲取 output 類型

[英]How to get output type from Popen stdout

我正在制作自動分級機,我無法從標准輸出中獲得 output 類型的“test_file”,就像我的 test_file 返回 integer 但標准輸出總是作為字符串 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)

就像從任何其他類型的文件句柄讀取時一樣,讀取標准 output 的唯一可能結果是 binary bytesstr ,當字節被解碼時 - 因為您使用text=True或其過時的同義詞universal_newlines=True在調用 subprocess.Popen( subprocess.Popen()時,或者因為您明確地.decode() bytes ,就像您在代碼中所做的那樣。

您的代碼還有其他幾個問題。 您通常應該盡可能避免使用Popen 您的代碼只是簡單地重復 subprocess.check_output subprocess.check_output()或其現代替代 subprocess.run subprocess.run()相當笨拙。 其次,調用 Python 作為 Python 的子進程通常是一種反模式。 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進行測試,在這種情況下,它當然會通過其return語句返回本機 Python 數據類型,如果這是它的定義方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM