0

I'm pretty novice in Python scripting and was trying to run an API call with some dynamic values passed.

A simple idea about the code is, it gets two datetimes in epoch(10 second interval)and calls an API to do a function.

import commands
end = str(datetime.datetime.now().strftime("%s"))
start = str((datetime.datetime.now() - datetime.timedelta(seconds=10)).strftime("%s"))
output = commands.getstatusoutput("curl 'http://my-api-url/object?param1=1&start=$start&end=$end&function=average'")

It doesn't work as the variables start and end are not getting expanded/substituted.

As you see, I come from bash scripting and tried looking on several variable substitution commands from web, but nothing specific found to my case here.

Vineeth
  • 692
  • 3
  • 9
  • 18
  • Try `"curl 'http://my-api-url/object?param1=1&start={}&end={}&function=average'".format(start, end)`. But you will lose a lot more time trying to advance like this than to look at Python doc. – Baris Demiray Oct 23 '18 at 09:52
  • Python isn't PHP, it has a C-style string interpolation system (in various versions from almost-C to C-inspired). See [the Python tutorial](https://docs.python.org/3.5/tutorial/inputoutput.html) for how to insert values in strings. – alexis Oct 23 '18 at 09:53

2 Answers2

1

Use str.format

Ex:

import commands
end = str(datetime.datetime.now().strftime("%s"))
start = str((datetime.datetime.now() - datetime.timedelta(seconds=10)).strftime("%s"))
output = commands.getstatusoutput("curl 'http://my-api-url/object?param1=1&start={start}&end={end}&function=average'".format(start=start, end=end))
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

In Python, you can concatenate strings using the '+' operator. In your case you could write:

output = commands.getstatusoutput("curl 'http://my-api-url/object?param1=1&start=" + start + "&end=" + end + "&function=average'")
Tony Pellerin
  • 231
  • 1
  • 7