writing to text file within thread python - python

I am trying to run this script in the background of a flask web app. This is an example code of what I am trying to do without the PIR sensor connected. I am essentially running this infinite loop and would like to write to a file periodically within a thread. I do not understand what is wrong and why the file is empty.
import threading
from datetime import datetime as dt
from time import sleep
global_lock = threading.Lock()
def write_to_file():
while global_lock.locked():
continue
def motionlog():
global_lock.acquire()
f = open("motionlog.txt", mode = "w")
f.write("Motion Detection Log" + "\n")
while True:
#output_lock.acquire()
f.write("Motion Detected at "+ dt.now().strftime("%m_%d_%Y-%I:%M:%S_%p")+"\n")
print('Motion Detected')
sleep(5)
global_lock.release()
t1 = threading.Thread(target=motionlog)
t1.start()
t1.join()

Related

variable import to another file not working properly

I'm cannot pass the result of a function i have at one file, it just gets stuck at execution.
How do i properly address this?
import time
import chess
import chesspl
import threading
from stockfish import Stockfish
stockfish = Stockfish(path="sf.exe")
board = chess.Board()
time.sleep(0.1)
mdta = chesspl.moves
pmv = []
print(mdta)
def get_best_move():
global bmove
while True:
mdta = chesspl.moves
time.sleep(2)
if len(mdta) > len(pmv):
for move in mdta[len(pmv):]:
board.push_san(move)
pmv.append(move)
s=str(board.fen)[34:-3]
stockfish.set_fen_position(s)
bmove=stockfish.get_best_move()
bmove = ''
thread = threading.Thread(target=get_best_move)
thread.start()
This is the file that generates the variable.
On the import file
import firstfile
import time
time.sleep(2)
best_move =firstfile.bmove
time.sleep(2)
print(best_move)
I have tried Importing the variable directly and adding a thread to it but wont work.

How to stop continuous_threading in python

I am working on a project, where I have to read values from serial port and display them on tkinter GUI. I am using continous threading module of python. I am using a continous thread to read the data on serial port continously after every 0.5s, but now i want to stop this continous thread. So how should I stop it ?
This is the function which I am calling when a checkbutton is presssed
def scan():
print("in scan")
btn1_state = var1.get()
print("Scan: %d"%btn1_state)
t1 = continuous_threading.PeriodicThread(0.5, readserial)
if(btn1_state == 1):
t1.start()
else:
print("entered else ")
t1.stop() #I am using stop() but the thread doesn't stop
Please Help
The problem is likely that you are using a blocking read function in your readserial function. It needs a timeout. I can reproduce with this code:
import time
import continuous_threading
time_list = []
def save_time():
while True:
time.sleep(1)
time_list.append(time.time())
th = continuous_threading.PeriodicThread(0.5, save_time)
th.start()
time.sleep(4)
th.join()
print(time_list)
This never exits.
Modified from the examples.
Since continuous_threading expects it's event loop to be in control, it never gets to the stop event.

Run same function simultaneously with different arguments

I have been attempting to make a small python program to monitor and return ping results from different servers. I have reached a point where pinging each device in the sequence has become inefficient and lacks performance. I want to continuously ping each one of my targets at the same time on my python.
What would the best approach to this be? Thanks for your time
def get_latency(ip_address, port):
from tcp_latency import measure_latency
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
latency = str(measure_latency(host=ip_address, port=port, runs=1, timeout=1))[1:-1]
#add to table and upload to database function()
ip_address_list = [('google.com', '80'), ('bing.com', '80')]
#Problem
#run function simultaneously but with different arguments
get_latency(ip_address_list[0][0], ip_address_list[0][1])
get_latency(ip_address_list[1][0], ip_address_list[1][1])
For loop does not run in simultaneous.
You can use threading to run in simultaneous.
see this:
import threading
def get_latency(ip_address, port):
from tcp_latency import measure_latency
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%Y-%m-%d %H:%M:%S")
latency = str(measure_latency(host=ip_address, port=port, runs=1, timeout=1))[1:-1]
#add to table and upload to database function()
ip_address_list = [('google.com', '80'), ('bing.com', '80')]
#adding to thread
t1 = threading.Thread(target=get_latency, args=(ip_address_list[0][0], ip_address_list[0][1]))
t2 = threading.Thread(target=get_latency, args=(ip_address_list[1][0], ip_address_list[1][1]))
# starting thread
t1.start()
t2.start()
# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
# both threads completely executed
print("Done!")
You can use a for loop for this purpose.
Something like this:
for i in range(len(ip_address_list)):
print(get_latency(ip_address_list[i][0], ip_address_list[i][1]))
Also you should define the modules before writing the function and return the results
from tcp_latency import measure_latency
from datetime import datetime
def get_latency(ip_address, port):
.
.
.
return results

