简体   繁体   中英

output from subprocess.check_output in Python is empty for openstack CLI

I tried executing an OpenStack CLI openstack volume list | grep -w my_vm1 openstack volume list | grep -w my_vm1 using subprocess in python

output = subprocess.check_output(cmd, shell=True)

In this case

cmd = 'openstack volume list | grep -w my_vm1'. 

I observed that the output is null. When I tried:

output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)

And if I print the output var, it shows me "type 'exceptions.OSError'". Am I missing something?

It seems like you are running into an OSError exception.

I usually run subprocess commands within try / expect for catching issues, and use pipe and communicate() to grab the output from commands. I find this flow more logic.

Something like this:

try:
    cmd = 'openstack volume list | grep -w my_vm1'
    output = subprocess.check_output(cmd, 
                                     stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
    out, err = p.communicate()
    print(out)
except OSError:
    print(err)
    sys.exit(1)

Granted you can run the command as the same user running the script, it should work. If not, this should show you some error message, granted that command is playing by the rules.

I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM