I have one query related to socket programming using Python.
I am running while loop upto some specific time but this loop is stuck after once time call and not terminating because the socket is somewhere stuck. I am also closing the socket after using socket every time, but it does not work. My code is given below.
Can anybody help me how to fix this issue without using 'os._exit(0)' because after while loop I need to continue program. I don't want to exist from program. i just want to exit from while loop after specific time....
def received_status_Frame(a,b):
connn,addr=a,b
message=connn.recv(4096).decode()
connn.close()
t=10
while (time.time()-start_time<t):
PORT = 12345
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind(('',PORT))
s.listen()
print ("before the try accept")
conn,address=s.accept()
threading.Thread(target=received_status_Frame,args=(conn,address)).start()
Related
Hi i have 2 python files and first file for data and its working with timer, example first file timer is set for 02/05/2023 - 02:50am and when this date is come this file triggered and opens the order, but 2st file is checks this order status i mean 2st file is only for checks status and if this order succes its print 'SUCCES' and if its not its print 'FAIL'
but it need to open like 2-3 days but its fail and says:
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(54, 'Connection reset by peer'))
i dont want to solve binance problem bec its nearly impossible, i found solution for this i write this command in terminal every time:
while true; do python3 /home/pi/Desktop/EREN/2-SHORTnormal/Loop.py && break; done
'This command help me for if its crash for anything like timestamp, time out or anything its start again '
but every time :(
Im waiting the trigger date (example 02/05/2023-02:50am) and i dont want to wake up for
open termnial write this command bla bla
WHAT I WANT:
I only want these files in one file like when i start the program its wait for trigger date and when its trigger i want it to start other file and if its crash i want to restart this program automatically but not to entire command, only the second one because if its start entire code its wait for trigger again but its cant trigger bec the trigger date it will already be past. How i can do this in python
example if this is my code:
Print('order is sent') #this is first files command and this work good
#and then
while status == succes
Print('order status:',status) #this is second files command
But second part crashes sometimes and i want to re open when it crashes until its status == success but only second part not whole code.
Okey i think i found the solution:
import time
#my 1.Command out the while loop,
while True:
try:
#my 2.Command
continue
except:
print("Program has crashed and restarts in 2 sec.")
time.sleep(2)
continue
if 2.Command is crash its print something and restart program. And 1.Command is run for only 1 time this is what i. want
First, thank for fixing my post. I'm still not sure how to include a sketch. I've been reading posts here for many months, but never posted one before.
My headless RasPi is running two sketches of mine, one reads data from a pm2.5 sensor (PMS7003) and the other is the program listed above that sends information to another Pi, the client, that turns on a pm2.5 capable air filter. (I live in California) The program that reads the PMS7003 sorts the data, called max_index, into one of six categories, 0 thru 5 and saves the current category to a text file. I'm using the 'w' mode during the write operation, so there is only one character in the text file at any time. The server program listed above reads the text file and sends it to a client that turns on the air filter for categories above 2. The client sends the word "done" back to the server to end the transaction.
Until you mentioned it, I didn't realize my mistake, clientsocket.recv(2). I'll fix that and try again.
So, the listener socket should go outside the while loop, leaving the send and receive inside???
Troubleshooting: I start the two programs using nice nohup python3 xxx.py & nice nohup python3 yyy.py. The program that reads the PMS7003 continues running and updating the text file with current category, but the server program falls out of existence after a few days. top -c -u pi reveals only the PMS7003 program running, while the server program is missing. Also, there's nothing in nohup.out or in socketexceptions.txt and I tried looking through system logs in /var/log but was overwhelmed by information and found nothing that made any sense to me.
Since writing to the socketexceptions.txt file is not in a try/except block, the crash might be happening there.
import socket
import time
index = " "
clientsocket = ""
def getmaxindex():
try:
with open('/home/pi/pm25/fan.txt','r')as f:
stat = f.read() #gets max_index from pm25b.py
return(stat)
except:
with open("/home/pi/pm25/socketexceptions.txt",'a')as f:
f.write("Failed to read max index")
def setup(index):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
s.bind(("192.168.1.70", 5050))
except:
with open("/home/pi/pm25/socketexceptions.txt",'a')as f:
f.write("Failed to bind")
try:
s.listen(1)
clientsocket, address = s.accept()
clientsocket.send(index)
rx = clientsocket.recv(2)
if rx == "done":
clientsocket.close()
except:
with open("/home/pi/pm25/socketexceptions.txt",'a')as f:
f.write("Failed to communicate with flient")
while True:
index = getmaxindex().encode('utf-8')
setup(index)
time.sleep(5)
enter code here
It is unknown what program is supposed to do and where exactly you run into problems, since there is only a code dump and no useful error description (what does "stop" mean - hang or exit, where exactly does it stop). But the following condition can never be met:
rx = clientsocket.recv(2)
if rx == "done":
The will receive at most 2 bytes (recv(2)) which is definitely not enough to store the value "done".
Apart from that it makes not real sense to recreate the same listener socket again and again, just to accept a single client and exchange some data. Instead the listener should only be created once and multiple accept should be called on the same listener socket, where each will result in a new client connection.
I'm developing a Python code that can run two applications and exchange information between them during their run time.
The basic scheme is something like:
start a subprocess with the 1st application
start a subprocess with the 2nd application
1st application performs some calculation, writes a file A, and waits for input
2nd application reads file A, performs some calculation, writes a file B, and waits for input
1st application reads file B, performs some calculation, writes a file C, and waits for input
...and so on until some condition is met
I know how to start one Python subprocess, and now I'm learning how to pass/receive information during run time.
I'm testing my Python code using a super-simple application that just reads a file, makes a plot, closes the plot, and returns 0.
I was able to pass an input to a subprocess using subprocess.communicate() and I could tell that the subprocess used that information (plot opens and closes), but here the problems started.
I can only send an input string once. After the first subprocess.communicate() in my code below, the subprocess hangs there. I suspect I might have to use subprocess.stdin.write() instead, since I read subprocess.communicate() will wait for the end of the file and I wish to send multiple times different inputs during the application run instead. But I also read that the use of stdin.write() and stdout.read() is discouraged. I tried this second alteranative (see #alternative in the code below), but in this case the application doesn't seem to receive the inputs, i.e. it doesn't do anything and the code ends.
Debugging is complicated because I haven't found a neat way to output what the subprocess is receiving as input and giving as output. (I tried to implement the solutions described here, but I must have done something wrong: Python: How to read stdout of subprocess in a nonblocking way, A non-blocking read on a subprocess.PIPE in Python)
Here is my working example. Any help is appreciated!
import os
import subprocess
from subprocess import PIPE
# Set application name
app_folder = 'my_folder_path'
full_name_app = os.path.join(app_folder, 'test_subprocess.exe')
# Start process
out_app = subprocess.Popen([full_name_app], stdin=PIPE, stdout=PIPE)
# Pass argument to process
N = 5
for n in range(N):
str_to_communicate = f'{{\'test_{n+1}.mat\', {{\'t\', \'y\'}}}}' # funny looking string - but this how it needs to be passed
bytes_to_communicate = str_to_communicate.encode()
output_communication = out_app.communicate(bytes_to_communicate)
# output_communication = out_app.stdin.write(bytes_to_communicate) # alternative
print(f'Communication command #{n+1} sent')
# Terminate process
out_app.terminate()
I have two .py scripts. One is a infinite-loop(infinite.py) and the other is a test order on a website(order.py).
I need to execute order.py externally for x. I need this to be non blocking so that my infinite loop can keep checking the other items to see if I need to run order.py for the next "x" that gets popped out from list. The problem is that order.py takes 2 minutes to complete and I need a return of some kind to perform some logic that states if the order was successful, to add x back to list. I do not want "x" to be back in list yet or else it will try to perform another order.py on the same item from list.
I have tried to use subprocess.Popen and call but I can't seem to get them to work. I can either get it to run externally and be non-blocking but I won't be able to get my response from order.py or I get order.py to run but the infinite.py is waiting for order.py to finish before continuing with loop. I have also tried threading as well
Here is the structure of my code.
list = ["item1", "item2", "item3", "item4"]
while True:
x = list.pop(0)
#Performs a simple check 1
if check is True:
#Performs check 2
if check2 is True:
# This is the section I need help with.
# I need to execute order.py and wait for a response while this
# infinite loop keeps going
if order.py is successful:
list.append(x)
else:
print("Problem with order.py")
list.append(x)
else:
list.append(x)
time.sleep(30)
pass
else:
list.append(x)
time.sleep(30)
pass
So after asking a few people I realized what I am trying to do will never work. An example that explained to me was imagine a hand of poker where the current hand is no finished so you do not know the results of your earning before placing a new bet with your current chips. I am closing this post.
Well~ briefly decribe
I'm working on LineBot which set on Heroku
Main program is already done
And now working on it's function which may need sub program
1.
My sub program use timer which runs every 20 seconds
Mainly use to detect newest earthquake info publish by government
and send to every user directly
I hope it can automatically send some result(time infomation) to my Main program in every 20 seconds (that's why I use Timer)
Is it possible?
(I can't use timer in Main program once I run other function Timer may stop...)
2.If it's possible how do I set or use my Sub program on Heroku?? (or maybe on other site which can help it auto run and send result to my Main program)
3.Can anyone teach me(or give me links) how to link two program together
ex:
A.py as Main
B.py as Sub
What should I do on B.py (ex: the form of it's result) so I can return results to A.py
Thanks a lot !!!
sub program code
from datetime import datetime
from threading import Timer
def printTime(inc):
dt = datetime.now()
m=dt.strftime('%m')
d=dt.strftime('%d')
H=dt.strftime('%H')
M=dt.strftime('%M')
print(m+d+H+M)
t = Timer(inc, printTime, (inc,))
t.start()
printTime(20)