2

I am trying to run a very basic AWS CLI command from python, instead of using boto3

So I found one answer from stack overflow I tried that but it didn't do any better, I don't want to use boto3, below is my code which I have tried

import subprocess

cmd='aws s3 ls'
push=subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
print push.returncode

If I run these commands into bash scripts it works perfectly fine. But I have a restriction that it has to be done using python scripts only.

1
  • 2
    Do you mind if I ask why you wish to run the AWS CLI from Python? Commented Mar 6, 2019 at 10:26

2 Answers 2

1

As the documentation for subprocess.Popen states, .returncode stores the child process return code. After running your code I am seeing this output:

ania@blabla:~$ python3 test.py 
None
ania@blabla:~$ 
[Errno 32] Broken pipe

Checking again the aforementioned docs:

A None value indicates that the process hasn’t terminated yet.

So let's modify your code to wait for the child process to end (I am using Python 3):

import subprocess

cmd='aws s3 ls'
push=subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE)
push.wait()   # the new line
print(push.returncode)

Now, in the output I get the exit status 0:

ania@blabla:~$ python3 test.py 
0

This is advice about an issue with the subprocess module, but what bothers me is why you don't want to use the boto3 module which is specifically written for sending API calls to AWS from Python. I discourage you from using subprocess to send these requests and switch to boto3, if possible.

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

2 Comments

Actually i am trying to run some things which i know how to do with aws cli commands but not with python so i just want to learn any way to run cli commands in pythons just because of that i put the simple command of aws s3 ls
Alright, I hope my answer was helpful then. If it solved your problem, you can mark it as accepted.
0

Well, you can try following commands.

import subprocess

push=subprocess.call(['aws', 's3', 'ls', '--recursive', '--human-readable', '--summarize'])

or

import subprocess

push=subprocess.run(['aws', 's3', 'ls', '--recursive', '--human-readable', '--summarize'])

Wish help for you.

Comments

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.