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.
Related
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()
i got this code in by googling it and i have tried this code but it plays only songs which we are giving .
i need code to play all the songs in the folder,one by one until i stops.
import time
from win32com.client import Dispatch
songs_dir='G:\songs\My Fav'
songs = os.listdir(songs_dir)
mp = Dispatch("WMPlayer.OCX")
tune = mp.newMedia("{}\\{}".format(songs_dir,songs[2]))
mp.currentPlaylist.appendItem(tune)
mp.controls.play()
time.sleep(1)
mp.controls.playItem(tune)
print("Playing music")
a=input("Press Enter to stop playing")
mp.controls.stop()```
Remove input because it pauses your script
Use time.duration to wait for the song complete
Code:
import time
import glob
from win32com.client import Dispatch
for file in glob.glob(r'C:\Users\MUSIC\*'):
print(f'Playing: {file}')
mp = Dispatch('WMPlayer.OCX')
tune = mp.newMedia(file)
mp.currentPlaylist.appendItem(tune)
mp.controls.play()
time.sleep(1)
mp.controls.playItem(tune)
time.sleep(int(tune.duration))
Need help with how to modify/fix code to allow me to control what is occurring in a process. I have looked around and read I need to either make a global variable which the process can read or use an event function to trigger the process. Problem though is I don't know how to implement them in a class function. I thought that if I followed pyimagesearch code that it would work but it appears that it only works with the threading module and not the multiprocessing module.
import RPi.GPIO as GPIO
from RPI.GPIO import LOW,OUT,HIGH,BCM
import multiprocessing as mp
import time
class TestClass():
def __init__(self,PinOne=22,PinTwo=27):
self.PinOne = PinOne
self.PinTwo = PinTwo
self.RunningSys = True
GPIO.setmode(BCM)
GPIO.setup(PinOne,OUT)
GPIO.output(PinOne,LOW)
GPIO.setup(PinTwo,OUT)
GPIO.output(PinTwo,LOW)
def Testloop(self):
while self.RunningSys:
GPIO.output(PinOne,HIGH)
GPIO.output(PinTwo,HIGH)
time.sleep(1)
GPIO.output(PinOne,LOW)
GPIO.output(PinTwo,LOW)
GPIO.output(PinOne,LOW)
GPIO.output(PinTwo,LOW)
def StopPr(self):
self.RunningSys = False
def MProc(self):
MPGP = mp.process(target=TestClass().Testloop())
MPGP.start()
MPGP.join()
In a separate script
From testfile import TestClass
import time
TestClass().MProc()
time.sleep(4)
TestClass().StopPr()
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()
i am new to python and just now started developing an linux application automation.
scenario i am trying is
thread.py --- will invoke all primary device threads and load test from testcase
admincase.py --- hold my tests for the case..
what i am unable to do is i want to pass certain objects from thread.py to admincase.py when loading the test. how do i do that..
object which i am tryin to pass is (EppQueue)
thread.py code
import threading
import sys
import time
import logging
import os
import Queue
from EPP import EPP
import ldtp
import ldtputils
from functions import functions
from admincases import admincases
import unittest
#logging.basicConfig(level=logging.DEBUG,
# format='(%(threadName)-10s) %(message)s',
# )
class inittest(unittest.TestCase):
global fun
global EppQueue
global window_name
def cleanup(epp_port):
if os.path.exists(epp_port):
os.unlink(epp_port)
def start_threads(EppQueue,server_ip,epp_port):
epp = EPP
EPP1 = threading.Thread(name='EPP', target=epp, args=(server_ip,54321,epp_port,EppQueue,))
EPP1.setDaemon(True)
EPP1.start()
return epp
fun = functions()
EppQueue = Queue.Queue(1)
server_ip ='192.168.10.125'
epp_port='/dev/ttyS17'
print "Starting"
cleanup(epp_port)
print "Clean up Over"
epp = start_threads(EppQueue,server_ip,epp_port)
raw_input("###### Please Start the main appilcation in the ATM and hit a KEY to continue ############")
check = 0
while check == 0:
window_name = fun.start_up_verify('atm_main_app')
if any(window_name):
check = 1
else:
check = 0
if not any(window_name):
print "Please start the application and run the test"
sys.exit(0)
else:
print window_name
print "SYSTEM IS READY TO PERFORM TEST"
raw_input("###### HIT ANY KEY TO START UNIT TEST ############")
raw_input("kkk")
test = unittest.defaultTestLoader.loadTestsFromName("admincases")
unittest.TextTestRunner(verbosity=2).run(test)
raw_input("keyy")
print "final"
admincase.py code
import unittest
from functions import functions
import time
import Queue
class admincases(unittest.TestCase):
global fun
global EppQueue
global window_name
def test_case_1(self):
print "test case 1"
window_name = 'frmatm_main_app'
fun.send_queue(self.EppQueue,"send_keys,&&&&&")
fun.verify_screen(window_name,"ico0")
fun.send_queue(self.EppQueue,"send_keys,C")
fun.verify_screen(window_name,"ManagementFunctions")
fun.send_queue(self.EppQueue,"send_keys,001234")
fun.verify_screen(window_name,"MainMenu")
fun.send_queue(self.EppQueue,"send_keys,1")
fun.verify_screen(window_name,"Diagnostics")
fun.send_queue(self.EppQueue,"send_keys,1")
fun.verify_screen(window_name,"TerminalStatus")
fun.send_queue(self.EppQueue,"send_keys,2")
time.sleep(10)
fun.send_queue(self.EppQueue,"send_keys,####****")
fun = functions()
#EppQueue = Queue.Queue(1)
Need some assistance on this...