免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: 无风之谷
打印 上一主题 下一主题

ChinaUnix技术实践之五——Python编程大赛 欢迎大家参与!!(获奖名单公布) [复制链接]

论坛徽章:
1
CU十二周年纪念徽章
日期:2013-10-24 15:41:34
11 [报告]
发表于 2011-06-29 10:16 |只看该作者
支持下。

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:58:11
12 [报告]
发表于 2011-06-29 11:07 |只看该作者
shell的编程大赛、AIX达人竞赛、ChinaUnix技术自测 三个活动,均未评选完,怎么又出新比赛了?那些比赛什么时候会出结果呢?是由于不常上网的好友,在我的怂恿下,参加了,但却迟迟没结果,好象我骗了别人。

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:58:11
13 [报告]
发表于 2011-06-29 11:10 |只看该作者
朋友叫我关注赛果,其实我一直在关注,只是时间长了……看来CU的比赛,以后慎向别人推荐,甚至提及。

论坛徽章:
27
CU大牛徽章
日期:2013-03-13 15:15:08CU大牛徽章
日期:2013-05-20 10:46:38CU大牛徽章
日期:2013-05-20 10:46:44CU大牛徽章
日期:2013-09-18 15:24:09CU大牛徽章
日期:2013-09-18 15:24:20CU大牛徽章
日期:2013-09-18 15:24:25CU大牛徽章
日期:2013-09-18 15:24:31CU大牛徽章
日期:2013-09-18 15:24:36CU大牛徽章
日期:2013-09-18 15:24:41CU大牛徽章
日期:2013-09-18 15:24:48CU大牛徽章
日期:2013-09-18 15:24:52处女座
日期:2013-09-27 17:45:43
14 [报告]
发表于 2011-06-29 14:11 |只看该作者
本帖最后由 yifangyou 于 2011-06-30 11:29 编辑

下面是我的答案,执行之前先把文件头的中文注释去掉,python对于含有gbk的中文的.py文件有点问题,第8题需要在python2.6.5上运行
  1. #1. 去除list中的重复数据  [11, 22, 33, 11, 22] => [11, 22, 33]  。
  2. #运行环境:CentOS5.4 python2.4.3 python 2.6.5
  3. #           Python 2.4.3 (#1, May 24 2008, 13:47:28)
  4. #                                         [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  5. #执行:
  6. #                        [root@localhost ~]# python test1.py
  7. #                        please input number list split by ","> 11, 22, 33, 11, 22
  8. #                        [11, 22, 33]
  9. import re
  10. inputLine = raw_input('please input number list split by ","> ')
  11. numList=re.split('\W', inputLine)
  12. result=[]
  13. for n in numList:
  14. #        判断是否是数字串
  15.   if n.isdigit():
  16.     i=int(n)
  17. #    判断是否在结果集里
  18.     if i not in result:
  19.        result.append(i)
  20. print result
复制代码
  1. #2. 格式化输出,三位一逗号  1234567 -> 1,234,567  
  2. #运行环境:CentOS5.4 python2.4.3 python 2.6.5
  3. #           Python 2.4.3 (#1, May 24 2008, 13:47:28)
  4. #                                         [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  5. #执行:
  6. #                                [root@localhost ~]# python test2.py
  7. #                                please input number> 1234567
  8. #                                1,234,567
  9. import re
  10. num=''
  11. while not num.isdigit():
  12.   num = raw_input('please input number> ')
  13. #反转字符串,低位在前
  14. rnum= num[::-1]
  15. #先按照3个整数匹配,其次按照2或1个整数匹配
  16. rarray =re.findall('(\d{3}|\d{1,2})',rnum)
  17. #逗号连接起来
  18. rnum=','.join(rarray)
  19. #反转回来
  20. print rnum[::-1]
复制代码
  1. #3. 字符反转  abcde -> edcba   
  2. #运行环境:CentOS5.4 python2.4.3 python 2.6.5
  3. #           Python 2.4.3 (#1, May 24 2008, 13:47:28)
  4. #                                         [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  5. #执行:
  6. #                        [root@localhost ~]# python test3.py
  7. #                        please input string> abcdefg
  8. #                        gfedcba
  9. s = raw_input('please input string> ')
  10. print s[::-1]
