here is the function:
def sh(*command, read_output=False, **kwargs):
command_text = " ".join(command)
print(f"\t> {command_text}")
try:
if read_output:
return check_output(command, **kwargs).decode("utf8")
else:
check_call(command, **kwargs)
except CalledProcessError as failure:
print(
f'ERROR: "{command_text}" command reported failure! Return code {failure.returncode}.'
)
sys.exit(failure.returncode)
I'm trying to use this function to get aws erc get-login first, then use that returned login command to login to aws erc. here is my codes:
result = sh('aws', 'ecr', 'get-login', '--no-include-email', read_output=True)
re = result.split()
sh(re)
then I get error:
command_text = " ".join(command)
TypeError: sequence item 0: expected str instance, list found
I think the sh
function expect arguments something like `('docker', 'login', '-u', 'AWS', '-p'...), but how can I achieve this?
You can use *
to unpack list/tuple and function get it as many arguments
sh( *re )
Or you can remove *
from *command
in definiton
def sh(command, ...)
and then you can send it only as list/tuple
sh( re )
but you can also check if command
is list
or string
if isinstance(command, str):
command_text = command
elif isinstance(command, list, tuple):
command_text = " ".join(command)
so then you can send it directly as one string.
sh( 'aws ecr get-login --no-include-email' )
or list with strings
sh( ['aws', 'ecr', 'get-login', '--no-include-email'] )
BTW: Similar way works **
with dictionary and named arguments
def fun(a=0, b=0, c=0):
print('a:', a)
print('b:', b)
print('c:', c)
data = {'b':2}
fun(**data)