好多资源哦

 找回密码
 立即注册
12
返回列表 发新帖
楼主: itubay

开一个Python项目网络实践贴贴吧

[复制链接]
 楼主| 发表于 2024-6-19 23:14:45 | 显示全部楼层
#shpm25.py 上海PM2.5监测
def rbCity():  #单击区县按钮的处理函数
    global sitelist, listradio
    sitelist.clear()  #清除原有监测站点列表
    for r in listradio:  #删除原有监测站点按钮
        r.destroy()
    n=0
    for c1 in data["监测站点"]:  #逐一取出所选区县市的监测站点
        if(c1 == city.get()):
            sitelist.append(data.iloc[n, 1])
        n += 1   
    sitemake()  #生成测站点按钮
    rbSite()  #显示PM2.5数值

def rbSite():  #单击监测站按钮后的处理函数
    n = 0
    for s in data.iloc[:,1]:  #逐一取得监测站点
        if(str(s) == site.get()):  #如果某监测站点名称与选中的监测站点相同,则
            pm = data.loc[n][ "PM2.5浓度"]  #取得该站点的PM2.5数值
            pm=pm[:-5]    #去除数据后面的5位单位字符
            pm=int(pm)  #把PM2.5的字符型数据转为整型
            ss=city.get()
            if(pd.isnull(pm)):  #如果没有数据,则
                result1.set(ss + "站的 PM2.5 值当前无数据!")   #显示无数据
            else:  #如果有数据,则
                if(pm <= 35):  #转换为空气质量等级
                    grade1 = "优秀"
                elif(pm <= 53):
                    grade1 = "良好"
                elif(pm <= 70):
                    grade1 = "中等"
                else:
                    grade1 = "差"
                result1.set(f"{ss}[{s}]站的 PM2.5 值为" + str(pm) + ";" + grade1 )
            break  #找到选中的监测站点的数据后就跳出循环
        n += 1

def clickRefresh():  #重新读取数据
    global data
    df = pd.read_html("http://www.86pm25.com/city/shanghai.html")
    data=df[0]
    rbSite()  #更新监测站点的数据

def sitemake():  #建立监测站点按钮
    global sitelist, listradio
    for c1 in sitelist:  #逐一建立按钮
        rbtem = tk.Radiobutton(frame2, text=c1, variable=site, value=c1, command=rbSite)  #建立单选按钮
        listradio.append(rbtem)  #插入至按钮列表
        if(c1==sitelist[0]):  #默认选取第1个按钮         
            rbtem.select()
        rbtem.pack(side="left")  #靠左对齐

import tkinter as tk
import pandas as pd
df = pd.read_html("http://www.86pm25.com/city/shanghai.html")
data=df[0]
win=tk.Tk()
win.geometry("680x300")
win.title("PM2.5 实时监测")
city = tk.StringVar()  #区县名称变量
site = tk.StringVar()  #监测站点名称变量
result1 = tk.StringVar()  #显示信息变量
citylist = []  #区县列表
sitelist = []  #监测站点列表
listradio = []  #区县按钮列表
#建立区县列表
for c1 in data["监测站点"]:  
    if(c1 not in citylist):  #如果列表中不存在该县区就将该县区名称插入列表
        citylist.append(c1)
#建立第1个区县的监测站点列表
count = 0
for c1 in data["监测站点"]:  
    #if(c1 ==  citylist[0]):  #如果是第1个区县,则
    #    sitelist.append(data.iloc[count, 1])  #把该区县的所有监测站点插入到监测站点列表
    count += 1
label1 = tk.Label(win, text="区县:", pady=6, fg="blue", font=("新细明体", 12))
label1.pack()
frame1 = tk.Frame(win)  #区县容器
frame1.pack()
for i in range(0,2):  #按钮分2行
    for j in range(0,8):  #每行8个
        n = i * 8 + j  #第n个按钮
        if(n < len(citylist)):
            city1 = citylist[n]  #取得区县名称
            rbtem = tk.Radiobutton(frame1, text=city1, variable=city, value=city1, command=rbCity)  #建立单选按钮
            rbtem.grid(row=i, column=j)  #设置按钮的位置
            if(n==0):  #选取第1个区县
                rbtem.select()
