常用Python代码

部署运行你感兴趣的模型镜像

系统

import tkinter as tk
from tkinter import filedialog


def file_path():
    """
    同过文件对话框的方式选择文件读取路径
    return: 返回转义后的路径
    """
    root = tk.Tk()
    root.withdraw()

    file_path = filedialog.askopenfilename()
    return file_path.replace('\\', '/')
import os


def delete_file(folder):
    """
    删除指定文件夹下的文件
    """
    file_list = os.listdir(folder)
    for file in file_list:
        full_path = os.path.join(folder, file)
        os.remove(full_path)
        print(f'{folder} 文件夹下共{len(file_list)}个文件,正在删除:{file}')
def get_suffix(filename):
    """
    获取文件夹的路径
    :param filename: 文件名
    :return: 文件夹的路径
    """
    # 从字符串中逆向查找.出现的位置
    pos = filename.rfind('/')
    # 通过切片操作从文件名中取出后缀名
    return filename[:pos + 1] if pos > 0 else ''
import win32api
import win32con


def click(x, y):
    """  
    鼠标移动到指定位置然后点击  
    """
    windll.user32.SetCursorPos(x, y)                            # 移动到指定位置
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y)   # 在(x, y) 按下鼠标左键
    time.sleep(0.05)  											# 停顿时间
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y)     # 在(x, y) 松开鼠标左键
import webbrowser


def click_url(url):
        """ 
        打开谷歌浏览器,跳转到指定的网页 
        """
        print("Google 浏览器已经打开,正在连接到指定网页 。。。")
        chrome_path = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
        webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(chrome_path))
        webbrowser.get('chrome').open(url, new=1, autoraise=True)
        print('等待页面加载········')
# 封装命令
pyinstaller -F gsd.py
import time 


def log(func):
    """
    用于计算程序运行时间 装饰器
    """
    def wrapper(*arg, **kw):
        start_t = time.time()
        # print(f"{func}正在运行****")
        result = func(*arg, **kw)
        end_t = time.time()
        print(f'用时 {(end_t - start_t):.2f} 秒')
        return result

    return wrapper
钉钉群机器人推送
class dingTalk(object):
	"""
	创建一个类让机器人发送Makedown,或者普通文本消息到指定的钉钉群,推送定期消息或者业绩情况
	"""
    def __init__(self, url_name, data):
        self.url_name = url_name
        self.data = data

    def dingtalk_md(self):
        """
        发送指定Markdown文件  到url
        """
        headers = {
            "Content-Type": "application/json"
        }
        data={
        "msgtype": "actionCard",
        "actionCard": {
            "title": "业绩播报", 
            "text":"![screenshot](http://110.110.110.png) \n\n" + self.data,   #  图片链接加文字
            "hideAvatar": "0", 
            "btnOrientation": "0", 
            "btns": [									# 定义点击按钮跳转指定链接
                 {
                     "title": "点我看业绩", 
                     "actionURL": "https://www.baidu.com"
                 }
            ]
                       }
        # "at": {                                       # 爱特对象
        #     #  "atMobiles": [
        #     #      "150XXXXXXXX"
        #     #  ], 
        #      "isAtAll": True							# True爱特所有人
        #  }
        }
        json_data=json.dumps(data)
        requests.post(url=self.url_name, data=json_data, headers=headers)
        print('已推送到钉钉')

    def dingtalk_text(self):
        """
        发送普通文本消息  到url
        """
        headers={
            "Content-Type": "application/json"
                }
        data={"msgtype": "text",
                "text": {
                    "content": self.data
                }
            }
        json_data=json.dumps(data)
        requests.post(url=self.url_name,data=json_data,headers=headers)

在这里插入图片描述
在这里插入图片描述
详细信息参阅*钉钉开发者文档*

数据库

def insert_data_to_pq(db_data):
    """
    把pandas 的DataFrame数据放到数据库中
    """
    engine = create_engine('postgresql://username:passworld@host:port/database_name')  
    pd.io.sql.to_sql(db_data, 'table_name', engine, index=False, if_exists='append')
    # db_data.to_sql('table_name', engine, index=False, if_exists='replace')
    print('数据插入数据库完成!!!')
class PgDatabase(object):
    """
    pg_db类 数据读取或者插入数据库
    """
    def __init__(self):
        self.conn = psycopg2.connect(
                        database='demo', user='postgres', password='123456',
                        host='110.110.110', port='5432')
                      

    def read_pg_sql(self, sql):
        """
        连接pq数据库并获取指定的SQL语句的数据
        """
        curs = self.conn.cursor()
        curs.execute(sql)
        data = curs.fetchall()
        curs.close()
        self.conn.close()
       
        return data

    def write_pg_sql(self, sql):
        """
        按照指定SQL语句修改pg数据库
        """
        curs = self.conn.cursor()
        insert_sql = sql
        curs.execute(insert_sql)
        self.conn.commit()
        curs.close()
        print("喵~~")

MySql连接

import pymysql

def sql_data(sql):
     """
     打开MySQL数据库连接
     """
    conn = pymysql.connect(host='110.110.110', user='root', password='123456',
                           database='demo')
    cur = conn.cursor()			# 创建游标
    cur.execute(sql)			# 执行指定SQL
    res = cur.fetchall()		# 获取所有结果,得到一个list
    cur.close()					# 关闭游标
    conn.commit()				# 提交
    conn.close()				# 关闭数据库连接
    print(res[:5])				# 打印前5行	
    return res					# 返回结果

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值