Python loop issue for Binance API - python-3.x

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

Related

Program Stops Without Reason (RasPi, Linux, Python3)

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.

Is there a way to save a file that is written by a python script, if the python script is killed before it is completed?

I have been running a web scraper script written in Python. I had to terminate the Python script because of an issue with my internet connection. At the time, the script has run for almost 2-3 hours. I used a for loop to write the data into a CSV file. I had used 'file.close()' to save the file once the for loop is over; but as I terminated the program early, my time of two hours have wasted.
Once I tried to delete the newly created CSV file(its size is 0kB), it is said 'The action can't be completed because the file is open in Python'. I thought that all the data I extracted is now on the RAM.(maybe that's why I don't get the permission to close the 0kB sized CSV file?)
So, is there any way to access those data and write the data into the above-mentioned CSV file? (Otherwise, I will have to run to the same program for another two hours and wait for the results)
Here's my code!
#! python3.8
fileCsv = open('newCsv.csv','w',newline='')
outputWriter = csv.writer(fileCsv)
for i in range(100,000): # whatever range
num, name = 10000, 'hello' # The data extracted from the website
ourputWriter.writerow([num,name])
time.sleep(1)
fileCsv.close() # My program was terminated before this line, in the for loop
Using with should help here.
with open('newCsv.csv','w') as wr:
for i in range(100,000): # whatever range
num, name = 10000, 'hello' # The data extracted from the website
wr.writerow([num,name])
time.sleep(1)

Python Wait /Pause until specific Time... And stop at end of schedule

With the following code, I am trying to run program between 9:15am and 17:30pm;; and it should esentially stop at 17:30pm and then, again wait until next day 9:15am without ending itself.
### For experiment sake, I have made the datetime.time(20,26) and (20,28)...
### You may change it to any of the hours and mins of your time...
### But I am hoping it would start and stop between those times please...
import time, datetime, pause
def printing_something():
print("Hello World") # you can add any func here
day_of_week = datetime.date.today().weekday() # (0=Monday), (5=Saturday) and (6=Sunday)
timer_now = datetime.datetime.now().time()
while True:
if day_of_week < 5 and (timer_now > datetime.time(20,26) and timer_now < datetime.time(20,28)):
time.sleep(5 - time.time() % 5)
printing_something()
else:
pause.until(datetime(9, 15, 0))
Firstly...
The problem with this code is it doesn't do anything at the start of the time, in case I start like an hour before the schedule... It shows it is running, but when the exact time comes(for example 20:26hours, like in code above), it just doesn't print anything that it is asked.
Secondly...
If I happen to start inside the scheduled time, then it will start printing, but then it doesn't stop the printing at the end of 20:28hours, like it is scheduled to stop...
So, the question again...
If I start the program anytime in day or night, and leave it... How to make it execute at 9:15am and make it stop at 17:30pm... and then allow the program to keep running(but paused) until the next day 9:15am....
(For more clarity, I was trying to run in the market hours only, between Monday to Friday... and parts of the code may not be relevant, but I am a rookie in python, sorry)
As there has not been much help from here, I have worked out a temporary work-around with the below code. I manually start the program execution at the start of the day, and then at 17:30pm, I close the program.
import schedule
import time
def job():
print("I'm working...")
schedule.every(5).minutes.do(job)
schedule.every().day.at("9:15").do(job)
while True:
schedule.run_pending()
time.sleep(1)

How to run infinite-loop python script that includes external .py script that's non-blocking but yet needs a response

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.

Socket stuck usinng python

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()

Resources