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...
Related
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.
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 have 2 servers in python, I want to mix them up in one single .py and run together:
Server.py:
import logging, time, os, sys
from yowsup.layers import YowLayerEvent, YowParallelLayer
from yowsup.layers.auth import AuthError
from yowsup.layers.network import YowNetworkLayer
from yowsup.stacks.yowstack import YowStackBuilder
from layers.notifications.notification_layer import NotificationsLayer
from router import RouteLayer
class YowsupEchoStack(object):
def __init__(self, credentials):
"Creates the stacks of the Yowsup Server,"
self.credentials = credentials
stack_builder = YowStackBuilder().pushDefaultLayers(True)
stack_builder.push(YowParallelLayer([RouteLayer, NotificationsLayer]))
self.stack = stack_builder.build()
self.stack.setCredentials(credentials)
def start(self):
self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT))
try:
logging.info("#" * 50)
logging.info("\tServer started. Phone number: %s" % self.credentials[0])
logging.info("#" * 50)
self.stack.loop(timeout=0.5, discrete=0.5)
except AuthError as e:
logging.exception("Authentication Error: %s" % e.message)
if "<xml-not-well-formed>" in str(e):
os.execl(sys.executable, sys.executable, *sys.argv)
except Exception as e:
logging.exception("Unexpected Exception: %s" % e.message)
if __name__ == "__main__":
import sys
import config
logging.basicConfig(stream=sys.stdout, level=config.logging_level, format=config.log_format)
server = YowsupEchoStack(config.auth)
while True:
# In case of disconnect, keeps connecting...
server.start()
logging.info("Restarting..")
App.py:
import web
urls = (
'/', 'index'
)
app = web.application(urls, globals())
class index:
def GET(self):
greeting = "Hello World"
return greeting
if __name__ == "__main__":
app.run()
I want to run both together from single .py file together.
If I try to run them from one file, either of the both starts and other one starts only when first one is done working.
How can I run 2 servers in python together?
import thread
def run_app1():
#something goes here
def run_app2():
#something goes here
if __name__=='__main__':
thread.start_new_thread(run_app1)
thread.start_new_thread(run_app2)
if you need to pass args to the functions you can do:
thread.start_new_thread(run_app1, (arg1,arg2,....))
if you want more control in your threads you could go:
import threading
def app1():
#something here
def app2():
#something here
if __name__=='__main__':
t1 = threading.Thread(target=app1)
t2 = threading.Thread(target=app2)
t1.start()
t2.start()
if you need to pass args you can go:
t1 = threading.Thread(target=app1, args=(arg1,arg2,arg3.....))
What's the differences between thread vs threading? Threading is higher level module than thread and in 3.x thread got renamed to _thread... more info here: http://docs.python.org/library/threading.html but that's for another question I guess.
So in your case, just make a function that runs the first script, and the second script, and just spawn threads to run them.
I wrote a simple test program using thread locks. This program does not behave as expected, and the python interpreter does not complain.
test1.py:
from __future__ import with_statement
from threading import Thread, RLock
import time
import test2
lock = RLock()
class Test1(object):
def __init__(self):
print("Start Test1")
self.test2 = test2.Test2()
self.__Thread = Thread(target=self.myThread, name="thread")
self.__Thread.daemon = True
self.__Thread.start()
self.test1Method()
def test1Method(self):
print("start test1Method")
with lock:
print("entered test1Method")
time.sleep(5)
print("end test1Method")
def myThread(self):
self.test2.test2Method()
if __name__ == "__main__":
client = Test1()
raw_input()
test2.py:
from __future__ import with_statement
import time
import test1
lock = test1.lock
class Test2(object):
def __init__(self):
print("Start Test2")
def test2Method(self):
print("start test2Method")
with lock:
print("entered test2Method")
time.sleep(5)
print("end test2Method")
Both sleeps are executed at the same time! Not what I expected when using the lock.
When test2Method is moved to test1.py everything works fine. When I create the lock in test2.py and import it in test1.py everything works fine. When I create the lock in a separate source file and import it both in test1.py and test2.py everything works fine.
Probably it has to do with circulair imports.
But why doesn't python complain about this?
In Python when you execute a python script using $ python test1.py what happen is that your test1.py will be imported as __main__ instead of test1, so if you want to get the lock defined in the launched script you shouldn't import test1 but you should import __main__ because if you do the first one you will create another lock that is different from the __main__.lock (test1.lock != __main__.lock).
So one fix to your problem (which far from being the best) and to see what is happening you can change your 2 script to this:
test1.py:
from __future__ import with_statement
from threading import Thread, RLock
import time
lock = RLock()
class Test1(object):
def __init__(self):
print("Start Test1")
import test2 # <<<<<<<<<<<<<<<<<<<<<<<< Import is done here to be able to refer to __main__.lock.
self.test2 = test2.Test2()
self.__Thread = Thread(target=self.myThread, name="thread")
self.__Thread.daemon = True
self.__Thread.start()
self.test1Method()
def test1Method(self):
print("start test1Method")
with lock:
print("entered test1Method")
time.sleep(5)
print("end test1Method")
def myThread(self):
self.test2.test2Method()
if __name__ == "__main__":
client = Test1()
raw_input()
test2.py:
from __future__ import with_statement
import time
# <<<<<<<<<<<<<<<<<<<<<<<<<<<<< test1 is changed to __main__ to get the same lock as the one used in the launched script.
import __main__
lock = __main__.lock
class Test2(object):
def __init__(self):
print("Start Test2")
def test2Method(self):
print("start test2Method")
with lock:
print("entered test2Method")
time.sleep(5)
print("end test2Method")
HTH,
Using print statements before and after the import statements and printing id(lock) right after it's been created reveals that there are in fact two locks being created. It seems the module is imported twice, and mouad explains in his answer that this is because test1.py is imported first as __main__ and then as test1, which causes the lock to be instantiated twice.
Be that as it may, using a global lock is not a good solution anyway. There are several better solutions, and I think you'll find one of them will suit your needs.
Instantiate the lock as a class variable of Test1, and pass it as an argument to Test2
Instantiate the lock as a normal variable of Test1 in __init__, and pass it as an argument to Test2.
Instantiate the lock in the if __name__ == "__main__" block and pass it to Test1, and then from Test1 to Test2.
Instantiate the lock in the if __name__ == "__main__" block and first instantiate Test2 with the lock, then pass the Test2 instance and the lock to Test1. (This is the most decoupled way of doing it, and I'd recommend going with this method. It will ease unit testing, at the very least.).
Here's the code for the last suggestion:
test1.py:
class Test1(object):
def __init__(self, lock, test2):
print("Start Test1")
self.lock = lock
self.test2 = test2
self.__Thread = Thread(target=self.myThread, name="thread")
self.__Thread.daemon = True
self.__Thread.start()
self.test1Method()
def test1Method(self):
print("start test1Method")
with self.lock:
print("entered test1Method")
time.sleep(1)
print("end test1Method")
def myThread(self):
self.test2.test2Method()
if __name__ == "__main__":
lock = RLock()
test2 = test2.Test2(lock)
client = Test1(lock, test2)
test2.py:
class Test2(object):
def __init__(self, lock):
self.lock = lock
print("Start Test2")
def test2Method(self):
print("start test2Method")
with self.lock:
print("entered test2Method")
time.sleep(1)
print("end test2Method")
As others said, the problem is not in the threading, but in your special case of cyclic imports.
Why special? Because usual workflow (mod1 imports mod2 and mod2 imports mod1) looks like the next:
You want to use module mod1, you imports it (import mod1)
When Python finds it, interpreter adds it to sys.modules and starts code execution
When it reaches line with import mod2, it stops execution of mod1 and starts execution of mod2
When interpreter reaches import mod1 within mod2, it doesn't load mod1 because it was already added to sys.modules
After that (unless some code in mod2 accesses some uninitialized resource from mod1) interpreter finishes execution of mod2 and mod1.
But in your case at step 4. Python executes test1 one more time because there is no test1 in sys.modules! The reason for this is that you didn't imported it in the first place, but run it from a command line.
So, just don't use cyclic imports - as you see it is a real mess.