Getting easygui to self update info - python

Trying to get a self updating speedometer and clock working for my truck using gps. So far I have been able to get the read out that I want using easygui and msgbox but it is not self updating which will not help much on either application. Below is the code. Any help would be much appreciated, I know this is pretty ugly and probably not correct but I am new to python.
import gps
from easygui import *
import sys
# Listen on port 2947 (gpsd) of localhost
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
while True:
try:
report = session.next()
if report['class'] == 'TPV':
if hasattr(report, 'time'):
hour = int(report.time[11:13])
hourfix = hour - 7
if hourfix < 12:
time = 'Current Time Is: ' + report.time[5:7] + '/' + report.time[8:10] + '/' + report.time[0:4] + ' ' + str(hourfix) + report.time[13:19] + ' am'
else:
hourfix = hourfix - 12
time = 'Current Time Is: ' + report.time[5:7] + '/' + report.time[8:10] + '/' + report.time[0:4] + ' ' + str(hourfix) + report.time[13:19] + ' pm'
if report['class'] == 'TPV':
if hasattr(report, 'speed'):
speed = int(report.speed * gps.MPS_TO_MPH)
strspeed = str(speed)
currentspeed = 'Current Speed Is: ' + strspeed + ' MPH'
msgbox(time + "\n" + currentspeed, "SPEEDO by Jono")
except KeyError:
pass
except KeyboardInterrupt:
quit()
except StopIteration:
session = None
print "GPSD has terminated"

Related

How to print out and make program do nothing after that python-3.x [duplicate]