Run function every 5 minutes while running main program

I want a function to run every 5 minutes while the main program is still running.
I've found multiple posts on how to make a function run every few seconds but they don't seem to work for me.
This is my program:
from Read import getUser, getMessage
from Socket import openSocket, sendMessage
from Initialize import joinRoom, Console
from question import query_yes_no
from Settings import AIDENT
import string
import sched, time
import urllib.parse
import requests
import subprocess
import sys
import os
s = openSocket()
joinRoom(s)
while True:
try:
try:
readbuffer = s.recv(1024)
readbuffer = readbuffer.decode()
temp = readbuffer.split("\n")
readbuffer = readbuffer.encode()
readbuffer = temp.pop()
except:
temp = ""
for line in temp:
if line == "":
break
if "PING" in line and Console(line):
msgg = (("PONG tmi.twitch.tv\r\n").encode())
print(msgg)
s.send(msgg)
break
user = getUser(line)
message = getMessage(line)
print (user + " > " + message)
PMSG = "/w " + user + " "
if "!ping" in message:
sendMessage(s, "PONG ( i'm working fine )")
except:
pass
I need to run sendMessage() function every 5 minutes without interrupting main program.
You have use threading in case , where your main method will keep on exeuting in separate thread and repeater function will execute after every nth sec
sample code would be like this :
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()
Give it a try by your self .
You should be using threads. This will create a thread, which simply executes your code and sleeps for 5 min. Instead of running your function, run the last two commands to create the thread and start it.
import threading
import time
def pong():
while True:
sendMessage(s, "PONG ( i'm working fine )")
time.sleep(300)
t = threading.Thread(target=pong, args=(,))
t.start()

Updating lines in terminal while doing other stuff on the last one in Python?

I am trying to write a Python program that tracks the prices of the stock market and outputs it to the user refreshing the same line through stderr, that's a simplified version of the code (used randint just to check that the program was doing something):
import random
import schedule
import time
import sys
def printran():
a = "\rFirst Line is: " + str(random.randint(1,10))
sys.stderr.write(a)
schedule.every(2).seconds.do(printran)
while True:
schedule.run_pending()
time.sleep(1)
My problems are:
a) How do I "refresh"the console output on multiple lines?
I tried stuff like:
a = "\rFirst Line is: " + str(random.randint(1,10)) + "\n\rSecond Line is: " + str(random.randint(2,20))
but the output is a mess and obviously the \n command will always generate a new line
b) since the while function doesn't really end I cannot do other stuff, do I need to use multithreading?
c) finding a solution that is as much as possible easy, portable and OS agnostic (must work on Linux, OSX, Win).
import random
import schedule
import threading
import time
def printran():
print("First Line is: " + str(random.randint(1,10)))
def run():
schedule.every(2).seconds.do(printran)
while True:
schedule.run_pending()
time.sleep(1)
if __name__ == "__main__":
t = threading.Thread(target=run)
t.start()
Also, you can use APScheduler
But in the following code sched.start() won't wait and it will stop with main.
import random
from apscheduler.schedulers.background import BackgroundScheduler
import time
def printran():
print("First Line is: " + str(random.randint(1,10)))
if __name__ == "__main__":
sched = BackgroundScheduler()
sched.add_job(printran, 'interval', seconds=2)
sched.start()
# wait 10 seconds and exit
time.sleep(10)
Should be crossplatform (I didn't check on Win, Mac, but it works on linux)

Categories