我希望每次抛出502 HTTP错误或Floodwaiterror之类的异常时重新启动循环或继续,但我不知道或不知道该怎么做
代码:
//FUNCTION FROM LIBRARY
// get GPS information
bool getGPS(float *lat, float *lon, float *speed=0, float *alt=0, float *course=0, int *vsat=0, int *usat=0) {
//String buffer = "";
bool fix = false;
sendAT(GF("+CGNSINF"));
if (waitResponse(GF(GSM_NL "+CGNSINF:")) != 1) {
return false;
}
stream.readStringUntil(','); // mode [GNSS off=0, GNSS on=1]
if ( stream.readStringUntil(',').toInt() == 1 ) fix = true;
stream.readStringUntil(','); //utctime yyyyMMddhhmmss.sss
*lat = stream.readStringUntil(',').toFloat(); //lat ±dd.dddddd
*lon = stream.readStringUntil(',').toFloat(); //lon ±ddd.dddddd
if (alt != NULL) *alt = stream.readStringUntil(',').toFloat(); //altitude metere
if (speed != NULL) *speed = stream.readStringUntil(',').toFloat(); //speed Km/hour [0,999.99]
if (course != NULL) *course = stream.readStringUntil(',').toFloat(); //course over ground degrees [0,360.00]
stream.readStringUntil(',');//Fix mode [0,1,2]
stream.readStringUntil(',');//Reserved1
stream.readStringUntil(',');//HDOP [0,99.9]
stream.readStringUntil(',');//PDOP [0,99.9]
stream.readStringUntil(',');//VDOP [0,99.9]
stream.readStringUntil(',');//Reserved2
if (vsat != NULL) *vsat = stream.readStringUntil(',').toInt(); //viewed satelites
if (usat != NULL) *usat = stream.readStringUntil(',').toInt(); //used satelites
stream.readStringUntil(',');//GLONASS Sats used
stream.readStringUntil(',');//Reserved3
stream.readStringUntil(',');//C/N0 max (dBHz 0-55)
stream.readStringUntil(',');//HPA (meters [0,9999.9])
stream.readStringUntil(',');//VPA (meters [0,9999.9])
stream.readStringUntil('\n');
waitResponse();
return fix;
}
//CALL FROM CODE
gps_fixstatus = modem.getGPS(&gps_latitude, &gps_longitude, &gps_speed, &gps_altitude, &gps_course, &gps_view_satellites, &gps_used_satellites);
if ( gps_fixstatus ) {
gps_altitude=gps_altitude*3.2808;
sprintf(payload, "{\"lat\":%8f,\"long\":%8f,\"speed\":%2f,\"head\":%2f,\"alt\":%2f}", gps_latitude,gps_longitude, gps_speed, gps_course, gps_altitude); //JSON-ify
SerialMon.println(payload); //JSON object
}
在每个异常中关闭循环的异常输出
Serial.print(TinyGPSplus.location.lat())
我还尝试在每个异常(loop.close)中关闭循环
import time
from telethon import TelegramClient,errors
from telethon.tl.functions.photos import UploadProfilePhotoRequest
import os
import urllib.request
import urllib.error
import asyncio
from datetime import datetime
import datetime
api_id = XXXXXX
api_hash = 'XXXXXXXXXXXXXXXX'
client = TelegramClient('Test_Session', api_id, api_hash)
client.start()
async def Change_Photo():
try:
while True:
time.sleep(3)
if os.path.exists("cat.jpg"):
os.remove("cat.jpg")
if os.path.exists("cat"):
os.remove("cat")
urllib.request.urlretrieve("https://cataas.com/cat", "cat")
os.rename('cat', 'cat.jpg')
await client(UploadProfilePhotoRequest(await client.upload_file(r"C:\Users\localhost\PycharmProjects\Scripts Python\Telethon\cat.jpg")))
now = datetime.datetime.now()
os.remove("cat.jpg")
print("Changed Photo:", now.strftime("%Y-%m-%d %H:%M:%S"))
except errors.FloodWaitError as e:
print('Have to sleep', e.seconds, 'seconds')
await asyncio.sleep(e.seconds)
except urllib.error.HTTPError as e:
if e.code == 502:
print("HTTP error 502... Trying again")
loop = asyncio.get_event_loop()
loop.run_until_complete(Change_Photo())
loop.close()
但是其中一个可行:
Changed Photo: 2019-05-03 14:48:40
Have to sleep 495 seconds
Task was destroyed but it is pending!
task: <Task pending coro=<UpdateMethods._dispatch_update() running at C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\client\updates.py:252>>
C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py:609: RuntimeWarning: coroutine 'UpdateMethods._dispatch_update' was never awaited
self._ready.clear()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Task was destroyed but it is pending!
task: <Task pending coro=<Connection._send_loop() running at C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\connection\connection.py:131> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002BFDB114DC8>()]>>
Task was destroyed but it is pending!
task: <Task pending coro=<Connection._recv_loop() running at C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\connection\connection.py:149> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002BFDB06E318>()]>>
Task was destroyed but it is pending!
task: <Task pending coro=<MTProtoSender._send_loop() running at C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\mtprotosender.py:378> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002BFDB114A68>()]>>
Task was destroyed but it is pending!
task: <Task pending coro=<MTProtoSender._recv_loop() running at C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\mtprotosender.py:416> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002BFDB114C48>()]>>
Task was destroyed but it is pending!
task: <Task pending coro=<UpdateMethods._update_loop() running at C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\client\updates.py:213> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0x000002BFDB114EE8>()]>>
Exception ignored in: <coroutine object Connection._send_loop at 0x000002BFDB0F48C8>
Traceback (most recent call last):
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\connection\connection.py", line 141, in _send_loop
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\connection\connection.py", line 96, in disconnect
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 688, in call_soon
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 480, in _check_closed
RuntimeError: Event loop is closed
Exception ignored in: <coroutine object MTProtoSender._recv_loop at 0x000002BFDB0F4BC8>
Traceback (most recent call last):
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\mtprotosender.py", line 416, in _recv_loop
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\site-packages\telethon\network\connection\connection.py", line 119, in recv
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\asyncio\queues.py", line 161, in get
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 688, in call_soon
File "C:\Users\localhost\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py", line 480, in _check_closed
RuntimeError: Event loop is closed
几周前,我对学习python的编码非常陌生,以确保我做得不好,但我找不到什么
答案 0 :(得分:1)
仅是为了完成和描述基本概念: 代替
var timestampData1 = [1555486016,1555486017,1555486018...];
var timestampData2 = [1555486016,1555486017,1555486018...];
var data = [];
data[1] = [];
$.each(timestampData1,function(index,value) {
data[1][value] = 1;
});
data[2] = [];
$.each(timestampData2,function(index,value) {
data[2][value] = 1;
});
console.log(data);
使用
async def important_error_prone_function():
try:
while True:
do_something()
except Error1:
correct_stuff_1()
except Error2:
correct_stuff_2()
然后,您的功能将继续运行,直到您要停止它为止。
答案 1 :(得分:0)
感谢@ sparky05提供的解决方案,我并没有意识到有例外情况
from telethon import TelegramClient,errors
from telethon.tl.functions.photos import UploadProfilePhotoRequest
import os
import urllib.request
import urllib.error
import asyncio
from datetime import datetime
import datetime
api_id = XXXXX
api_hash = 'XXXXXXXXXXXX'
client = TelegramClient('Change_Photo', api_id, api_hash)
client.start()
async def Change_Photo():
while True:
try:
#time.sleep(0)
if os.path.exists("cat.jpg"):
os.remove("cat.jpg")
if os.path.exists("cat"):
os.remove("cat")
urllib.request.urlretrieve("https://cataas.com/cat", "cat")
os.rename('cat', 'cat.jpg')
await client(UploadProfilePhotoRequest(await client.upload_file(r"C:\Users\localhost\PycharmProjects\Scripts Python\Telethon\cat.jpg")))
now = datetime.datetime.now()
os.remove("cat.jpg")
print("Changed Photo:", now.strftime("%Y-%m-%d %H:%M:%S"))
except errors.FloodWaitError as e:
print('Have to sleep', e.seconds, 'seconds')
await asyncio.sleep(e.seconds)
except urllib.error.HTTPError as e:
if e.code == 502:
print("HTTP error 502... Trying again")
# except errors.FloodWaitError as e:
# print('Have to sleep', e.seconds, 'seconds')
# await asyncio.sleep(e.seconds)
#
# except urllib.error.HTTPError as e:
# if e.code == 502:
# print("HTTP error 502... Trying again")
loop = asyncio.get_event_loop()
loop.run_until_complete(Change_Photo())
loop.close()