how to set var including quotes in a command variable - python

I have the following cmd,am trying to equate data in var including quotes to changes('changes=var' as shown below),can anyone suggest the syntax to do it?
var = "769373 769374"
cmd = ['tool', '--server=commander.company.com', 'runProcedure', 'Android_Main',
'--procedureName', 'priority_kw', '--actualParameter',
`'changes=var'`,
'gerrit_server=review-android.company.com']

Use + to concatenate in Python. Example below show how it's used:
cmd = ['tool', '--server=commander.company.com', 'runProcedure', 'Android_Main',
'--procedureName', 'priority_kw', '--actualParameter',
'changes=' + var, 'gerrit_server=review-android.company.com']

I would recommend doing it this way:
var = "769373 769374"
cmd = ['tool', '--server=commander.company.com', 'runProcedure', 'Android_Main',
'--procedureName', 'priority_kw', '--actualParameter',
'changes={}'.format(var),
'gerrit_server=review-android.company.com']
Using string concatenation ('changes=' + var) works fine in this case, but that approach will sometimes fail when you're not expecting it to. For example, if var was an int, you'd get a TypeError: cannot concatenate 'str' and 'int' objects.

Related

Putting a variable into a string (quote) python

I am facing a problem while calling the variable values within the double quote
Here's my code:
AccountID = ["1234567","5678912"]
for account in range(len(AccountID)):
response = sts.assume_role(RoleArn=(f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"), RoleSessionName="learnaws-test-session")
print(response)
I have return response output with no variable values
File "test3.py", line 19
response = (RoleArn=(f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"), RoleSessionName="learnaws-test-session")
^
SyntaxError: invalid syntax
how would i return an expected results like:
arn:aws:iam::1234567:role/Cloudbees_Jenkins
arn:aws:iam::5678912:role/Cloudbees_Jenkins
You could use f-strings, a very convenient way to refer to variables inside print statements in python.
In your case, it would look like this:
response = f"arn:aws:iam::{int(AccountID[0])}:role/Cloudbees_Jenkins"
response = (RoleArn=(f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"), RoleSessionName="learnaws-test-session")
The problem here has nothing to do with generating the string.
The problem is that in Python the = (assignment) operator does not produce an output value.
So the expression RoleArn = ...a_bunch_of_stuff... only assigns that stuff to RoleArn. It doesn't produce any output value that can be assigned to response.
And the assignement RoleSessionName="learnaws-test-session" doesn't produce any return value that can be assigned to be part of the tuple that is being assigned to RoleArn.
So just break the code up into three lines:
RoleSessionName="learnaws-test-session"
RoleArn= f"arn:aws:iam::{AccountID[account]}:role/Cloudbees_Jenkins"
response = (RoleArn, RoleSessionName)
In recent Python versions (3.8 and newer) you can use the "walrus operator" := to both assign a value and return that value to be used in an expression, but in your code you should not because it IMO makes the code less clear.
AccountID = [1234567,5678912]
for i in AccountID:
print("arn:aws:iam::",i,"role/Cloudbees_Jenkins")

How do I use variable inside a parentheses and single quotes?

Using Python 2.7 I am trying to put a variable inside a (' ')
Orignial string
r = search.query('Hello World')
What I have tried so far and is not working...
r = search.query('{0}').format(company_name_search)
r = search.query('s%') % (company_name_search)
Both methods are not working and output the error below. What is the best way to take r = search.query('Hello World') and put a variable for Hello World so I can dynamically change the search parameters at will?
AttributeError: 'Results' object has no attribute 'format'
TypeError: unsupported operand type(s) for %: 'Results' and 'str'
You are now applying the .format() or % to the query(). Apply them to the string. '{0}'.format(company_name_search) or '%s'%(company_name_search). Then throw that into the query function, like
r = search.query('{0}'.format(company_name_search))
r = search.query('s%' % (company_name_search))

parsing integers in python into a command for another software

I want to write
vol_id = geom.get_owning_volume("surface", 12)
and I have S=12 on the fly during large code execution so I use
S=12
vol_id = geom.get_owning_volume("surface", "%d") %(S)
which gives me an error
TypeError: in method 'get_owning_volume', argument 2 of type 'int'
I have used the variation
S=12
vol_id = geom.get_owning_volume("surface", "%d" %(S))
this gives the same error
why I cannot parse the integer 12 to the desired place! any suggestions?
The % operator is for interpolating into strings, not into Python code. Your example is trying to pass the string "%d" where the function expects a number; no wonder it fails!
In your case, just put the variable S where you need it:
S=12
vol_id = geom.get_owning_volume("surface", S)
From the documentation that I found, get_owning_volume takes a string and an integer, and you already have an integer, so there's no need to convert it:
vol_id = geom.get_owning_volume("surface", S)
From the comments it looks like S is actually a string, and you want an integer, then this should work:
vol_id = geom.get_owning_volume("surface", int(S))

python variable concatination with different equators

How would I be able to make a variable that contains another = sign in it, like this:
newval = dict[key_to_find] = int(change)
The problem with doing this is that in Python the '=' is an assignment operator rather than a symbol.
Python is reading what you wrote as trying to assign to two variables. For example:
foo = "test" and bar = "test" can be written as foo = bar = "test"
Creating a variable name with an '=' it can't be done.
If you are trying to create a new variable that has a string value that comes from two other sources you can use the format that intboolstring suggested, or the format function is pretty handy.
Going along with your example:
newval = "{dict} = {int}".format(dict=dict[key_to_find], int = int(change))
To give a simpler example of how this works:
var_a = 'Hello'
var_b = 'world'
variable = "{a} {b}!".format(a = var_a, b = var_b)
Variable will print:
"Hello world!"
I'm basing the answer off of
variable that contains another = sign in it
I think you are trying to concatenate dict[key_to_find] and int(change) with an equal sign in the middle. This can be done with the following
newval = str(dict[key_to_find]) + " = " + str(int(change))
The reason that I'm leaving in the int cast is because if you had change as 7.5, then you would want it in the string as 7.

Python, how can I initialize a variable during function/method calls

In most interpreted languages (example given in psuedo PHP) I would be able to do something like this
function f($name, &$errors = null) {
if(something_wrong) {
if(!is_null($errors) {
$errors[] = 'some error';
}
return false;
}
}
if(!f('test', $errs = array()) {
print_r($errs);
}
And get a result like
Array
(
[0] => some error
)
However when I try this in Python
def f(name, errors = None):
if something_wrong:
if errors:
errors.append('some error')
return False
if not f('test', errs = []):
print str(errs)
I get an error
TypeError: f() got an unexpected keyword argument 'errs'
Which makes perfect sense in the context of Python thinking I am trying to set a specific argument, and not create a new variable altogether.
However if I try
if not f('test', (errs = [])):
print str(errs)
I get
f('test', (errs = []))
^
SyntaxError: invalid syntax
Because I think now it assumes I am trying to create a tuple.
Is there any way to keep this code on one line, or do I absolutely have to initialise the variable on it's own before passing it to the function/method? From what I can tell the only solution is this
errs = []
if not f('test', errs):
print str(errs)
It should be called as f(name, errors = []) or f(name, []). If you want to init with attribute name, python requires the variable key you given is same with any attribute name you declared in the function definition.
"In Python, assignment is a statement, not an expression, and can
therefore not be used inside an arbitrary expression."
see http://effbot.org/pyfaq/why-can-t-i-use-an-assignment-in-an-expression.htm

Categories

Resources