首页
关于
Search
1
怎么快速从GitHub上下载代码
48 阅读
2
GitHub下载加速的有效方法
39 阅读
3
Python中的center()是怎么用的
35 阅读
4
如何在GitHub上下载旧版本
34 阅读
5
怎样删除GitHub存储库
32 阅读
Python
Github
IDC推荐
登录
Search
Xbe
累计撰写
242
篇文章
累计收到
1
条评论
首页
栏目
Python
Github
IDC推荐
页面
关于
搜索到
81
篇与
的结果
2025-03-08
Python中的简单定时器
Timer: 隔一定时间调用一个函数,如果想实现每隔一段时间就调用一个函数的话,就要在Timer调用的函数中,再次设置Timer。Timer是Thread的一个派生类python中的线程提供了java线程功能的子集。#!/usr/bin/env python from threading import Timer import time timer_interval=1 def delayrun(): print 'running' t=Timer(timer_interval,delayrun) t.start() while True: time.sleep(0.1) print 'main running't是一个Timer对象。delay一秒钟之后执行delayrun函数。其中time.sleep函数是用来让主线程暂停一点时间再继续执行。
2025年03月08日
4 阅读
0 评论
0 点赞
2025-03-08
利用Python对网站进行测速
利用python可以编写的用于测试网站访问速率的代码,实现原理是输出打开某url的时间,并计算出访问100次的平均时间,时间和最小时间等等。根据时间的变化判断网站速度。完整代码:import urllib2 from datetime import * import time def Process(url,n): minSpan = 10.0 maxSpan = 0.0 sumSpan= 0.0 over1s = 0 for i in range(n): startTime = datetime.now() try: res = urllib2.urlopen(url,timeout=10) except: pass endTime = datetime.now() span = (endTime-startTime).total_seconds() sumSpan = sumSpan + span if span < minSpan: minSpan = span if span > maxSpan: maxSpan = span #超过一秒的 if span>1: over1s=over1s + 1 print(u'%s Spent :%s seconds'%(url,span)) print(u'requested:%s times,Total Spent:%s seconds,avg:%s seconds, max:%s seconds,min:%s seconds,over 1 secnod:%s times'%(n,sumSpan,sumSpan/n,maxSpan,minSpan,over1s)) print('\n') if __name__=='__main__': Process('http://www.baidu.com',100)运行结果如下:http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.094 seconds http://www.baidu.com Spent :0.016 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.016 seconds http://www.baidu.com Spent :0.015 seconds http://www.baidu.com Spent :0.015 seconds http://www.baidu.com Spent :0.016 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.046 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.094 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.109 seconds http://www.baidu.com Spent :0.094 seconds http://www.baidu.com Spent :0.094 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.062 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.047 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.015 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.047 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.016 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.016 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.015 seconds http://www.baidu.com Spent :0.016 seconds http://www.baidu.com Spent :0.016 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.015 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.078 seconds http://www.baidu.com Spent :0.109 seconds http://www.baidu.com Spent :0.015 seconds http://www.baidu.com Spent :0.094 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.109 seconds http://www.baidu.com Spent :0.094 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.047 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.032 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds http://www.baidu.com Spent :0.031 seconds requested:100 times,Total Spent:3.67 seconds,avg:0.0367 seconds, max:0.109 seconds,min:0.015 seconds,over 1 secnod:0 times
2025年03月08日
6 阅读
0 评论
0 点赞
2025-03-08
用Python来统计本机CPU利用率
模块win32pdh是Python中的一个模块,封装了Windows Performance Data Helpers API。win32pdh方法AddCounter 添加一个新计数器 AddEnglishCounter 通过英文名称为查询添加计数器 RemoveCounter 删除一个打开的计数器。 EnumObjectItems 枚举对象的项目 EnumObjects 枚举对象 OPENQUERY 打开一个新查询 CloseQuery 关闭打开的查询。 MakeCounterPath 制作完全解决的计数器路径 GetCounterInfo 检索有关计数器的信息,例如数据大小,计数器类型,路径和用户提供的数据值。 GetFormattedCounterValue 检索格式化的计数器值 CollectQueryData 收集指定查询中所有计数器的当前原始数据值,并更新每个计数器的状态代码。 ValidatePath 验证指定的计数器是否存在于计数器路径中指定的计算机上。 ExpandCounterPath 检查指定的计算机(如果没有指定本地计算机),则检查与计数器路径中的通配符字符串匹配的计数器和计数器实例。 ParseCounterPath 解析计数器路径的元素。 ParseInstanceName 解析实例名称的元素 SetCounterScaleFactor 设置在请求格式化计数器值时应用于指定计数器的计算值的比例因子。 BrowseCounters 显示计数器浏览对话框,以便用户可以选择要返回给调用者的计数器。 ConnectMachine 连接到指定的计算机,并在PDH DLL中创建和初始化计算机条目。 LookupPerfIndexByName 返回与指定计数器名称对应的计数器索引。 LookupPerfNameByIndex 返回与指定索引对应的性能对象名称。 完整代码:python统计cpu利用率#-*-coding=utf-8-*- import win32pdh import time # Counter paths PROCESSOR_PERCENT = r'\Processor(_Total)\% Processor Time' MEMORY_PERCENT = r'\Memory\% Committed Bytes In Use' MEMORY_COMMITTED = r'\Memory\Committed Bytes' PROCESS_BYTES = lambda x: r'\Process(%s)\Private Bytes' % x class Query: def __init__(self): self.counters = {} self.query = None self.query = win32pdh.OpenQuery(None, 0) def add_counter(self, path): if win32pdh.ValidatePath(path) != 0: raise Exception('Invalid path: %s' % path) counter = win32pdh.AddCounter(self.query, path, 0) self.counters[path] = counter def remove_counter(self, path): win32pdh.RemoveCounter(self.counters[path]) del self.counters[path] def get_values(self): values = {} win32pdh.CollectQueryData(self.query) for path in self.counters: status, value = win32pdh.GetFormattedCounterValue( self.counters[path], win32pdh.PDH_FMT_LONG) values[path] = value return values sysinfo_query = Query() sysinfo_query.add_counter(PROCESSOR_PERCENT) sysinfo_query.add_counter(MEMORY_PERCENT) sysinfo_query.get_values() def get_sysinfo(): """Return a tuple (mem_usage, cpu_usage).""" info = sysinfo_query.get_values() return info[MEMORY_PERCENT], info[PROCESSOR_PERCENT] listcpu=[] while True: time.sleep(2) x,y=get_sysinfo() listcpu.append(y) if len(listcpu)==10: icount=0 for c in listcpu: if c>4: icount+=1 if icount>5: print "在统计的1分钟内,cpu已经有5次大于4%" listcpu=[] print y
2025年03月08日
6 阅读
0 评论
0 点赞
2025-03-08
详解Python中的Thread线程模块
threading.ThreadThread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另一种是创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入。下面分别举例说明。先来看看通过继承threading.Thread类来创建线程的例子:#coding=gbk import threading, time, random count = 0 class Counter(threading.Thread): def __init__(self, lock, threadName): '''@summary: 初始化对象。 @param lock: 琐对象。 @param threadName: 线程名称。 ''' super(Counter, self).__init__(name = threadName) #注意:一定要显式的调用父类的初始化函数。 self.lock = lock def run(self): '''@summary: 重写父类run方法,在线程启动后执行该方法内的代码。 ''' global count self.lock.acquire() for i in xrange(10000): count = count + 1 self.lock.release() lock = threading.Lock() for i in range(5): Counter(lock, "thread-" + str(i)).start() time.sleep(2) #确保线程都执行完毕 print count在代码中,我们创建了一个Counter类,它继承了threading.Thread。初始化函数接收两个参数,一个是琐对象,另一个是线程的名称。在Counter中,重写了从父类继承的run方法,run方法将一个全局变量逐一的增加10000。在接下来的代码中,创建了五个Counter对象,分别调用其start方法。最后打印结果。这里要说明一下run方法 和start方法: 它们都是从Thread继承而来的,run()方法将在线程开启后执行,可以把相关的逻辑写到run方法中(通常把run方法称为活动[Activity]。);start()方法用于启动线程。再看看另外一种创建线程的方法:import threading, time, random count = 0 lock = threading.Lock() def doAdd(): '''@summary: 将全局变量count 逐一的增加10000。 ''' global count, lock lock.acquire() for i in xrange(10000): count = count + 1 lock.release() for i in range(5): threading.Thread(target = doAdd, args = (), name = 'thread-' + str(i)).start() time.sleep(2) #确保线程都执行完毕 print count在这段代码中,我们定义了方法doAdd,它将全局变量count 逐一的增加10000。然后创建了5个Thread对象,把函数对象doAdd 作为参数传给它的初始化函数,再调用Thread对象的start方法,线程启动后将执行doAdd函数。这里有必要介绍一下threading.Thread类的初始化函数原型:def __init__(self, group=None, target=None, name=None, args=(), kwargs={}) 参数group是预留的,用于将来扩展; 参数target是一个可调用对象(也称为活动[activity]),在线程启动后执行; 参数name是线程的名字。默认值为“Thread-N“,N是一个数字。 参数args和kwargs分别表示调用target时的参数列表和关键字参数。Thread类还定义了以下常用方法与属性:Thread.getName() Thread.setName() Thread.name用于获取和设置线程的名称。Thread.ident获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。Thread.is_alive()Thread.isAlive()判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。Thread.join([timeout])调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束。下面举个例子说明join()的使用:import threading, time def doWaiting(): print 'start waiting:', time.strftime('%H:%M:%S') time.sleep(3) print 'stop waiting', time.strftime('%H:%M:%S') thread1 = threading.Thread(target = doWaiting) thread1.start() time.sleep(1) #确保线程thread1已经启动 print 'start join' thread1.join() #将一直堵塞,直到thread1运行结束。 print 'end join' threading.RLock和threading.Lock在threading模块中,定义两种类型的琐:threading.Lock和threading.RLock。它们之间有一点细微的区别,通过比较下面两段代码来说明:import threading lock = threading.Lock() #Lock对象 lock.acquire() lock.acquire() #产生了死琐。 lock.release() lock.release() import threading rLock = threading.RLock() #RLock对象 rLock.acquire() rLock.acquire() #在同一线程内,程序不会堵塞。 rLock.release() rLock.release()这两种琐的主要区别是:RLock允许在同一线程中被多次acquire。而Lock却不允许这种情况。注意:如果使用RLock,那么acquire和release必须成对出现,即调用了n次acquire,必须调用n次的release才能真正释放所占用的琐。threading.Condition可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题。threadiong.Condition在内部维护一个琐对象(默认是RLock),可以在创建Condigtion对象的时候把琐对象作为参数传入。Condition也提供了acquire, release方法,其含义与琐的acquire, release方法一致,其实它只是简单的调用内部琐对象的对应的方法而已。Condition还提供了如下方法(特别要注意:这些方法只有在占用琐(acquire)之后才能调用,否则将会报RuntimeError异常。):Condition.wait([timeout]):wait方法释放内部所占用的琐,同时线程被挂起,直至接收到通知被唤醒或超时(如果提供了timeout参数的话)。当线程被唤醒并重新占有琐的时候,程序才会继续执行下去。Condition.notify():唤醒一个挂起的线程(如果存在挂起的线程)。注意:notify()方法不会释放所占用的琐。Condition.notify_all()Condition.notifyAll()唤醒所有挂起的线程(如果存在挂起的线程)。注意:这些方法不会释放所占用的琐。现在写个捉迷藏的游戏来具体介绍threading.Condition的基本使用。假设这个游戏由两个人来玩,一个藏(Hider),一个找(Seeker)。游戏的规则如下:1. 游戏开始之后,Seeker先把自己眼睛蒙上,蒙上眼睛后,就通知Hider;2. Hider接收通知后开始找地方将自己藏起来,藏好之后,再通知Seeker可以找了; 3. Seeker接收到通知之后,就开始找Hider。Hider和Seeker都是独立的个体,在程序中用两个独立的线程来表示,在游戏过程中,两者之间的行为有一定的时序关系,我们通过Condition来控制这种时序关系。#---- Condition #---- 捉迷藏的游戏 import threading, time class Hider(threading.Thread): def __init__(self, cond, name): super(Hider, self).__init__() self.cond = cond self.name = name def run(self): time.sleep(1) #确保先运行Seeker中的方法 self.cond.acquire() #b print self.name + ': 我已经把眼睛蒙上了' self.cond.notify() self.cond.wait() #c #f print self.name + ': 我找到你了 ~_~' self.cond.notify() self.cond.release() #g print self.name + ': 我赢了' #h class Seeker(threading.Thread): def __init__(self, cond, name): super(Seeker, self).__init__() self.cond = cond self.name = name def run(self): self.cond.acquire() self.cond.wait() #a #释放对琐的占用,同时线程挂起在这里,直到被notify并重新占 有琐。 #d print self.name + ': 我已经藏好了,你快来找我吧' self.cond.notify() self.cond.wait() #e #h self.cond.release() print self.name + ': 被你找到了,哎~~~' cond = threading.Condition() seeker = Seeker(cond, 'seeker') hider = Hider(cond, 'hider') seeker.start() hider.start()threading.EventEvent实现与Condition类似的功能,不过比Condition简单一点。它通过维护内部的标识符来实现线程间的同步问题。(threading.Event和.NET中的System.Threading.ManualResetEvent类实现同样的功能。)Event.wait([timeout])堵塞线程,直到Event对象内部标识位被设为True或超时(如果提供了参数timeout)。Event.set()将标识位设为TureEvent.clear()将标识伴设为False。Event.isSet()判断标识位是否为Ture。下面使用Event来实现捉迷藏的游戏(可能用Event来实现不是很形象)#---- Event #---- 捉迷藏的游戏 import threading, time class Hider(threading.Thread): def __init__(self, cond, name): super(Hider, self).__init__() self.cond = cond self.name = name def run(self): time.sleep(1) #确保先运行Seeker中的方法 print self.name + ': 我已经把眼睛蒙上了' self.cond.set() time.sleep(1) self.cond.wait() print self.name + ': 我找到你了 ~_~' self.cond.set() print self.name + ': 我赢了' class Seeker(threading.Thread): def __init__(self, cond, name): super(Seeker, self).__init__() self.cond = cond self.name = name def run(self): self.cond.wait() print self.name + ': 我已经藏好了,你快来找我吧' self.cond.set() time.sleep(1) self.cond.wait() print self.name + ': 被你找到了,哎~~~' cond = threading.Event() seeker = Seeker(cond, 'seeker') hider = Hider(cond, 'hider') seeker.start() hider.start()threading.Timerthreading.Timer是threading.Thread的子类,可以在指定时间间隔后执行某个操作。下面是Python手册上提供的一个例子:def hello(): print "hello, world" t = Timer(3, hello) t.start() # 3秒钟之后执行hello函数。threading模块中还有一些常用的方法没有介绍:threading.active_count()threading.activeCount()获取当前活动的(alive)线程的个数。threading.current_thread()threading.currentThread()获取当前的线程对象(Thread object)。threading.enumerate()获取当前所有活动线程的列表。threading.settrace(func)设置一个跟踪函数,用于在run()执行之前被调用。threading.setprofile(func)设置一个跟踪函数,用于在run()执行完毕之后调用。threading模块的内容很多。
2025年03月08日
5 阅读
0 评论
0 点赞
2025-03-08
Python怎么安装第三方模块
Python中有哪几种方法安装第三方模块,安装Python第三方模块的方法有很多,这里介绍三种方法安装第三方模块。【方法一】: 通过setuptools来安装python模块首先下载 http://peak.telecommunity.com/dist/ez_setup.pyNOTE: 最好下载个setuptools,本人是15.2版本,里面包含了ez_setup运行 python ez_setup.pyD:\work\installation\setuptools-15.2\setuptools-15.2>python ez_setup.py > 1.txt Extracting in c:\users\admini~1\appdata\local\temp\tmpbxikxf Now working in c:\users\admini~1\appdata\local\temp\tmpbxikxf\setuptools-15.2 Installing Setuptools ...... Copying setuptools-15.2-py2.7.egg to c:\python27\lib\site-packages setuptools 15.2 is already the active version in easy-install.pth Installing easy_install-script.py script to C:\Python27\Scripts Installing easy_install.exe script to C:\Python27\Scripts Installing easy_install-2.7-script.py script to C:\Python27\Scripts Installing easy_install-2.7.exe script to C:\Python27\Scripts Installed c:\python27\lib\site-packages\setuptools-15.2-py2.7.egg Processing dependencies for setuptools==15.2 Finished processing dependencies for setuptools==15.2运行 easy_install pyD:\work>easy_install py #py 为第三方库文件 Searching for py Best match: py 1.4.26 Adding py 1.4.26 to easy-install.pth file Using c:\python27\lib\site-packages Processing dependencies for py Finished processing dependencies for py【方法二】: 通过pip来安装python模块安装 easy_install pipD:\work>easy_install pip Searching for pip Best match: pip 6.1.1 Processing pip-6.1.1-py2.7.egg pip 6.1.1 is already the active version in easy-install.pth Installing pip-script.py script to C:\Python27\Scripts Installing pip.exe script to C:\Python27\Scripts Installing pip2.7-script.py script to C:\Python27\Scripts Installing pip2.7.exe script to C:\Python27\Scripts Installing pip2-script.py script to C:\Python27\Scripts Installing pip2.exe script to C:\Python27\Scripts Using c:\python27\lib\site-packages\pip-6.1.1-py2.7.egg Processing dependencies for pip Finished processing dependencies for pip运行 pip install xlrdUsage: pip <command></command> [options] Commands: install Install packages. uninstall Uninstall packages. freeze Output installed packages in requirements format. list List installed packages. show Show information about installed packages. search Search PyPI for packages. wheel Build wheels from your requirements. zip DEPRECATED. Zip individual packages. unzip DEPRECATED. Unzip individual packages. help Show help for commands. General Options: -h, --help Show help. --isolated Run pip in an isolated mode, ignoring environment variables and user configuration. -v, --verbose Give more output. Option is additive, and can be used up to 3 times. -V, --version Show version and exit. -q, --quiet Give less output. --log <path> Path to a verbose appending log. --proxy <proxy> Specify a proxy in the form [user:passwd@]proxy.server:port. --retries <retries> Maximum number of retries each connection should attempt (default 5 times). --timeout <sec> Set the socket timeout (default 15 seconds). --exists-action <action> Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup. --trusted-host <hostname> Mark this host as trusted, even though it does not have valid or any HTTPS. --cert <path> Path to alternate CA bundle. --client-cert <path> Path to SSL client certificate, a single file containing the private key and the certificate in PEM format. --cache-dir <dir> Store the cache data in <dir>. --no-cache-dir Disable the cache. --disable-pip-version-check Don't periodically check PyPI to determine whether a new version of pip is available for download. Implied with --no-index.【方法三】:直接从网上下载下可执行文件来安装.比如说,去 >>> pythonlibs <<< 网站,提供了很多Python非官方包下载,二进制文件,下载安装方便.
2025年03月08日
6 阅读
0 评论
0 点赞
1
...
6
7
8
...
17