复制代码
  1. #4. 打印当前系统的挂载点和空间大小(Linux)
  2. #运行环境:CentOS5.4 python2.4.3 python 2.6.5
  3. #           Python 2.4.3 (#1, May 24 2008, 13:47:28)
  4. #                                         [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  5. #执行:
  6. #                [root@localhost ~]# python test4.py
  7. #                文件系统              容量  已用 可用 已用% 挂载点
  8. #                /dev/sda2             194G   19G  166G  10% /
  9. #                /dev/sda6             159G  190M  151G   1% /opt
  10. #                /dev/sda3              97G  5.0G   87G   6% /data
  11. #                /dev/sda1             190M   25M  156M  14% /boot
  12. #                tmpfs                 2.0G     0  2.0G   0% /dev/shm
  13. import os
  14. import re
  15. #用管道执行可取回返回结果
  16. p=os.popen('df -h')
  17. x=p.read()
  18. print x
  19. p.close()
复制代码
  1. #5. 模拟登录401验证网站(Basic HTTP Authentication)
  2. #运行环境:CentOS5.4 python2.4.3 python 2.6.5
  3. #           Python 2.4.3 (#1, May 24 2008, 13:47:28)
  4. #                                         [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  5. #执行:
  6. #                [root@localhost ~]# python test5.py
  7. #   打开另一个SSH执行
  8. #                [root@localhost ~]# curl -u abc:123 http://127.0.0.1:8081
  9. #                login success!
  10. #                [root@localhost ~]# curl -u abc:1234 http://127.0.0.1:8081
  11. #                forbidden
  12. import BaseHTTPServer
  13. import re
  14. import cgi
  15. import base64

  16. class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
  17.      def get_Auth(self):
  18.                username='abc'
  19.                password='123'
  20.                # 获取base64验证码
  21.                b64=re.findall('\S+,self.headers['Authorization'])
  22.                if len(b64)==0:
  23.                     return 0
  24.                # 解码
  25.                d64=base64.b64decode(b64[0])
  26.                if d64==username+':'+password:
  27.                     return 1
  28.                else:
  29.                     return 0
  30.      def do_GET(self):
  31.           if self.get_Auth() == 1:      # 认证成功
  32.                data='login success!\n'
  33.                self.send_response(200)
  34.                self.send_header('Content-Length',len(data))
  35.                self.end_headers()
  36.                self.wfile.write(data)
  37.           else:
  38.               data='forbidden\n'  #对于认证失败的请求,返回 401 错误
  39.               self.wfile.write('HTTP/1.1 401 Unauthorized\r\n')
  40.               self.send_header('Content-Length',len(data))
  41.               self.send_header('WWW-Authenticate','Basic realm="test5"')
  42.               self.end_headers()
  43.               self.wfile.write(data)
  44.                      
  45. server = BaseHTTPServer.HTTPServer(('127.0.0.1',8081), WebRequestHandler)    #创建 HTTPSever 服务器,绑定地址:http://127.0.0.1:8081
  46. try:
  47.      server.serve_forever()   # 启动 HTTPServer 服务器
  48. except KeyboardInterrupt:
  49.      pass
  50. server.server_close()
复制代码
  1. #6. 获取远程某机器的系统当前日期时间(Linux)
  2. #运行环境:CentOS5.4 python2.4.3 python 2.6.5
  3. #           Python 2.4.3 (#1, May 24 2008, 13:47:28)
  4. #                                         [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  5. #执行:
  6. #                执行服务端
  7. #                [root@localhost ~]# python test6_timeServer.py
  8. #                waiting for connection...
  9. #                ...connected from: ('192.168.13.120', 48786)
  10. #                ...connected from: ('192.168.13.120', 57623)
  11. #   打开另一个SSH执行客户端
  12. #                        [root@localhost ~]# python test6_timeClient.py
  13. #                        please input time server ip> 192.168.13.105
  14. #                        now is [Thu Jun 30 10:51:25 2011]
  15. #                        [root@localhost ~]# python test6_timeClient.py
  16. #                        please input time server ip>
  17. #                        connect   : 1230  failed: (111, 'Connection refused')
  18. #                        [root@localhost ~]# python test6_timeClient.py
  19. #                        please input time server ip> 192.168.13.110
  20. #                        connect  192.168.13.110 : 1230  failed: timed out

  21. from SocketServer import (TCPServer as TCP,StreamRequestHandler as SRH)
  22. from time import ctime

  23. HOST = ''
  24. PORT = 1230
  25. ADDR = (HOST, PORT)

  26. class MyRequestHandler(SRH):
  27.         def handle(self):
  28.                 print '...connected from:', self.client_address
  29.                 #返回时间给客户端
  30.                 self.wfile.write('now is %s' % (ctime()))

  31. #监听本机1230端口        
  32. tcpServ = TCP(ADDR, MyRequestHandler)
  33. print 'waiting for connection...'

  34. try:
  35.      tcpServ.serve_forever()  # 启动 HTTPServer 服务器
  36. except KeyboardInterrupt:
  37.      pass
  38. tcpServ.server_close()
复制代码
  1. #test6_timeClient.py
  2. from socket import *
  3. import sys
  4. HOST = raw_input('please input time server ip> ')
  5. PORT = 1230
  6. BUFSIZ = 1024
  7. ADDR = (HOST, PORT)

  8. tcpCliSock = socket(AF_INET, SOCK_STREAM)
  9. tcpCliSock.settimeout(5)

  10. try:
  11.     tcpCliSock.connect(ADDR)
  12.     #向时间服务器查询
  13.     tcpCliSock.send('what time is\r\n')
  14.     #接收数据
  15.     data = tcpCliSock.recv(BUFSIZ)
  16.     print data.strip()
  17.     tcpCliSock.close()
  18. except:
  19.     (ErrorType, ErrorValue, ErrorTB) = sys.exc_info()
  20.     print 'connect ',HOST,':',PORT,' failed:',ErrorValue
复制代码
  1. #7. 打印Apache日志中访问次数最多的10条URL。
  2. #运行环境:CentOS5.4 python2.4.3 python 2.6.5
  3. #           Python 2.4.3 (#1, May 24 2008, 13:47:28)
  4. #                                         [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
  5. #执行:
  6. #                                [root@localhost ~]# python test7.py
  7. #                                please input apache access_log file path > /root/access_log
  8. #                                " /favicon.ico " be accessed 4 times
  9. #                                " /icons/compressed.gif " be accessed 3 times
  10. #                                " /pic/ " be accessed 3 times
  11. #                                " /icons/back.gif " be accessed 3 times
  12. #                                " /icons/blank.gif " be accessed 3 times
  13. #                                " /pic " be accessed 3 times
  14. #                                " /pic/20110625-%d1%e3%c6%dc%ba%fe.zip " be accessed 3 times
  15. #                                " /index.php?=PHPE9568F35-D428-11d2-A769-00AA001ACF42 " be accessed 1 times
  16. #                                " /ganglia " be accessed 1 times
  17. #                                " / " be accessed 1 times
  18. import re
  19. f=None
  20. while not f:
  21.         access_log = raw_input('please input apache access_log file path > ')
  22.         f = open(access_log, 'r')

  23. results={}
  24. for eachLine in f.readlines():
  25.         fields=re.match('.+"[A-Z]{3,6} (/.*) HTTP/1\.[10]".+', eachLine)
  26.         if fields is not None:
  27.                 path=fields.group(1)
  28.                 if path in results:
  29.                         results[path]+=1
  30.                 else:
  31.                         results[path]=1
  32. f.close()
  33. rresults=sorted(results.items(), key=lambda results:results[1],reverse=True)
  34. for eachItem in rresults[:10]:
  35.         print '"',eachItem[0],'" be accessed',eachItem[1],"times"
复制代码
  1. #8. 并发抓取10个URL,打印出HTTP状态码
  2. #运行环境:CentOS5.4 python 2.6.5
  3. #                Python 2.6.5 (r265:79063, Jun 29 2011, 12:30:49)
  4. #                [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
  5. #                Type "help", "copyright", "credits" or "license" for more information.
  6. #执行:
  7. #                [root@UNI-HEB-1-N015-bind-006 ~]# /usr/local/bin/python2.6 test8.py
  8. #                starting at: Thu Jun 30 11:00:31 2011
  9. #                all DONE at: Thu Jun 30 11:00:40 2011
  10. #                http://www.youku.com response:200
  11. #                http://www.sina.com.cn response:200
  12. #                http://www.baidu.com response:200
  13. #                http://www.sohu.com response:200
  14. #                http://img.163.com/abd.jpg response:404
  15. #                http://www.163.com response:200
  16. #                http://www.qq.com response:200
  17. #                https://img.alipay.com/images/cms2/201106/20110630574935.gif response:200
  18. #                http://www.google.com response:200
  19. #                http://192.168.13.110 response:0
  20. import threading
  21. import urllib
  22. from time import ctime

  23. #被测试的url
  24. urls = ['http://www.163.com',
  25.         'http://img.163.com/abd.jpg',
  26.         'http://www.google.com',
  27.         'http://www.sina.com.cn',
  28.         'http://192.168.13.110',
  29.         'http://www.sohu.com',
  30.         'http://www.baidu.com',
  31.         'http://www.qq.com',
  32.         'http://www.youku.com',
  33.         'https://img.alipay.com/images/cms2/201106/20110630574935.gif']
  34. #结果集
  35. results=[]
  36. #获取url线程
  37. def loop(i,aurl):
  38.         try:
  39.              f=urllib.urlopen(aurl)
  40.              results.append(aurl+' response:'+str(f.code));
  41.              f.close()
  42.         except IOError, e:
  43. #                        获取url出错,返回0
  44.              results.append(aurl+' response:'+str(0));   
  45.    
  46. #开始时间
  47. print 'starting at:', ctime()

  48. threads = []
  49. nloops = range(len(urls))

  50. for i in nloops:
  51.         t = threading.Thread(target=loop,args=(i,urls[i]))
  52.         threads.append(t)

  53. for i in nloops: # start threads
  54.         threads[i].start()

  55. for i in nloops: # wait for all
  56.         threads[i].join() # threads to finish

  57. print 'all DONE at:', ctime()
  58. for result in results:
  59.         print result
复制代码

论坛徽章:
0
15 [报告]
发表于 2011-06-29 14:12 |只看该作者
shell的编程大赛、AIX达人竞赛、ChinaUnix技术自测 三个活动,均未评选完,怎么又出新比赛了?那些比赛什么 ...
hq8318 发表于 2011-06-29 11:07


      http://bbs.chinaunix.net/thread-2332641-1-1.html  这个是自测活动的获奖名单,不知这位兄弟是否已经看到,
     其他两个活动,都在评选中,我们会尽快公布获奖名单。请这位兄弟放心,欢迎积极推荐其他网友参与活动!
jecoso 该用户已被删除
16 [报告]
发表于 2011-06-29 14:12 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
0
17 [报告]
发表于 2011-06-29 14:52 |只看该作者
本帖最后由 106033177 于 2011-06-29 15:22 编辑

随便写了一下 不好看
  1. #1. 去除list中的重复数据  [11, 22, 33, 11, 22] => [11, 22, 33]  
  2. #1. 去除list中的重复数据  [11, 22, 33, 11, 22] => [11, 22, 33]  
  3. li=[11, 22, 33, 11, 22]
  4. print set(li)

  5. #2. 格式化输出,三位一逗号  1234567 -> 1,234,567  
  6. #python2.5
  7. d=12345678
  8. import re
  9. pattern = re.compile(r'(?<=\d)(?=(\d\d\d)+(?!\d))')
  10. print  pattern.sub(',', str(d))
  11. #python2.7
  12. print '{:,}'.format(d)

  13. #3. 字符反转  abcde -> edcba  
  14. s= 'abcde'
  15. print s[::-1]

  16. #4. 打印当前系统的挂载点和空间大小(Linux)
  17. #官方推荐subprocess模块
  18. import os
  19. print  os.popen('df').read()


  20. #5. 模拟登录401验证网站(Basic HTTP Authentication)

  21. import urllib2, base64
  22. usr='xxx'
  23. pwd='xxx'
  24. url='http://xx.com'
  25. request = urllib2.Request(url)
  26. b64str = base64.encodestring('%s:%s' % (usr, pwd)).replace('\n', '')
  27. request.add_header("Authorization", "Basic %s" % b64str)   
  28. result = urllib2.urlopen(request)

  29. ###下面是官方文档的例子
  30. auth_handler = urllib2.HTTPBasicAuthHandler()
  31. auth_handler.add_password(realm='PDQ Application',
  32.                           uri='https://mahler:8092/site-updates.py',
  33.                           user='klem',
  34.                           passwd='kadidd!ehopper')
  35. opener = urllib2.build_opener(auth_handler)
  36. urllib2.install_opener(opener)
  37. urllib2.urlopen('http://www.example.com/login.html')



  38. #6. 获取远程某机器的系统当前日期时间(Linux)
  39. #假设开了ntp服务
  40. import socket
  41. host=''
  42. port=123
  43. s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM )
  44. requset = '\x1b' + 47 * '\0'
  45. s.sendto(requset, (host,port))
  46. data, address = s.recvfrom(1024 )
  47. #处理一下data就可以了
  48. #没开ntp服务开了telnet的话随便发个东东到23端口是不是也可?

  49.    
  50. #7. 打印Apache日志中访问次数最多的10条URL。
  51. #正则不熟随便写了一个
  52. f=open('access.log')
  53. d={}
  54. for line in f:
  55.     k=line.split('"')[1].split()[1]
  56.     if d.has_key(k):
  57.         d[k]+=1
  58.     else:
  59.         d[k]=1
  60. print sorted(d.items(),key=lambda d:d[1],reverse=True)



  61. #8. 并发抓取10个URL,打印出HTTP状态码。
  62. import threading
  63. import urllib2
  64. class Turl(threading.Thread):
  65.     def run(self):
  66.         try:
  67.             url = urllib2.urlopen('http://localhost/1')
  68.             print url.code
  69.         except urllib2.HTTPError, e:
  70.             print e.code
  71.         except Exception ,e:
  72.             print e
  73. th=[]
  74. for i in range(10):
  75.     t = Turl()
  76.     th.append(t)
  77.     t.setDaemon(True)
  78.     t.start()
  79. for t in th:
  80.     t.join()



