Substitute variable in a command in Python [duplicate] - python

This question already has answers here:
Variable interpolation in Python [duplicate]
(5 answers)
Closed 4 years ago.
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.

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))

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'")

Related

What does '\' mean when declaring a variable? [duplicate]

This question already has answers here:
What does a backslash by itself ('\') mean in Python? [duplicate]
(5 answers)
What is the purpose of a backslash at the end of a line?
(2 answers)
Closed 1 year ago.
While I was searching code from the internet about YouTube data analysis, I found code like this:
df_rgb2['total_sign_comment_ratio'] = df_rgb2['total_number_of_sign'] / df_rgb2['comment_count']
total_sign_comment_ratio_max = df_rgb2['total_sign_comment_ratio'].replace([np.inf, -np.inf], 0).max()
df_rgb2['total_sign_comment_ratio'] = \
df_rgb2['total_sign_comment_ratio'].replace([np.inf, -np.inf], total_sign_comment_ratio_max*1.5)
and I was wondering why the analyst used the expression:
df_rgb2['total_sign_comment_ratio'] = \
because whether I apply that code or not, the result is same.
I tried to find the meaning of '\' but all I have got is how to use '\' when printing out the result.
\ is usually used to make a piece of code go on onto multiple lines. If you where to just press enter and continue to write code a line below for example declaring a variable, it would count as an error.
You use this when you need to tidy up code or when your working window is too small for some reason.
See: https://developer.rhino3d.com/guides/rhinopython/python-statements/

what is the use of \ operator inside a list in python? [duplicate]

This question already has answers here:
What is the purpose of a backslash at the end of a line?
(2 answers)
Closed 2 years ago.
What is the use of \ in python?
Example, I saw the following codes"
data_idxs = [(self.entity_idxs[data[i][0]], self.relation_idxs[data[i][1]], \
self.entity_idxs[data[i][2]]) for i in range(len(data))]
or
self.relations = self.train_relations + [i for i in self.valid_relations \
if i not in self.train_relations] + [i for i in self.test_relations \
if i not in self.train_relations]
I guess you write \ when you want to have your code continue in a new line? But I also saw that when you have a lot of parameter in a method definition, you can have new line without using .
I guess you write \ when you want to have your code continue in a new line?
Yes. That's all it means.
In these cases it's not actually needed though because line continuation is implied by brackets.

Execute instructions written in a string [duplicate]

This question already has answers here:
How do I execute a string containing Python code in Python?
(14 answers)
Closed 2 years ago.
I have a little problem, I have written a for loop as a string.
In PHP, with the help of function exec(), we can run the string which will eventually run the for loop defined inside the string.
Can we do such a thing in Python as well?
By example, I would like run follow it:
string="for i in range(1,(5+1)): print(str(i))"
How to run this in Python?
You can use exec if you want to execute some statements:
code = 'for i in range(1,(5+1)): print(str(i))'
exec(code)
If you want to evaluate an expression and get the value then you can use eval:
value = eval('2+3')
print(value) # 5

Python: what does d = _ mean? [duplicate]

This question already has answers here:
What is the purpose of the single underscore "_" variable in Python?
(5 answers)
Closed 3 years ago.
At 44:05 in his Fun of Reinvention talk, Dave Beasley writes
>>> d = _
There is a lot before that, which is necessary for the result he gets. But ignoring the output, what does that input line mean? Whenever I try it, either in a file in the PyCharm editor, in the PyCharm Python console, using straight IDLE (all v3.7) I get an error.
Any idea what this may mean and how to get something like that to run?
Thanks
_ is a special variable in the python language.
In some REPLs, like IDLE, it holds the result of the last expression executed.
d = _ assigns the result of the last expression executed to d.

Return value in python function [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
import urllib,re
def getver():
url='https://github.com/Bendr0id/xmrigCC/releases'
website = urllib.urlopen(url)
html = website.read()
links = re.findall(r'(?<=<a href=")[^"]*\bgcc-win64.zip\b', html)
link=links[0]
version=link.split('/')
ver0=version[5]
return ver0
getver()
I've tried to run the code but it doesnt output anything,instead when I replace return with print it prints out the correct answer which is 1.5.2 .
What am I doing wrong?
You have been fooled by the interactive interpeter's friendly habit of printing out the results of any bare expressions you enter.
This does not happen when you run a program, so you need to ensure you output values specifically by using the print statement.
This is specifically mentioned in a rather obscure portion of the Python documentation dealing with the language's grammar.
Change the last line to:
print(getver())

Categories

Resources