So cute are you Python 8

本文介绍了Python中几种实用的编程技巧,包括使用lambda表达式简化代码、列表推导式快速创建列表、利用多线程提高程序效率等。通过这些技巧,可以更高效地进行Python开发。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Using lambda

#!/usr/bin/evn python
#coding:utf-8
#FileName:lambda.py
#function: using lambda
#History:14-10-2013
def make_repeater(n):
    return lambda s:s*n
 
twice = make_repeater( 2)
 
print twice('word')
print twice( 5)
2.
#!/usr/bin/evn python
#coding:utf-8
#FileName:list_comprehension.py
#function: how to use list
#History:14-10-2013
listone = [2,3,4]
listtow = [2*i for i in listone if i>2]
print listtow

3.write an program that carry args
#!/usr/bin/evn python
#coding:utf-8
#FileName:cat.py
#function: write an program that carry args
#History:14-10-2013
import sys
 
def readfile(filename):
    '''Print a file to the standared output.'''
    f =file(filename)
    while True:
        line=f.readline()
        if len(line)== 0:
            break
        print line,
    f.close()
 
#Script starts from here
if len(sys.argv)< 2:
    print 'No action specified.'
    sys.exit()
 
if sys.argv[ 1].startswith('--'):
    option =sys.argv[ 1][ 2:]
    # fetch sys.argv[1] but without the first tow characters
    if option=='version':
        print 'Version 1.2'
    elif option=='help':
        print '''\
This program prints files to the standared output
Any number of files can be specified.
Optios inxlude:
    --veersion:Prints the version number
    --help :Display the help'''
    else:
        print 'Unknown option.'
    sys.exit()
else:
    for filename in sys.argv[ 1:]:
        readfile(filename)

4.Found port

#!/usr/bin/evn python
#coding:utf-8
#FileName:scaner.py
#a function that could scanning a host's port
import socket
import socket
import threading
import getopt,sys
 
def connect_port(ip,port):
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect((ip,port))
        print '主机 %s端口 %d 打开' %(ip,port)
        s.close()
    except socket.error,msg:
            pass
    except Exception:
        s.close()
        pass
def scan():
    threads =[]
    opt,args = getopt.getopt(sys.argv[ 1:],'')
  
    if len(args)<  0:
        print '无法连接'
        quit()
    addr=raw_input('请输入要扫描的主机地址:')
    if addr=='':
        addr='127.0.0.1'
    else:
        addr=addr
    sport=raw_input('请输入开始端口:')
     
    if sport =='':
        sport='0'
    else:
        sport=sport
     
    eport=raw_input('请输入结束端口:')
    if eport =='':
        eport='500'
    else:
        eport=eport
    for i in xrange(int(sport),int(eport)):
        threads.append(threading.Thread(target=connect_port(str(addr),i)))
  
    for t in threads:
        t.start()
  
    for j in threads:
        t.join()
    #threads.clear()
    
 
if __name__ == '__main__':
    print '初始化完成...\r\n'
    threads1 =[]
    scan()
    addr = raw_input('ADDRESS:_')
    s=addr
    for l in xrange( 1,254):
        addr=s+'.'+str(l);
        print addr
        for i in xrange( 0,500):
            threads1.append(threading.Thread(target=connect_port(str(addr),i)))
        #for t in threads1:
            #t.start()
        #for j in threads1:
            #t.join()
5.Using thread

#!/usr/bin/evn python
#coding:utf-8
#Filename:thread_t1.py
#Function:show how to use thread with python first
#History:15-10-2013
import time
import thread
 
def timer(no,interval):
    cnt =  0;
    print 'New Thread starting...\r\n'
    while cnt<10:
        print 'Thread:(%d) Time:%s \n' %(no,time.ctime())
        time.sleep(interval)
        cnt+= 1
    thread.ext_thread()
 
def test():#Use thread.start_new_thread() to create tow threads
    thread.start_new_thread(timer,( 1, 1))
    thread.start_new_thread(timer,( 2, 2))
 
if __name__=='__main__':
    test()
    time.sleep(10)
6.Using threading

#!/usr/bin/evn python
#coding:utf-8
#Filename:threading_t1.py
#Function:show how to use threading with python first
#History:15-10-2013
import threading
import time
class timer(threading.Thread):
    def __init__(self,num,interval):
        threading.Thread.__init__(self)
        self.thread_num=num
        self.interval=interval
        self.thread_stop=False
 
    def run(self):
        while not self.thread_stop:
            print 'Thread Object(%d),Timer:%s\n'%(self.thread_num,time.ctime())
            time.sleep(self.interval)
    def stop(self):
        self.thread_stop=True
 
def test():
    thread1=timer( 1, 1)
    thread2=timer( 2, 2)
    thread1.start()
    print 'Thread1 was started...\r\n'
    thread2.start()
    print 'Thread2 was started...\r\n'
    time.sleep(10)
    thread1.stop()
    thread2.stop()
    return
 
if __name__=='__main__':
    test()

7.Lock with thread 1

#!/usr/bin/evn python
#coding:utf-8
#Filename:lock.py
#Function:show how to use threading with lock and python
#History:15-10-2013
import thread
import time
mylock = thread.allocate_lock()#Allocate a lock
num= 0
 
def add_num(name):
    global num
    while True:
        mylock.acquire()#Get the lock
        #Do something to the thared resource
        print 'Thread %s locked num:=%s'%(name,str(num))
        if num>= 5:
            print 'Thread %s released!num=%s'%(name,str(num))
            mylock.release()
            thread.exit_thread()
        num+= 1
        print 'Thread %s released ! num=%s'%(name,str(num))
        mylock.release()
 
def test():
    thread.start_new_thread(add_num,('A',))
    thread.start_new_thread(add_num,('B',))
     
 
if __name__=='__main__':
    test()
    time.sleep(10)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值