复制代码

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:58:11
18 [报告]
发表于 2011-06-29 15:44 |只看该作者
回复 15# 无风之谷


    自测的获奖名单已公布,这个没看到,不好意思。为什么“参与ChinaUnix技术自测,赢8GB U盘大奖”帖子不作修改,说明活动结束,给出获奖名单链接?以前的活动都是这样处理的,蛮方便。我只留意大赛的帖子,极少到活动专区浏览的。

论坛徽章:
0
19 [报告]
发表于 2011-06-29 16:34 |只看该作者
回复  无风之谷


    自测的获奖名单已公布,这个没看到,不好意思。为什么“参与ChinaUnix技术自测, ...
hq8318 发表于 2011-06-29 15:44



    已经做了修改,多谢仁兄提醒。

论坛徽章:
0
20 [报告]
发表于 2011-06-29 21:39 |只看该作者
只会做前面3题,后面的没有涉足网页方面的。所以不知道。 使用:Python 2.5
#1. 去除list中的重复数据  [11, 22, 33, 11, 22] => [11, 22, 33]  
a =[11,22,33,11,22]
list(set(a))

#2. 格式化输出,三位一逗号  1234567 -> 1,234,567  

b =str(12345675625623457734)
modb = len(b)%3

def Func(string):
    result = []
    for i in range(len(string)/3):
        result.append(string[i*3i+1)*3])
    return ','.join(result)

if (modb == 0):
    print Func(b)
else:
    print b[0:modb]+','+Func(b[modb:])


#3. 字符反转  abcde -> edcba  
b = 'abcde'
''.join(sorted(list(b),reverse = True))
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP