The code only stops when a keyboardinterrupt is used.
A break was used though I took it out and the adc data was read and then the spi.close was skipped along with the update_sheet("PCEM SHT.1", ADCDATA)
I've tried using a different exception, raise exception based on the number of variables in ADCDATA, but with no effect
# import many libraries
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from oauth2client.service_account import ServiceAccountCredentials
import datetime
import spidev # import the SPI driver
def read_mcp3002(channel):
### Working ADC Code
return adc_data
def update_sheet(sheetname, my_list):
###Working Update google sheet code
try:
while True:
Result=1##3.23#for 3302 [mV]..... Voltage=(High Voltage-Low Voltage)/(2^(# of conversion bits))
voltage1=(read_mcp3002(0))
voltage1k=voltage1*Result
voltage2=(read_mcp3002(1))
voltage2k=voltage2*Result # This one #
ADCDATA += [[voltage1k, voltage2k]]
if len(ADCDATA) == 100000:
#print(ADCDATA)
ADCDATA = []
print("+10000")
except KeyboardInterrupt: # Ctrl-C
spi.close()
def main():
update_sheet("PCEM SHT.1", ADCDATA)
if __name__ == '__main__':
main()
The desired result would be to automatically stop at len(ADCDATA)=100000: if len(ADCDATA)==100000, it would run the code in the If statement, and also execute spi.close() and lastly run through def main()'s update_sheet("PCEM SHT1", ADCDATA).
I was able to deal with my problem by importing sys and placing a system exit(1) at the bottom of the & inside the if len(ADCDATA)==100000
if len(ADCDATA)==100000
print("PCEM DATA")
spi.close()
update_sheet"........")
sys.exit(1)
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.
I make a python script running in the console, and I want to create another console for printing important messages without running another python script to do that.
I first tried to use win32console.AllocConsole() directly, but it got Access is denied
(Seemingly because one process can attach to at most one console according to the docs).
So I tried creating a new process by using multiprocessing :
import sys, os
import win32api, win32con, win32console
import multiprocessing
def ShowConsole():
win32console.FreeConsole()
win32console.AllocConsole()
sys.stdout = open("CONOUT$", "w")
sys.stderr = open("CONOUT$", "w")
print("Test")
os.system("pause")
if __name__ == '__main__':
p = multiprocessing.Process(target=ShowConsole)
p.start()
But when I ran the code in Powershell, it exited directly with no message while no new console is created.
None of the possible solutions I found in stackoverflow works for me. What should I do?
Update: It turns out that it is because multiprocessing.Process fails to call ShowConsole function. I use multiprocessing.dummy.Process as the alternative and it works as expected.
The reason why multiprocessing.Process fails to call target is still unclear.
There's nothing wrong with your example above, it pops the console as shown below. I added a "hello" in the main section to differentiate.
But since you want to values from the first console to the second,
here's a better example. Utilize put/get to pass the information from the first console to the second console.
import win32console
import multiprocessing
import time
def secondconsole(output):
win32console.FreeConsole()
win32console.AllocConsole()
while True:
print(output.get())
if __name__ == "__main__":
output = multiprocessing.Queue()
multiprocessing.Process(target=secondconsole, args=[output]).start()
while True:
print("Hello World")
output.put("Hello to second console") #here you will provide the data to the second console
time.sleep(3) #sleep for 3 seconds just for testing
It looks like the issue might be with the way you are trying to open the console using sys.stdout and sys.stderr. Try using the following code instead:
import sys, os
import win32api, win32con, win32console
import multiprocessing
def ShowConsole():
win32console.FreeConsole()
win32console.AllocConsole()
os.dup2(win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE), sys.stdout.fileno())
os.dup2(win32console.GetStdHandle(win32console.STD_ERROR_HANDLE), sys.stderr.fileno())
print("Test")
os.system("pause")
if __name__ == '__main__':
p = multiprocessing.Process(target=ShowConsole)
p.start()
I need to read data ( lets say pressure) from serial Port Microcontroller by Client Request. I check the tutorial for ROS Services in Python but still my code is not giving the data value to to client. Here first the Service Server Python node
#!/usr/bin/env python3
from __future__ import print_function
import rospy
import numpy as np
from os import system
import time
import threading
import Microcontroller_Manager_Serial as Serial
import IMU_Functions as IMU
import Motors_Functions as Motor
import Pressure_Functions as Pressure
from geometry_msgs.msg import Vector3
import Modem_Functions as Modem
import threading
import time
import serial
import serial.tools.list_ports
from time import sleep
from std_msgs.msg import Float32
from std_msgs.msg import String
from demo_teleop.srv import ImuValue
Communication_Mode_ = 0
def handle_ros_services():
global P0
data_received = Pressure.Pressure_Get_Final_Values(1,1)
print("Server Read Data:")
P0 = (np.int16((data_received[6]<<24) | (data_received[7]<<16) | (data_received[8]<<8) | (data_received[9])))/10000
P=P0
pressure = P/9.81
current_x_orientation_s=pressure
print("Returning ", current_x_orientation_s)
#return ImuValue(current_x_orientation_s)
def ros_serice_server():
#rospy.init_node('ros_serice_server')
s = rospy.Service('imu_value', ImuValue, handle_ros_services)
print("Ready to get_value")
rospy.spin()
if __name__ == '__main__':
rospy.init_node('server_node_f')
Serial.Serial_Port_Standard()
while not rospy.is_shutdown():
try:
print("entering service")
ros_serice_server()
except:
print("pass")
When I call the server I got this output
entering service
Ready to get_value
And here the client node
#!/usr/bin/env python3
from __future__ import print_function
import rospy
import sys
import numpy as np
from os import system
import time
import threading
import Microcontroller_Manager_Serial as Serial
import IMU_Functions as IMU
import Pressure_Functions as Pressure
import time
import serial
import serial.tools.list_ports
from time import sleep
from std_msgs.msg import Float32
from std_msgs.msg import String
from demo_teleop.srv import ImuValue
Communication_Mode_ = 0
def imu_client():
rospy.wait_for_service('handle_ros_services')
print("Request call send")
imu_value = rospy.ServiceProxy('imu_value', ImuValue)
#resp1 = imu_value
#return imu_value.current_x_orientation_s
if __name__ == "__main__":
rospy.init_node('client_node_f')
while not rospy.is_shutdown():
try:
print("entering client")
imu_client()
except:
print("pass")
When i call the client only got
entering client
So means the server never enter the handle_ros_services()and the client never enter imu_client(): functions. What is wrong with the code?
You have the naming wrong when calling wait_for_service. Your service callback is called handle_ros_services but the service name itself is imu_value. Because of this your client will wait forever, because the former service name never actually gets brought up. Instead inside imu_client() you want the line
rospy.wait_for_service('imu_value')
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
sys.dont_write_bytecode = True
import shlex
import subprocess
import SocketServer
sess = []
class TCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
global sess
sess.append(self.request)
ip,port = self.client_address
print "#%d: client %s:%d"%(len(sess),ip,port)
while True:
cmd = self.request.recv(8192)
out = subprocess.check_output(shlex.split(cmd),stderr=subprocess.STDOUT,shell=True)
self.request.send(out)
self.request.close()
class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer): pass
if __name__ == "__main__":
port = 4242
svr = ThreadedTCPServer(("",port),TCPHandler)
print ":%d"%port
svr.serve_forever()
It is much more simple than you think:
class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer): pass
Than you just have to use your new ThreadedTCPServer instead of TCPServer.
For more information you can read some doc.
However in your code you made some mistakes:
The target argument must be a callable object not an "already-called" object.
To handle many requests you need to build a Threads pool. If you only use one thread it does not make any difference if it is the main thread or a "child" thread.
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import sys
sys.dont_write_bytecode = True
import shlex
import subprocess
import SocketServer
sess = []
class TCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
global sess
sess.append(self.request)
ip,port = self.client_address
print "#%d: client %s:%d"%(len(sess),ip,port)
while True:
cmd = self.request.recv(8192)
out = subprocess.check_output(shlex.split(cmd),stderr=subprocess.STDOUT,shell=True)
self.request.send(out)
self.request.close()
class ThreadedTCPServer(SocketServer.ThreadingMixIn,SocketServer.TCPServer): pass
if __name__ == "__main__":
port = 4242
svr = ThreadedTCPServer(("",port),TCPHandler)
print ":%d"%port
svr.serve_forever()
Shouldn't you loop the
server = SocketServer.TCPServer(('',1520), service)
t = Thread(target=server.serve_forever())
t.start()
Just a guess..
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...