check output from CalledProcessError

后端 未结 6 724
心在旅途
心在旅途 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:13

    If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:

    import subprocess
    
    command = ["ls", "-l"]
    try:
        output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
        success = True 
    except subprocess.CalledProcessError as e:
        output = e.output.decode()
        success = False
    
    print(output)
    

    This is Python 2 and 3 compatible.

    If your command is a string rather than an array, prefix this with:

    import shlex
    command = shlex.split(command)
    

提交回复
热议问题