Newbie cant run the following code in bash

i want in bash to pass a variable (number) to python code and transform it into H:m:s:ms.
how i do that?


export mls=1000; python -c '
import os

def convert_milliseconds(ms): 
    seconds = ms // 1000 
    minutes = seconds // 60 
    hours = minutes // 60 
    days = hours // 24 
 
    seconds %= 60 
    minutes %= 60 
    hours %= 24 
 
    return f"{days} days, {hours} hours, {minutes} minutes, {seconds} seconds" 


print (convert_milliseconds(os.environ['mls']))
'

It helps to look at the traceback:

Traceback (most recent call last):
  File "<string>", line 17, in <module>
    print (convert_milliseconds(os.environ[mls]))
                                           ^^^
NameError: name 'mls' is not defined

Because you used single quotes within single quotes, they were skipped, and Python is trying to use a Python variable named mls, instead of the string literal 'mls'.

You could use double quotes, but you would get another problem, because environment variables are strings, so you would need to add a call to int(), like so:

print(convert_milliseconds(int(os.environ["mls"])))

Alternatively, you could embed the variable within the Python code. This won’t work very well if you’re dealing with strings, but with numbers, you can just do this:

$ mls=1000
$ python -c 'print(2 * '$mls')'
2000

Or you could pass data as arguments and read sys.argv:

$ python -c 'import sys; print(sys.argv)' hello
['-c', 'hello']

The latter two options have the advantage of not cluttering the environment variables.

2 Likes

thanks, this worked! i succeeded to transform milliseconds to time in linux bash with this python code.

mls=1000; python -c '
import os

def convert_milliseconds(ms): 
    seconds = ms // 1000 
    minutes = seconds // 60 
    hours = minutes // 60 
    days = hours // 24 
 
    seconds %= 60 
    minutes %= 60 
    hours %= 24 
 
    return f"{days} days, {hours} hours, {minutes} minutes, {seconds} seconds" 


print(convert_milliseconds('$mls'))