watch_folder = r'D:/zip' upload_url = 'http://192.168.1.231:6060/dz' def upload_file(file_path): with open(file_path, 'rb') as file: files = {'file': file} response = requests.post(upload_url, files=files) print(f"Uploaded {file_path}: {response.status_code}") def delete_file(file_path): os.remove(file_path) print(f"Deleted {file_path}") def monitor_folder(): files = set() while True: current_files = set(os.listdir(watch_folder)) new_files = current_files - files for file in new_files: file_path = os.path.join(watch_folder, file) upload_file(file_path) delete_file(file_path) files = current_files time.sleep(15) if __name__ == "__main__": monitor_folder() 这段代码一段时间没有接收到连接会报错, raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='192.168.1.231', port=6060): Max retries exceeded with url: /dz (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001915C2540F0>: Failed to establish a new connection: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。',)) 如何改代码可以在没有接收到连接时一直等待,而不是报错中断程序
时间: 2024-04-18 15:23:32 浏览: 216
dbf.rar_arcgis_arcgis python_site:www.pudn.com
要在没有接收到连接时一直等待而不报错中断程序,您可以使用 `try-except` 块来捕获连接错误,并在捕获到错误时进行延迟重试。下面是修改后的代码示例:
```python
import os
import time
import requests
watch_folder = r'D:/zip'
upload_url = 'http://192.168.1.231:6060/dz'
def upload_file(file_path):
with open(file_path, 'rb') as file:
files = {'file': file}
response = requests.post(upload_url, files=files)
print(f"Uploaded {file_path}: {response.status_code}")
def delete_file(file_path):
os.remove(file_path)
print(f"Deleted {file_path}")
def monitor_folder():
files = set()
while True:
current_files = set(os.listdir(watch_folder))
new_files = current_files - files
for file in new_files:
file_path = os.path.join(watch_folder, file)
try:
upload_file(file_path)
delete_file(file_path)
except requests.exceptions.ConnectionError as e:
print(f"Connection error: {e}")
time.sleep(15) # 等待一段时间后重试
files = current_files
time.sleep(15)
if __name__ == "__main__":
monitor_folder()
```
在修改后的代码中,当捕获到 `ConnectionError` 异常时,会打印错误消息并等待一段时间后重试上传。这样可以避免报错中断程序,并持续等待连接恢复。
阅读全文