Get output of system ping without printing to the console

前端 未结 2 1691
温柔的废话
温柔的废话 2021-01-05 16:22

I want to call ping from Python and get the output. I tried the following:

response = os.system(\"ping \"+ \"- c\")

However,

2条回答
  •  半阙折子戏
    2021-01-05 16:38

    To get the output of a command, use subprocess.check_output. It raises an error if the command fails, so surround it in a try block.

    import subprocess
    
    try:
        response = subprocess.check_output(
            ['ping', '-c', '3', '10.10.0.100'],
            stderr=subprocess.STDOUT,  # get all output
            universal_newlines=True  # return string not bytes
        )
    except subprocess.CalledProcessError:
        response = None
    

    To use ping to know whether an address is responding, use its return value, which is 0 for success. subprocess.check_call will raise and error if the return value is not 0. To suppress output, redirect stdout and stderr. With Python 3 you can use subprocess.DEVNULL rather than opening the null file in a block.

    import os
    import subprocess
    
    with open(os.devnull, 'w') as DEVNULL:
        try:
            subprocess.check_call(
                ['ping', '-c', '3', '10.10.0.100'],
                stdout=DEVNULL,  # suppress output
                stderr=DEVNULL
            )
            is_up = True
        except subprocess.CalledProcessError:
            is_up = False
    

    In general, use subprocess calls, which, as the docs describe, are intended to replace os.system.

提交回复
热议问题