Scheduled Maintenance: We are aware of an issue with Google, AOL, and Yahoo services as email providers which are blocking new registrations. We are trying to fix the issue and we have several internal and external support tickets in process to resolve the issue. Please see: viewtopic.php?t=158230

 

 

 

[SOLVED] python3 string formatting

Programming languages, Coding, Executables, Package Creation, and Scripting.
Post Reply
Message
Author
arzgi
Posts: 1197
Joined: 2008-02-21 17:03
Location: Finland
Been thanked: 32 times

[SOLVED] python3 string formatting

#1 Post by arzgi »

This is driving me nuts, have been banging my head two days, but can't figure it out.

In python3 shell it works as expected:

Code: Select all

$ python3
Python 3.7.3 (default, Apr  3 2019, 05:39:12) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> aika = '21.11.2019 21.44.57'
>>> lampo = '+49.0°C'
>>> f'{aika} {lampo}'
'21.11.2019 21.44.57 +49.0°C'
>>> 
The script I'm working on:

Code: Select all

#!/usr/bin/env python3

import subprocess, time

while True:
    subprocess.call("/home/arto/bin/lampo.sh")
    with open("/tmp/aika") as fa:
        aika = fa.readline()

    with  open("/tmp/lampo") as fl:
        lampo = fl.readline()

    print(f'{aika} {lampo}')

    time.sleep(30)
Output:

Code: Select all

21.11.2019 21.54.21
 +50.0°C

21.11.2019 21.54.28
 +50.0°C

21.11.2019 21.54.37
 +49.0°C

21.11.2019 21.54.51
 +50.0°C

21.11.2019 21.54.58
 +50.0°C

21.11.2019 21.55.07
 +50.0°C

21.11.2019 21.55.21
 +50.0°C
And the bash script, that is launched from python3 script:

Code: Select all

#!/bin/bash

if [ -f /tmp/aika ] 
    then rm /tmp/aika
fi

if [ -f /tmp/lampo ]
    then rm /tmp/lampo
fi

if [ -f /tmp/dd ]
    then rm /tmp/dd
fi

date >> /tmp/dd
cat /tmp/dd | gawk '{print $2, $3}' >> /tmp/aika
sensors | grep 'Core 3:' | gawk '{printf $3"\n"}' >> /tmp/lampo
What is the problem, why can't I get two string variables printed to same line?
Last edited by arzgi on 2019-11-22 08:26, edited 1 time in total.

cronoik
Posts: 310
Joined: 2015-05-20 21:17

Re: python3 string formatting

#2 Post by cronoik »

arzgi wrote:What is the problem, why can't I get two string variables printed to same line?
Calling readlines() will read the whole file line by line (including the newlines!). You need to strip the newlines before printing the results to get them in one line:

Code: Select all

aika = aika.replace('\n', '')
Have a nice day!

arzgi
Posts: 1197
Joined: 2008-02-21 17:03
Location: Finland
Been thanked: 32 times

Re: python3 string formatting

#3 Post by arzgi »

Thanks cronolk for finding the solution!

Code: Select all

22.11.2019 11.10.36 +42.0°C

22.11.2019 11.11.06 +42.0°C

22.11.2019 11.11.36 +43.0°C

22.11.2019 11.12.06 +44.0°C

Post Reply