import os import pystray import threading from PIL import Image from pystray import MenuItem import time import requests import json import shutil from configparser import ConfigParser import socket def close(icon, item): global isWorking isWorking = False icon.stop() def check_one_instance(): try: global s s = socket.socket() host = socket.gethostname() s.bind((host, 20309)) return True except Exception: print('already has an instance') return False def main(): conf = ConfigParser() # 需要实例化一个ConfigParser对象 conf.read('conf.ini') global isWorking isWorking = True serverUrl = conf['ctc']['serverUrl'] currentPath = os.getcwd() backupPath = os.path.join(currentPath, 'backup') if not os.path.exists(backupPath): os.mkdir(backupPath) menu = (MenuItem('退出', close), ) image = Image.open("favicon.ico") title = "ctc数据推送" icon = pystray.Icon(title, image, "ctc数据推送", menu) threading.Thread(target=icon.run, daemon=True).start() while isWorking: files = os.listdir(currentPath) for file in files: file_path = os.path.join(currentPath, file) if file_path.endswith('.txt'): with open(file_path, 'r', encoding="utf-8") as f: post_data = json.load(f) for i in post_data['TestVaule']: for k in i: if i[k] == 'null': i[k] = None try: requests.post(url=serverUrl, json=post_data) try: shutil.move(file_path, backupPath) except Exception: os.remove(file_path) except Exception as e: err = '服务器错误:{}'.format(e.__str__()[0:80]) icon.notify(message=err) time.sleep(3) if __name__ == '__main__': if check_one_instance(): main() # pyinstaller -F -w -i favicon.ico ctc数据推送.py