sangyul lee
sangyul lee

Reputation: 123

aws cli command on python 3.8 syntax error

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?

Upvotes: 0

Views: 647

Answers (2)

Marcin
Marcin

Reputation: 238507

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.

Upvotes: 1

Prune
Prune

Reputation: 77885

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.

Upvotes: 2

Related Questions