So I'm writing a little script in python to read the temperature of built-in core sensor(Raspberry Pi) + print it on the screen + write the data to the .txt file. Everything is working pretty much, but I have two problems which I couldn't solve and I have spent like 3-4 hours on it. Fully output of that command is for example: temp=39.0'C and I need only the number from that string --> 39.0. So I'm trying to replace characters and part of the string that I don't need and make it number float.
return temp.replace("temp=", " ").replace("'C", "") My problem is when I'm running this code I still have 1 space before my number and that's because I'm replacing "temp=" with " ", but if I delete that space second replace becomes part of the string and it doesn't do its job anymore, in my opinion, there's too many --> """""'""" of those characters and program gets confused. But how can I solve it? Second problem how can I change it to float because, in my opinion, those numbers are still part of the string? Please help because I am so frustrated that such little script takes so much time to get it working.
import re
import os
import time
def measure_temp():
temp = os.popen("vcgencmd measure_temp").readline()
return temp.replace("temp=", " ").replace("'C", "")
while True:
temperature = measure_temp()
print(temperature)
f = open("pythonLog.txt", "a")
f.write (temperature)
f.close()
time.sleep(1)
Thanks to all who trie to help i have solved by extracting by using temp = temp[1] so the space at the index 0 is gone.
Related
Fairly new to Python, and I've got a batch job that I now have to start saving some extracts from out to a company Sharepoint site. I've searched around and cannot seem to find a solution to the issue I keep running into. I need to pass a date into the filename, and was first having issues with using a normal string. If I just type out the entire thing as a raw string, I get the output I want:
x = r"\\mnt4793\DavWWWRoot\sites\GlobalSupply\Plastics\DataExtracts\2021-02-15_aRoute.xlsx"
print (x)
The output is: \mnt4793\DavWWWRoot\sites\GlobalSupply\Plastics\DataExtracts\2021-02-15_aRoute.xlsx
However, if I break the string into it's parts so I can get a parameter in there, I wind up having to toss an extra double-quote on the "x" parameter to keep the code from running into a "SyntaxError: EOL while scanning string literal" error:
x = r"\\mnt4793\DavWWWRoot\sites\GlobalSupply\Plastics\DataExtracts\""
timestamp = date_time_obj.date().strftime('%Y-%m-%d')
filename = "_aRoute.xlsx"
print (x + timestamp + filename)
But the output I get passes that unwanted double quote into my string: \mnt4793\DavWWWRoot\sites\GlobalSupply\Plastics\DataExtracts"2021-02-15_aRoute.xlsx
The syntax I need is clearly escaping me, I'm just trying to get the path built so I can save the file itself. If it happens to matter, I'm using pandas to write the file:
data = pandas.read_sql(sql, cnxn)
data.to_excel(string_goes_here)
Any help would be greatly appreciated!
Per the comment from #Matthias, as it turns out, an r-string can't end with a single backslash. The quick workaround, therefore, was:
x = r"\\mnt4793\DavWWWRoot\sites\GlobalSupply\Plastics\DataExtracts" + "\\"
The comment from #sammywemmy also linked to what looks to be a much more thorough solution.
Thank you both!
I'm learning Python and for my homework I wrote a simple script that get a string from user like this one: aaaabbbbcccdde and transforms it to a4b4c3d2e1.
Now I've decided to get things more interesting and modified code for continuous input and output in realtime. So I need a possibility to enter symbols and get an output coded with that simple algorithm.
The only problem I've faced with I needed output without '\n' so all the coded symbols were printed consequently in one string e.g: a4b4c3d2e1
But in that case output symbols mixed with my input and eventually the script froze. Obviously I need Enter symbols for input on one string and output it on another string w/o line breaks.
So, could you tell me please is it possible without a lot of difficulties for newbie make up a code that would do something like this:
a - #here the string in shell where I'm always add any symbols
a4b4c3d2e1a4b4c3d2e1a4b4c3d2e1 - #here, on the next string the script continuously outputs results of coding without breaking the line.
import getch
cnt = 1
print('Enter any string:')
user1 = getch.getch()
while True:
buf = getch.getch()
if buf == user1:
cnt += 1
user1 = buf
else:
print(user1, cnt, sep='')
user1 = buf
cnt = 1
so this snippet outputs me something like this:
a4
s4
d4
f4
etc
And in all cases when I'm trying to add end='' to output print() the program sticks.
What is possible to do to get rid of that?
Thanks !
I don't really know the details but I can say that: when you add end='', the program don't freeze, but the output (stdout) does not refresh (maybe due to some optimisation ? I really don't know).
So what you want to do is to flush the output right after you print in it.
print(user1, cnt, sep='', end='')
sys.stdout.flush()
(It is actually a duplicate of How to flush output of print function? )
I'm new to python and I've been trying to make a little function to call upon when I need to filter an input from everything except regular letters.
I've used SO for parts of the code, but I can't seem to understand why does it only print on every second try.
Here's my code:
import re
i=1
def inputFilterText():
inputRaw = input('input: ')
inputFiltered = re.sub('[^a-zA-Z]+', '', inputRaw)
return inputFiltered
while i > 0:
inputFilterText()
print(inputFilterText())
And here's my output:
I'm not really sure what's going on, but I presume it's a logical error. I've only just started using Python so any help is appreciated.
PSThe 'while' is only there so it's easier to test, it can be omitted.
You are calling inputFilterText twice. Once within the print() and once before. This is causing the code to prompt for input twice before printing the second response.
The problem is that you make a call to the inputFilterText function twice. The first time the output is discarded. Causing input to be taken twice, but only showing a result once.
To fix it, remove the inputFilterText() line. An example of working code.
import re
i=1
def inputFilterText():
inputRaw = input("input: ")
inputFiltered = re.sub(""[^a-zA-Z]+, "", inputRaw)
return inputFiltered
while i > 0:
print(inputFilterText())
Also, in future please send code as raw text, rather than screenshots.
Might I suggest using a variable here, you're not doing anything with the first filter call (this is why it's asking the first time) and the second one you're only printing.
while True:
txt = inputFilterText()
#do some stuff if needed
print(txt)
I want the output of my code to overwrite the previous output on the same line.
I have read the previous answers to a similar question and have read that I can do this using a ',' and a '\r', but this doesn't seem to work for me. I tried:
for i in range(length):
print 'Minutes:',minute,'of {0}'.format(length),'\r',
minute+=1
time.sleep(1)
But it doesn't print anything other than the last line of the loop. I've tried other arrangements,but nothing yet has worked. Could someone let me know what I'm doing wrong?
Thanks.
If You are doing this in Linux, You can simply use ASCII escape sequence to move cursor up one line (\033[1A). Of course, You will still use \r to move to the beginning of the line. You could use something like this:
for i in range(length):
print('Minutes: ' + minutes + '\033[1A\r')
minutes += 1
sleep(1)
You need sys.stderr for fast output on a screen:
import sys,time
length,minute = 10,0
for i in range(length):
sys.stderr.write('Minutes:{} of {}\r'.format(minute,length))
minute+=1
time.sleep(1)
Don't forget to add sys.stderr.write('\n') at the end of your loop to avoid printing into the same line.
The easiest way I can think of doing this is, if you know how many lines your shell is, then you can just
print "\n" * (number_of_lines - 1)
then
print 'Minutes:',minute,'of {0}'.format(length)
So together,
for i in range(length):
print "\n" * (number_of_lines - 1)
print 'Minutes:',minute,'of {0}'.format(length)
minute += 1
time.sleep(1)
General Tips
You use commas and str.format() in the same print statement, instead just use str.format() for all of it. e.g print 'Minutes: {0}, of {1}'.format(minute, length).
You used minute as your counter even though it appears you are counting by seconds. For clarity you may want to rename that variable second.
Note
sys.stderr is the better way to do this. Please look at rth's answer
If you are using Python3, you can use a code like this:
import time
minute, length = 1, 100
for i in range(length):
print ('Minutes: {0} of {1}\r'.format(minute, length), end = "")
minute+=1
time.sleep(1)
However if you are using Python2, you can import print_function from __future__ module like this example:
from __future__ import print_function
import time
minute, length = 1, 100
for i in range(length):
print("Minutes: {0} of {1}\r".format(minute, length), end = "")
minute+=1
time.sleep(1)
PS: I have a strange issue when running the last code from my terminal using Python2.7.10. The script work but there is not any output.
However within Python 2.7.10 interpreter the code works fine.
Test both solutions and leave your feedbacks if you encounter any problems within Python2.
EDIT:
I think the better solution to avoid the strange issue that i encounter, and i don't know the cause, is using the ASCII escape as #Fejs said in his answer.
Your code will be something like this:
import time
minute, length = 1, 100
for i in range(length):
print "Minutes: {0} of {1} {2}".format(minute, length, '\033[1A\r')
minute+=1
time.sleep(1)
Try flushing the output before each sleep.
minute+=1
sys.stdout.flush()
time.sleep(1)
I made a python script to take text from an input file and randomly rearrange the words for a creative writing project based around the cut-up technique (http://en.wikipedia.org/wiki/Cut-up_technique).
Here's the script as it currently stands. NB: I'm running this as a server side include.
#!/usr/bin/python
from random import shuffle
src = open("input.txt", "r")
srcText = src.read()
src.close()
srcList = srcText.split()
shuffle(srcList)
cutUpText = " ".join(srcList)
print("Content-type: text/html\n\n" + cutUpText)
This basically does the job I want it to do, but one improvement I'd like to make is to identify duplicate words within the output and remove them. To clarify, I only want to identify duplicates in a sequence, for example "the the" or "I I I". I don't want to make it so that, for example, "the" only appears once in the entire output.
Can someone point me in the right direction to start solving this problem? (My background isn't in programming at all, so I basically put this script together through a lot of reading bits of the python manual and browsing this site. Please be gentle with me.)
You can write a generator to produce words without duplicates:
def nodups(s):
last = None
for w in s:
if w == last:
continue
yield w
last = w
Then you can use this in your program:
cutUpText = " ".join(nodups(srcList))
Adding the lines
spaces = [(i%10) == 9 and '\n' or ' ' for i in range(0,len(srcList))];
cutUpText = "".join(map(lambda x,y: "".join([x,y]),srcList,spaces));
helps bring some raw formatting to the text screens.
Add this to your existing program:
srcList = list(set(srcText.split()))