0

I want to save the aws command in a variable.

#!/usr/bin/python3

import subprocess

aa = (subprocess.check_output(['aws ce get-cost-and-usage --time-period Start=2020-08-01,End=2020-08-31 --granularity=DAILY  --metrics BlendedCost |grep Amount | awk '{ gsub('\"',''); print $2 }' | sed 's/.$//''], shell=True)).decode('ascii').strip()

print(aa)
  File "test.py", line 5
    aa = (subprocess.check_output(['aws ce get-cost-and-usage --time-period Start=2020-08-01,End=2020-08-31 --granularity=DAILY  --metrics BlendedCost |grep Amount | awk '{ gsub('\"',''); print $2 }' | sed 's/.$//''], shell=True)).decode('ascii').strip()
                                                                                                                                                                           ^
SyntaxError: invalid syntax

What is the problem?

1
  • 1
    firstly, you're missing the ) at the end of that line, next, you need to escape those ' i.e. \' Commented Aug 6, 2020 at 5:04

2 Answers 2

2

You have at least one problem in this expression:

'{ gsub('\"',''); print $2 }'

You have single-quoted strings inside single-quoted strings. You have to escape the inner ones, or double them Not that your doubled one serves only as a single.

'{ gsub(\'\"\',\'\'); print $2 }'

'{ gsub(''\"'',""); print $2 }'

Note that in the second one, I converted your empty string to double quotes; this saves one instance of escaping.

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

Comments

1

You can check the following form:

#!/usr/bin/python3

import subprocess

cmd = "aws ce get-cost-and-usage --time-period Start=2020-08-01,End=2020-08-31 --granularity=DAILY  --metrics BlendedCost --profile la |  grep Amount | awk '{ gsub(\"\\\"\",\"\"); print $2 }' |  sed 's/.$//'"

print(cmd)

aa = subprocess.check_output([cmd], shell=True).decode('ascii').strip()

print(aa)

The print(cmd) gives:

aws ce get-cost-and-usage --time-period Start=2020-08-01,End=2020-08-31 --granularity=DAILY  --metrics BlendedCost --profile la |  grep Amount | awk '{ gsub("\"",""); print $2 }' |  sed 's/.$//'

I can't confirm if the command actually works, but there is no syntax error at least.

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.