Python Forum

Full Version: How to use a variable as part of a filename
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I would like to simplify the following code, replacing the multiple if/elif's with a single line, but I have not been able to successfully figure it out.
def print_time():
    now = datetime.datetime.now()
    hour = now.hour
    minute = now.minute
    second = now.second
    if hour == 1:
        command = 'echo 0 | fbink -i 1.png -g x=100 -c'
    elif hour == 2:
        command = 'echo 0 | fbink -i 2.png -g x=100 -c'
    elif hour == 3:
        command = 'echo 0 | fbink -i 3.png -g x=100 -c'
    elif hour == 4:
        command = 'echo 0 | fbink -i 4.png -g x=100 -c'
    elif hour == 5:
        command = 'echo 0 | fbink -i 5.png -g x=100 -c'
    elif hour ==6:
        command = 'echo 0 | fbink -i 6.png -g x=100 -c'
#   etc...        
    os.system(command)
Any help is much appreciated!
The modern way to do it (f-string syntax):

command = f'echo 0 | fbink -i {hour}.png -g x=100 -c'
The backward compatible (to 3.5 and earlier) way to do it (the format method of strings):

command = 'echo 0 | fbink -i {}.png -g x = 100 -c'.format(hour)
Thanks! My code looks much better now.
and also subprocess.run is preferd over os.system
That's working well,however when there is more text following the braces, it is ignored.
For example:
command = 'fbink -t regular=/mnt/us/clock/bahnschrift.ttf,top=1410,px=35,format "BATTERY {}%" -me'.format(batpercent)
The % (or any other text) is not displayed.
?
I don't know, it's working fine for me. What is the value of batpercent? It's not a string with a new line character in it, is it?
no, it's an integer...
Turns out I was incorrect; it was a string with a trailing LF.
(Dec-21-2019, 09:24 AM)buran Wrote: [ -> ]and also subprocess.run is preferd over os.system

I am running on python v2.7; subprocess.run is not available. Would subprocess.Popen also be preferred?
End of life (support) for Python 2.7 is this coming Wednesday. Switch to Python 3.x if at all possible.
Pages: 1 2