This question already has answers here:
How do I terminate a script?
(14 answers)
Closed 4 months ago.
I want to print out an error code "DAT_GRESKA" or "GRESKA" in other input and then make the code do nothing but in my case it is taking me back and asking me to redo the input because its false. How do I make it to stop but without using exit() or quit().
import csv
def unos_csv():
ucsv = input("Unesi CSV datoteku: ")
if ucsv == 'raspored1.csv' or ucsv == 'raspored2.csv':
ucsv = str(ucsv)
return ucsv
else:
print('DAT_GRESKA')
return main()
def ime_predmeta():
subname = input("Unesi kod predmeta: ")
if subname.isupper():
return subname
else:
print("GRESKA")
return main()
def obrada():
file = open(unos_csv(), "r")
reader = csv.reader(file, delimiter=',')
predmet = ime_predmeta()
with open(predmet + '.txt', 'a')as a:
for row in reader:
danu_nedelji = int(row[0])
dejan = row[3].split('[')[1].split(']')[0]
if predmet in row[3]:
t1 = row[1]
t2 = row[2]
h1, m1 = t1.split(':')
h2, m2 = t2.split(':')
t11 = int(h1) * 60 + int(m1)
t22 = int(h2) * 60 + int(m2)
tkon = t22 - t11
tkon = str(tkon)
if danu_nedelji == 0:
a.write("Monday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 1:
a.write("Tuesday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 2:
a.write("Wednesday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 3:
a.write("Thursday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
elif danu_nedelji == 4:
a.write("Friday" + ' ' + row[1] + ' ' + row[2] + ' ' + tkon + ' ' + dejan + '\n')
a.close()
def main():
obrada()
if __name__ == '__main__':
main()
I think you misunderstand how the return statement works.
The reason that your program "continues" ... it doesn't continue -- you specifically invoke your main program another time. If you simply want to go back to the calling location and continue, use
return
You used
return main()
which is a command to invoke main again, wait until it's done, and send that value back to whatever called the function.

ASCII animation blinking python

Decided to make a simple mp3 player for terminal. But while I was doing animation I had a problem - it blinks when the frame changes. Heres a video of it: https://youtu.be/in4VLPOfzHw. And the code:
import time, os, glob, eyed3, math, sys
from colorama import init
from mutagen.mp3 import MP3
mpts = glob.glob('*.mp3')
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
i = 0
song_list = []
for mpt in mpts:
song = MP3(mpt)
duration = math.ceil(song.info.length)
m_duration = duration // 60
s_duration = duration % 60
song = eyed3.load(mpt)
name = song.tag.title
song_list.append([name, [m_duration, s_duration]])
init()
# draw
while True:
# cassette
res = ''
i += 1
res += light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|'
if i % 4 == 0:
res += white + ' (/)====(/) '
elif i % 4 == 1:
res += white + ' (-)====(-) '
elif i % 4 == 2:
res += white + ' (\\)====(\\) '
elif i % 4 == 3:
res += white + ' (|)====(|) '
res += light_grey + '|'
res += dark_grey + '| \n'
res += dark_grey + ' |'
res += light_grey + '|############|'
res += dark_grey + '|\n'
res += light_grey + ' ■____________■ \n'
# green line
res += lime + ' ___________________________________\n\n'
# song list
res += red + ' # NAME TIME\n'
for i1 in range(len(song_list)):
res += dark_grey + ' ' + str(i1+1) + '.'
res += white + ' ' + song_list[i1][0] + ' '*(28 - len(song_list[i1][0])) + f'{song_list[i1][1][0]}:{song_list[i1][1][1]}\n'
os.system('cls')
sys.stdout.write(res)
sys.stdout.flush()
time.sleep(0.4)
Can it be fixed or sould I try to make in some other language instead of python?
It's the shelling out to cls that's doing it. Since you're already using ANSI codes for other stuff, try something like:
clear = '\033c'
...
while True:
...
print(clear)
Note that you'll never be able to completely get rid of the screen flicker using the "clear the screen then redraw it" technique, but this will shave several milliseconds from every loop and should decrease the flickering.
The idea is to avoid cleaning the whole screen (os.system('cls')). We could simply move the cursor to top and reprint everything. However moving cursor to top is almost impossible. One workaround I found is to print a lot of special characters that move cursor up one line until all the way to the top.
Reference:
cmd console game; reduction of blinking
The first solution of using \b does not work for me on a windows machine. So I go for the ender_scythe's solution. You have to print an empty line on first run to avoid the issue he/she mentioned. Here is the sample code that does not blink at all:
import time
import os
i = 0
dark_grey = '\033[1;30;40m'
light_grey = '\033[0;37;40m'
white = '\033[1;37;40m'
lime = '\033[1;32;40m'
red = '\033[0;31;40m'
def my_cls(nrow = 0):
if nrow == 0:
os.system('cls')
else:
print('\033[F'*nrow)
def my_display(chars):
print(''.join(chars))
return len(chars)
nrow = 0
while True:
my_cls(nrow)
# cassette
res = []
i+=1
if i == 1:
res.append('\n')
res.append(light_grey + ' ■̅̅̅̅̅̅̅̅̅̅̅̅■ \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|###########|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|')
if i % 4 == 0:
res.append(white + ' (/)====(/) ')
elif i % 4 == 1:
res.append(white + ' (-)====(-) ')
elif i % 4 == 2:
res.append(white + ' (\\)====(\\) ')
elif i % 4 == 3:
res.append(white + ' (|)====(|) ')
res.append(light_grey + '|')
res.append(dark_grey + '| \n')
res.append(dark_grey + ' |')
res.append(light_grey + '|############|')
res.append(dark_grey + '|\n')
res.append(light_grey + ' ■____________■ \n')
# green line
res.append(lime + ' ___________________________________\n\n')
# song list
res.append(red + ' # NAME TIME\n')
nrow = my_display(res)
time.sleep(0.4)

Trouble getting text in to an email

I'm trying to send an email to someone with information I've scraped from the web but I can't get the contents to send. I keep receiving empty emails. Any help would be great. I've tried all sorts of different numbers of ' and +s and i can't figure it out.
def singaporeweather():
singaporehigh=singapore_soup.find(class_='tab-temp-high').text
singaporelow=singapore_soup.find(class_='tab-temp-low').text
print('There will be highs of ' + singaporehigh + ' and lows of ' +
singaporelow + '.')
def singaporesuns():
singaporesunsets=singapore_soup.find(class_='row col-sm-5')
suns_singapore=singaporesunsets.find_all('time')
sunset_singapore=suns_singapore[1].text
sunrise_singapore=suns_singapore[0].text
print('Sunrise: ' + sunrise_singapore)
print('Sunset: ' + sunset_singapore)
def ukweather():
ukhigh= uk_soup.find('span', class_='tab-temp-high').text
uklow= uk_soup.find(class_='tab-temp-low').text
print('There will be highs of ' + ukhigh + ' and lows of ' + uklow +
'.')
def uksuns():
uk_humid = uk_soup.find('div', class_='row col-sm-5')
humidity=uk_humid.find_all('time')
sunrise_uk=humidity[0].text
sunset_uk= humidity[1].text
print('Sunrise: '+str(sunrise_uk))
print('Sunset: '+str(sunset_uk))
def ukdesc():
uk_desc=uk_soup.find('div',class_='summary-text hide-xs-only')
uk_desc_2=uk_desc.find('span')
print(uk_desc_2.text)`enter code here`
def quotes():
quote_text=quote_soup.find(class_='b-qt qt_914910 oncl_q').text
author=quote_soup.find(class_='bq-aut qa_914910 oncl_a').text
print('Daily quote:\n' + '\"'+quote_text +'\"'+ ' - ' + author +'\n')
def message():
print('Subject:Testing\n\n')
print(('Morning ' +
nameslist[random.randint(1(len(nameslist)-1))]).center(30,'*'),
end='\n'*2)
quotes()
print('UK'.center(30,'_') + '\n')
ukweather()
ukdesc()
uksuns()
print('\n' + 'Singapore'.center(30,'_') + '\n')
singaporeweather()
singaporedesc()
singaporesuns()
smtpthing.sendmail('XXX#outlook.com', 'XXX#bath.ac.uk', str(message()))
In your functions, instead of printing the results to the console, you should use return statements so that you can use the function's result in your main program. Otherwise, message() is returning null, which is why your email is empty (the main program cannot see message()'s result unless it is returned).
Try something like:
def singaporeweather():
singaporehigh=singapore_soup.find(class_='tab-temp-high').text
singaporelow=singapore_soup.find(class_='tab-temp-low').text
return 'There will be highs of ' + singaporehigh + ' and lows of ' +
singaporelow + '.'
By using a return statement like this one, you will be able to use singaporeweather()'s result in your main program, e.g.:
var result = singaporeweather()
Using returns in the rest of your methods as well, you will be able to do the following in your function message():
def message():
body = "" #your message
body += 'Subject:Testing\n\n'
body += ('Morning ' + nameslist[random.randint(1(len(nameslist)-1))]).center(30,'*')
body += quotes()
body += 'UK'.center(30,'_') + '\n'
+ ukweather()
+ ukdesc()
+ uksuns()
+ '\n' + 'Singapore'.center(30,'_') + '\n'
+ singaporeweather()
+ singaporedesc()
+ singaporesuns()
#finally, don't forget to return!
return body
Now you are returning body, now you can use message()'s result in your main program to send your email correctly:
smtpthing.sendmail('XXX#outlook.com', 'XXX#bath.ac.uk', str(message()))

syntax error for writing a variable in a script

dump.pbd='pdb' + pdbFile + '_' + 'res' + residMin + '_' residMax + '.pdb'
the program keep giving me syntax error when I run it.
import re
import sys
import os
import time
from sys import argv
import xmltodict
if len(sys.argv) < 3:
message = '\n Get protein file in the form of pdf file from pdb website. \n\n Usage: '+sys.argv[0] + ' [4-letter PDBid] [resid range] \n' + ' Example: ' + sys.argv[0] + ' 2rh1 53-71\n' + ' Output File: pdb2rh1_res53-71.pdb'
print (message)
exit()
pdbID=sys.argv[1]
residRange=sys.argv[2]
residData=residRange.split('-')
residMin=int(residData[0])
residMax=int(residData[1])
twoletter=pdbID[1:3]
xmlfile=pdbID + '.xml'
pdbgzfile=pdbID + '.pdb.gz'
pdbFile=pdbID+'.pdb'
dump.pbd='pdb' + pdbFile + '_' + 'res' + residMin + '_' residMax + '.pdb'
wgetcom='wget https://files.rcsb.org/view/'+pdbFile+' -O '+pdbFile
print(wgetcom)
os.system(wgetcom)
f = open (pdbFile,'r')
k = 0
rc = 0
data = f.readlines()
g = open (dump.pdb, 'w')
for linedata in data:
line=linedata.strip()
words = line.split()
if(words[0] == 'ATOM'):
k=k+1
words[5]=int(line[22:26].strip())
if(words[5] in range(residMin,residMax+1)):
g.write(linedata)
for i in words:
if(i=='CA'):
rc = rc+1
print(rc)
the code is not working because it is giving me a syntax error for line number 22 that states dump.pbd='pdb' + pdbFile + '' + 'res' + residMin + '' residMax + '.pdb'. so can you please help me with that?
Thanks so much on advance!
You've forgotten to add a + sign.
This line should work: dump.pbd='pdb' + pdbFile + '' + 'res' + residMin + '' + residMax + '.pdb'
There must be a + sign between '_' and residMax as this is the Python concatenating strings syntax.

Scripting Python for Linux commands

I have a question. I have been really trying to learn Python. For a project, I want to make an ncurses GUI for my backup server. My backup server runs rdiff-backup, and I want to have the ncurses take in variable names and plug them into my script. I have been trying to do a lot of reading so I don't ask dumb questions.
Here is my function for running the script:
def runScript():
# Cannot concatenate 'str' and 'list' objects
#script = rdiff + rdiffArgs
script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \
+ ' ' + clientName + '#' + clientHost + '::' + clientDir \
+ ' ' + serverDir
os.system(script)
What I originally thought would be neat was to add all the variables into a list, so I could just run say
script = rdiff + rdiffArgs
Is there a better way to do this without all the space concatenation?
Thanks for your assistance
EDIT: Let me post the whole script so far. I wasn't very clear and I really appreciate your help and patience
#!/usr/bin/env python
import os
import smtplib
# Global variables
rdiff = '/usr/bin/rdiff-backup'
rdiffVerbosity = '-v5'
rdiffStatistics = '--print-statistics'
emailSmtp = 'smtp.gmail.com'
smtpPort = '465'
emailUsername = 'reports'
emailPassword = '3kc9dl'
emailTo = 'user#domain.com'
emailFrom = 'internal#domain.com'
serverName = 'root'
serverHost = 'SV-Datasafe'
serverDir = '/srv/backup/SV-Samba01'
clientName = 'root'
clientHost = 'SV-Samba01'
clientDir = '/srv'
rdiffArgs = rdiffArgs = [rdiffVerbosity, rdiffStatistics, \
clientName + '#' + clientHost + '::' \
+clientDir + ' ' + serverDir]
time = ''
dateStamp = datetime.now()
def sendEmail():
subject = dateStamp + clientName
body = clientDir + ' on ' + clientHost + ' backed up to ' + serverName + \
' in the directory ' + serverDir + ' on ' + dateStamp
message = """\
From: %s
To: %s
Subject: %s
%s
""" % (emailFrom, emailTo, subject, body)
deliverEmail = smtplib.SMTP(emailSmtp, port=smtpPort)
deliverEmail.login(emailUsername, emailPassword)
def runScript():
# Cannot concatenate 'str' and 'list' objects
#script = rdiff + rdiffArgs
script = rdiff + ' ' + rdiffVerbosity + ' ' + rdiffStatistics \
+ ' ' + clientName + '#' + clientHost + '::' + clientDir \
+ ' ' + serverDir
os.system(script)
# TODO:: Logging
you can use format specifiers
def runScript():
script = "%s %s %s#%s %s::%s %s" %(rdiff,rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir)
os.system(script)
or say your rdiffArgs is already in a list
rdiffArgs = [rdiffVerbosity,rdiffStatistics,clientName,clientHost,clientDir,serverDir]
you can join them with a space
rdiffArgs = ' '.join(rdiffArgs)
lastly, just so you might want to know, you can import rdiff in your script , since rdiff-backup is written in Python
from rdiff_backup.Main import Main as backup
task=['/etc', '/tmp/backup']
backup(task)
the above backs up /etc/ to /tmp/backup. That way, you don't have to make system call to rdiff-backup. Of course, this is up to you. making system call is sometimes easier
try to use subprocess module and pass arguments as list e.g.
client = clientName + '#' + clientHost + '::' + clientDir
cmd = [rdiff, rdiffVerbosity, rdiffStatistics, client , serverDir]
p = Popen(cmd ", shell=True)
print os.waitpid(p.pid, 0)[1]
or if have args already as list use something like this
cmd = [rdiff] + args
You join paths using os.path.join
You concatenate strings like so: "".join(['a', 'b']) or ", ".join(['c', 'd'])
Which part is difficult? I am not sure I understand the question 100%
Is this it?
script = rdiff + " ".join(rdiffArgs)

Categories

Resources