Stop reading process output in Python without hang?

前端 未结 5 1150
遇见更好的自我
遇见更好的自我 2020-11-22 14:45

I have a Python program for Linux almost looks like this one :

import os
import time

process = os.popen(\"top\").readlines()

time.sleep(1)

os.popen(\"kill         


        
5条回答
  •  忘了有多久
    2020-11-22 15:12

    ( J.F. Sebastian your codes work great , I think it's better than my solution =) )

    I've solved it using another way.

    Instead of making the output directly on the terminal I make it into a file "tmp_file" :

    top >> tmp_file
    

    then I used the tool "cut" to make its output "which is top output" as process's value

    cat tmp_file
    

    and it did what I want it to do .This is the final code:

    import os
    import subprocess
    import time
    
    subprocess.Popen("top >> tmp_file",shell = True)
    
    time.sleep(1)
    
    os.popen("killall top")
    
    process = os.popen("cat tmp_file").read()
    
    os.popen("rm tmp_file")
    
    print process
    
    # Thing better than nothing =)
    

    Thank you so much guys for help

提交回复
热议问题