Link to home
Start Free TrialLog in
Avatar of enthuguy
enthuguyFlag for Australia

asked on

convert usd to aud using python CurrencyConverter

Hi Python experts

this is reference to this conversation

https://www.experts-exchange.com/questions/29167463/python-convert-currency.html?anchor=a42998667¬ificationFollowed=242733822&anchorAnswerId=42998667#a42998667

how to convert "float(amount)" from USD to AUD please :)

#!/usr/bin/env python2.7

import argparse
import boto3
import datetime
from currency_converter import CurrencyConverter

parser = argparse.ArgumentParser()
parser.add_argument('--days', type=int, default=30)
args = parser.parse_args()


now = datetime.datetime.utcnow()
start = (now - datetime.timedelta(days=args.days)).strftime('%Y-%m-%d')
end = now.strftime('%Y-%m-%d')
dtemplate="{:10} {:14} {:40} {:16.10f} {:6} {:10}"
htemplate="{:10} {:14} {:40} {:16} {:6} {:10}"

cd = boto3.client('ce', 'ap-southeast-2')

results = []

token = None
while True:
    if token:
        kwargs = {'NextPageToken': token}
    else:
        kwargs = {}
    data = cd.get_cost_and_usage(TimePeriod={'Start': start, 'End':  end}, Granularity='DAILY', Metrics=['UnblendedCost'], GroupBy=[{'Type': 'DIMENSION', 'Key': 'LINKED_ACCOUNT'}, {'Type': 'DIMENSION', 'Key': 'SERVICE'}], **kwargs)
    results += data['ResultsByTime']
    token = data.get('NextPageToken')
    if not token:
        break

print(htemplate.format("TimePeriod", "LinkedAccount", "Service", "Amount", "Unit", "Estimated"))

for result_by_time in results:
    for group in result_by_time['Groups']:
        amount = group['Metrics']['UnblendedCost']['Amount']
        unit = group['Metrics']['UnblendedCost']['Unit']
        print(dtemplate.format(result_by_time['TimePeriod']['Start'], group['Keys'][0],  group['Keys'][1], float(amount), unit,  result_by_time['Estimated']))

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Kimputer
Kimputer

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of noci
noci

You can change this:
print(dtemplate.format(result_by_time['TimePeriod']['Start'], group['Keys'][0],  group['Keys'][1], float(amount), unit,  result_by_time['Estimated']))

Open in new window


into:
aud_amount = format(CurrencyConverter(float(amount)),"USD","AUD")
print(dtemplate.format(result_by_time['TimePeriod']['Start'], group['Keys'][0],  group['Keys'][1], aud_mount, unit,  result_by_time['Estimated']))

Open in new window


It can be folded into one line as well...
Avatar of enthuguy

ASKER

Thanks Kim, Noci,

I have another challenge now.

After introducing this currency in the script. When I execute as root, it works fine
Since I execute via jenkins (non-root) user and my server allows jenkins user to execute only selective files from sudoers file

Error when jenkins user execute it
T
raceback (most recent call last):
  File "/usr/local/bin/aws_cost_explorer.py", line 7, in <module>
    from currency_converter import CurrencyConverter
ImportError: No module named currency_converter

Open in new window


when I printed sys path using

print '\n'.join(sys.path)

/usr/local/bin
/usr/lib/python2.7/site-packages/pip-19.3.1-py2.7.egg
/usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/root/.local/lib/python2.7/site-packages
/usr/lib64/python2.7/site-packages
/usr/lib/python2.7/site-packages

Open in new window


after seeing few package loading issues as non-root user, I updated jenkins sudoers file like below still no luck.
export PATH=$PATH:/usr/lib64/python2.7
Defaults env_reset
Defaults env_keep += "PATH PYTHONPATH"
jenkins ALL=(root) NOPASSWD: /usr/local/bin/aws_cost_explorer.py

Open in new window


Without currency module (with only USD), jenkins user executes above py file and generats report fine
What is the difference in the path between running as root & running as jenkins?
(The Jenkins task can also run on jet another system where the currency module is not available.)
You can also place a copy of the currency modules WITH the package...  [ not preferred though ]
Thanks
I can give it a try...could you give me a reference please
"currency modules WITH the package"
Put the module.py file (and all other stuff if there are subdirectories in the module ) in the same directory...
bit advanced for me :P
I couldnt find the module directory


/usr/lib64/python2.7/site-packages
/usr/lib/python2.7/site-packages
There is two forms:
Either a .py file in the site-packages or a directory there with __init__.py  in it.

try to find the package: find / -type f -iname '*currency_converter*'  -ls and find / -type d -iname '*currency_converter*'  -ls
It should give you the path to the python module file(s).