2

While Executing AWS CLI using python, Please find code for reference.

import awscli.clidriver
driver = awscli.clidriver.create_clidriver()
driver.main(['ec2','describe-instances','--instance-ids','i-12345678'])

Is it possible to store the output of driver.main in a variable ?

2
  • Focus on questions about an actual problem you have faced. Include details about what you have tried and exactly what you are trying to do. Commented Nov 27, 2018 at 5:38
  • I am trying to execute aws cli using python, While executing it using above method its returning the output of describe instance on CLI, I am not able to store the retrieved output in variable, whereas I am able to store exit code of executed cli. Commented Nov 27, 2018 at 5:42

1 Answer 1

2

I don't think this is supported by the AWS CLI but you can do this:

import awscli.clidriver
from cStringIO import StringIO
import sys

driver = awscli.clidriver.create_clidriver()

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

driver.main(['ec2','describe-instances','--instance-ids','i-12345678'])

sys.stdout = old_stdout

myvar = mystdout.getvalue()

Note that this is based on another Stack Overflow answer here.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for help. yes its returning the expected outcome, but result is string and is not convertible to json using json library of python.
Of course it is convertible to JSON. Just add lines import json ; myjson = json.loads(myvar).
@SakshiGupta, if this helped you should accept the correct answer.
It did help Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.