ping for indefinite amount of time and get its output in Python

后端 未结 3 1998
死守一世寂寞
死守一世寂寞 2020-12-12 02:10

The task is: Try to send ping in python using the most basic form like \"ping 8.8.8.8\". After some time terminate the ping command (In a terminal, one will do Ctrl+C) and g

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 02:44

    ping will block in your code as soon as it fills its stdout OS pipe buffer (~65K on my system). You need to read the output:

    #!/usr/bin/env python
    import signal
    from subprocess import Popen, PIPE
    from threading import Timer
    
    child = Popen(['ping', '8.8.8.8'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    Timer(5, child.send_signal, [signal.SIGINT]).start() # Ctrl+C in 5 seconds
    out, err = child.communicate() # get output
    print(out.decode())
    print('*'*60)
    print(err.decode())
    

提交回复
热议问题