label2 = tk.Label(win, text="监测站点:", pady=6, fg="blue", font=("新细明体", 12))
label2.pack()
frame2 = tk.Frame(win)  #监测站点容器
frame2.pack()
sitemake()
btnDown = tk.Button(win, text="更新数据", font=("新细明体", 12), command=clickRefresh)
btnDown.pack(pady=6)
lblResult1 = tk.Label(win, textvariable=result1, fg="red", font=("新细明体", 16))
lblResult1.pack(pady=6)
rbSite()  #显示测站讯息
win.mainloop()

#命令行执行 python shpm25.py


pypm25.png
回复

使用道具 举报

 楼主| 发表于 2024-6-20 23:51:24 | 显示全部楼层
python小程序,验证2的67次方减1不是质数
#验证2^67-1 是合数且得出其因子。
#因为只有尾数是1,3,7,9的数才可能是尾数为7的数字的因子,因此其它尾数可以跳过。
#(其实,10以上的质数,其个位也只能是1,3,7,9这4种)
# 先求出大数的平方根的整数部分,其因子之一必不比此(整数部分+1)大,因此循环可以少很多
import math
import datetime
BigN=2**67-1
Root=round(math.sqrt(BigN))+1
littleFactor=round(Root / 10)+1
startT=datetime.datetime.now()
for i in range(littleFactor):
   a=i*10+1
   b=i*10+3
   c=i*10+7
   d=i*10+9
   #去掉下面显示进度的这一句,时间可以缩短到41秒。
   #if (i%10000==0): print(i)
   if (BigN % a)==0 and (a!=1):
       print (a, ", ", BigN/a, "is its factor!")
       break
   if(BigN % b)==0:
       print(b, ", ", BigN/b,"is its factor!")
       break
   if (BigN %c)==0:
       print(c,", ", BigN /c, "is its factor!")
       break
   if(BigN %d)==0:
       print(d, ", ", BigN /d, "is its factor!")
       break
endT=datetime.datetime.now()
print("运行时间是:", endT-startT)  


mpyth.png
回复

使用道具 举报

 楼主| 发表于 2024-6-21 00:02:56 | 显示全部楼层
#上海天气预报
import requests
from lxml import etree
import pandas as pd
import re
url='http://www.weather.com.cn/weather1d/101020100.shtml#input'
with requests.get(url) as res:
    content=res.content
    html=etree.HTML(content)
    location=html.xpath('//*[@id="around"]//a[@target="_blank"]/span/text()')
    temperature=html.xpath('//*[@id="around"]/div/ul/li/a/i/text()')
    df=pd.DataFrame({'location':location,'temperature':temperature})
    #print(df['temperature'])
    df['high']=df['temperature'].apply(lambda x:int(re.match('(-?[0-9]*?)/-?[0-9]*?°C',x).group(1)))
    df['low']=df['temperature'].apply(lambda x:int(re.match('-?[0-9]*?/(-?[0-9]*?)°C',x).group(1)))
    print(df)
shwth.png
回复

使用道具 举报

 楼主| 发表于 2024-6-21 15:30:30 | 显示全部楼层
#重启Spooler打印服务
import win32service
import win32serviceutil
import time

service_name = "Spooler"
interval = 60

def restart_service(service_name):
    try:
        service = win32serviceutil.ChangeServiceConfigA(service_name, win32service.SERVICE_START)
        print("Attempting to restart service:",service_name)
        win32serviceutil.RestartService(service_name)
        print("Service",service_name," restarted successfully.")
    except:
        print("Failed to restart service:")

restart_service(service_name)
time.sleep(interval * 60)

回复

使用道具 举报

 楼主| 发表于 2024-6-21 15:39:14 | 显示全部楼层
#重启windows打印服务
import win32service
import win32serviceutil
import time

service_name = "Spooler"
interval = 60

def QueryServiceStatus(service_name):
    (_,status,_,_,_,_,_)=win32serviceutil.QueryServiceStatus(service_name)
    return status

def restart_service(service_name):
    print(service_name,"statues:",QueryServiceStatus(service_name))
    if QueryServiceStatus(service_name)==win32service.SERVICE_RUNNING:
        win32serviceutil.StopService(service_name)
        print("Server Stopping")
        while QueryServiceStatus(service_name) != win32service.SERVICE_STOPPED:
            time.sleep(1)
        win32serviceutil.StartService(service_name)
        print("Server Starting")
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    if QueryServiceStatus(service_name)==win32service.SERVICE_STOP_PENDING:
        print("Server Stopping")
        while QueryServiceStatus(service_name) != win32service.SERVICE_STOPPED:
            time.sleep(1)
        print("Server Stoped to Start")
        win32serviceutil.StartService(service_name)
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    if QueryServiceStatus(service_name)==win32service.SERVICE_STOPPED:
        print("Server Stoped to Start")
        win32serviceutil.StartService(service_name)
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    if QueryServiceStatus(service_name)==win32service.SERVICE_START_PENDING:
        print("Server Starting")
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    print(service_name," restarted successfully.")

restart_service(service_name)
time.sleep(interval * 60)

pywsa.png
回复

使用道具 举报

 楼主| 发表于 2024-6-21 15:44:34 | 显示全部楼层
#每整点自动重启windows打印服务
import win32service
import win32serviceutil
import time

service_name = "Spooler"
interval = 60

def QueryServiceStatus(service_name):
    (_,status,_,_,_,_,_)=win32serviceutil.QueryServiceStatus(service_name)
    return status

def restart_service(service_name):
    print(service_name,"status:",QueryServiceStatus(service_name))
    if QueryServiceStatus(service_name)==win32service.SERVICE_RUNNING:
        win32serviceutil.StopService(service_name)
        print("Server Stopping")
        while QueryServiceStatus(service_name) != win32service.SERVICE_STOPPED:
            time.sleep(1)
        win32serviceutil.StartService(service_name)
        print("Server Starting")
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    if QueryServiceStatus(service_name)==win32service.SERVICE_STOP_PENDING:
        print("Server Stopping")
        while QueryServiceStatus(service_name) != win32service.SERVICE_STOPPED:
            time.sleep(1)
        print("Server Stoped to Start")
        win32serviceutil.StartService(service_name)
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    if QueryServiceStatus(service_name)==win32service.SERVICE_STOPPED:
        print("Server Stoped to Start")
        win32serviceutil.StartService(service_name)
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    if QueryServiceStatus(service_name)==win32service.SERVICE_START_PENDING:
        print("Server Starting")
        while QueryServiceStatus(service_name) != win32service.SERVICE_START_PENDING:
            time.sleep(1)
        while QueryServiceStatus(service_name) != win32service.SERVICE_RUNNING:
            time.sleep(1)
        print("Server Running")
    print(service_name," restarted successfully.")

igo=0
def gotask():
    global igo
    while 1:
        att=time.localtime(time.time())
        ath=att[4]
        if ath==0:
            igo=igo+1
            print("[%s].gotask:%s"%(igo,att))
            restart_windows_service(service_name)

gotask()


回复

使用道具 举报

 楼主| 发表于 2024-6-21 15:46:28 | 显示全部楼层
以上代码通用,可改为其他windows服务名称即可实现自动重启指定windows服务
回复

使用道具 举报

 楼主| 发表于 2024-6-24 20:32:06 | 显示全部楼层
#每小时获取指定城市的pm值并写入对应文件
import threading
import re,sys
import time
import hashlib
import os
from urllib import request

sys.setdefaultencoding='utf-8'

def fetchdata(city):
    md5=''
    while True:
        fettime=time.localtime(time.time())
        if fettime.tm_min==0:
            temp='https://pm25.im/'+city
            url=request.urlopen(temp)
            text=url.read()
            regyh='<span class="time"><i></i>(.*?)</span>'
            comreg=re.compile(regyh,re.S)
            yh=re.findall(comreg,text.decode('utf-8'))
            regpm='<p class="denseness">(.*?)</p>'
            comreg=re.compile(regpm,re.S)
            pm=re.findall(comreg,text.decode('utf-8'))
            wval=f"{yh}@{city},pm:{pm}\n".replace(r"['", '').replace(r"']",'').replace(r"<em>",'').replace(r"</em>",'')
            print(wval)
            data=open('c:/weather/'+city+'.txt','a',encoding='utf-8')
            data.write(wval)
            data.close()
        time.sleep(60)

fetchdata('shanghai')

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|好多资源哦

GMT+8, 2024-10-31 01:42 , Processed in 0.127742 second(s), 16 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表