check output from CalledProcessError

后端 未结 6 719
心在旅途
心在旅途 2020-12-02 15:11

I am using subprocess.check_output from pythons subprocess module to execute a ping command. Here is how I am doing it:

output = subprocess.check_output([\"p         


        
6条回答
  •  借酒劲吻你
    2020-12-02 16:07

    Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.

    Also, it was unclear where the output string was coming from. My update:

    import subprocess
    
    # Output returned in error handler
    try:
        print("Ping stdout output on success:\n" + 
               subprocess.check_output(["ping", "-c", "2", "-w", "2", "1.1.1.1"]))
    except subprocess.CalledProcessError as e:
        print("Ping stdout output on error:\n" + e.output)
    
    # Output returned normally
    try:
        print("Ping stdout output on success:\n" + 
               subprocess.check_output(["ping", "-c", "2", "-w", "2", "8.8.8.8"]))
    except subprocess.CalledProcessError as e:
        print("Ping stdout output on error:\n" + e.output)
    

    I see an output like this:

    Ping stdout output on error:
    PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
    
    --- 1.1.1.1 ping statistics ---
    2 packets transmitted, 0 received, 100% packet loss, time 1007ms
    
    
    Ping stdout output on success:
    PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
    64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=37.8 ms
    64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=38.8 ms
    
    --- 8.8.8.8 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 1001ms
    rtt min/avg/max/mdev = 37.840/38.321/38.802/0.481 ms
    

提交回复
热议问题