<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DevOps技术分享 &#187; PYTHON</title>
	<atom:link href="http://www.showerlee.com/archives/category/programming/python/feed" rel="self" type="application/rss+xml" />
	<link>http://www.showerlee.com</link>
	<description>与你共同学习运维开发</description>
	<lastBuildDate>Mon, 19 Oct 2020 05:51:41 +0000</lastBuildDate>
	<language>zh-CN</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.6</generator>
		<item>
		<title>[Python] Multiprocessing多线程任务</title>
		<link>http://www.showerlee.com/archives/2157</link>
		<comments>http://www.showerlee.com/archives/2157#comments</comments>
		<pubDate>Mon, 11 Dec 2017 07:32:18 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[python3]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2157</guid>
		<description><![CDATA[在编写Python时, 如果我们需要同一时间内执行多个任务, 我们可以利用python内建模块multipro [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	在编写Python时, 如果我们需要同一时间内执行多个任务, 我们可以利用python内建模块multiprocessing来让其并行执行某个方法.
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;">1. 随机执行方法</span>
</p>
<p>
	# vi ~/multipro1.py
</p>
<pre class="prettyprint lang-py">import multiprocessing

def spawn(num):
    print('Sprawned! {}.'.format(num))


if __name__ == "__main__":
    for i in range(50):
        p = multiprocessing.Process(target=spawn, args=(i,))

        p.start()</pre>
<p><span style="color:#337FE5;">2. 按顺序执行方法</span> </p>
<p>
	<span># vi ~/multipro2.py</span>
</p>
<p>
	<span> </span>
</p>
<pre class="prettyprint lang-py">import multiprocessing


def spawn(num):
    print('Sprawned! {}.'.format(num))


if __name__ == "__main__":
    for i in range(50):
        p = multiprocessing.Process(target=spawn, args=(i,))

        p.start()

        # Waiting to finish One by one
        p.join()</pre>
<p>
	<span style="color:#E53333;">Tip: 这里</span><span style="color:#E53333;"><strong>if __name__ == "__main__":</strong></span><span style="color:#E53333;">的作用:</span>
</p>
<p>
	<span style="color:#E53333;">1. 当直接执行该脚本时, 内建变量__name__的值被赋予"__main__", 所以按照if逻辑, python解释器可以继续执行接下来的代码.</span>
</p>
<p>
	<span style="color:#E53333;">2. 当其他脚本去调用(import)该脚本时, __name__的值被赋予当前脚本名"multipro1", 而不是"__main__", 所以按照if逻辑, 保证if下面的代码不会被其他脚本调用.</span>
</p>
<p>
	
</p>
<p>
	<span>所以在我们日常编写脚本的时候, 可以推荐按照如下结构, 在自己使用正常的同时, 保证在其他python脚本在调用test.py中的test1(), test2(), test3()的同时, 不会去执行if条件下的方法.</span>
</p>
<p>
	<span><span style="color:#000000;"># vi test.py</span></span>
</p>
<pre class="prettyprint lang-py">def test1():
    ....

def test2():
    ....

def test3():
    ....

if __name__ == "__main__":
    ....
</pre>
<p>
	<span style="color:#337FE5;">3. 多线程处理返回值.</span>
</p>
<p>
	# vi multipro3.py
</p>
<pre class="prettyprint lang-py">from multiprocessing import pool

def job(num):
	return num * 2

if __name__ == '__main__':
	p = Pool(processes=20)
	data = p.map(job, range(5))
	data2 = p.map(job, [5, 2])
	p.close()</pre>
<p>
	<span style="color:#337FE5;">4.多线程爬取<span style="color:#337FE5;">随机</span>网站URL</span>
</p>
<p>
	<span style="color:#337FE5;"><span style="color:#000000;"># vi ~/multipro4.py</span></span>
</p>
<p>
	<span style="color:#337FE5;"><span style="color:#000000;"></p>
<pre class="prettyprint lang-py">from multiprocessing import Pool
import bs4 as bs
import random
import requests
import string

# Return Four digits domain URL
def random_starting_url():
    starting = ''.join(random.SystemRandom().choice(
        string.ascii_lowercase) for _ in range(4))
    url = ''.join(['http://', starting, '.com'])
    return url


# Correct URL if it is relative
def handle_local_links(url, link):
    if link.startswith('/'):
        return ''.join([url, link])
    else:
        return link


# Get URL from "a" tag of 'body' tag
def get_links(url):
    try:
        # Request the URL
        resp = requests.get(url)
        # return the HTML
        soup = bs.BeautifulSoup(resp.text, 'lxml')
        # Get 'body' tag of the HTML
        body = soup.body
        # Get URL from "a" tag of 'body' tag
        links = [link.get('href') for link in body.find_all('a')]
        # Correct URL if it is relative
        links = [handle_local_links(url, link) for link in links]
        # Encoding the URL to ascii
        links = [str(link.encode('ascii')) for link in links]

        return links

    except TypeError as e:
        print(e)
        print('Got a TypeError, probably got a None that we tried to iterate over')
        return([])
    except IndexError as e:
        print(e)
        print('No valid link found, return a empty list')
        return([])
    except AttributeError as e:
        print(e)
        print('Likely got None for links, so we are throwing this')
        return([])
    except Exception as e:
        print(str(e))
        return([])


def main():
    # CPU process
    process = 5
    # The site intends to scrap
    site = 3
    p = Pool(processes=process)
    # Get random URL list
    parse_us = [random_starting_url() for _ in range(site)]
    # Multiprocessing the URL and parse the result
    data = p.map(get_links, parse_us)
    # Get each URL in a list
    data = [url for url_list in data for url in url_list]
    p.close()
    # Write to txt file
    with open('urls.txt', 'w') as f:
        f.write(str(data))


if __name__ == '__main__':
    main()
</pre>
<p>
</span></span>
</p>
<p>
	
</p>
<p>
	</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2157">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] Multiprocessing多线程任务" href="http://www.showerlee.com/archives/2157">http://www.showerlee.com/archives/2157</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2157/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] 利用Beautiful Soup+Pandas+Pyqt5+Selenum进行python爬虫</title>
		<link>http://www.showerlee.com/archives/2109</link>
		<comments>http://www.showerlee.com/archives/2109#comments</comments>
		<pubDate>Thu, 07 Dec 2017 03:34:16 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[其他]]></category>
		<category><![CDATA[python3]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2109</guid>
		<description><![CDATA[Beautiful Soup, pandas, pyqt5是一组非常方便的进行网络爬虫的python模块. B [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	Beautiful Soup, pandas, pyqt5是一组非常方便的进行网络爬虫的python模块.
</p>
<p>
	<span>Beautiful Soup主要从解析好的HTML源码中抓取我们所需要的关键内容</span>
</p>
<p>
	<span>Pandas与<span>Beautiful Soup类似, 不过它侧重去抓取源码中的表格信息</span></span>
</p>
<p>
	<span><span>pyqt5这里的作用是模拟浏览器去解析源码中的Javasript, 并最终抓取JS实际的返回值.</span></span>
</p>
<p>
	
</p>
<p>
	这里我在我的Flask env下创建了一个测试页面, 用这些模块进行一些简单的页面爬虫测试.
</p>
<p><a href="http://flask.showerlee.com/scrapingtest/" rel="nofollow">http://flask.showerlee.com/scrapingtest/</a></p>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">安装环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	OS:&nbsp; &nbsp; &nbsp; &nbsp;Windows 7 x64&nbsp; &nbsp;<br />
Python:&nbsp; &nbsp;Python3.6.2<br />
Git Bash: Git-2.15.1.2-64-bit
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;">一. 环境配置:</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span style="color:#000000;">1. 安装并运行Git bash</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span style="color:#000000;"><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">2. 安装并测试python版本</span><br />
</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	<span style="color:#000000;"></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;"><span style="color:#000000;">#</span><span style="color:#000000;">&nbsp;python -V</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;"><span style="color:#000000;"> </span></span>
</p>
<pre class="prettyprint lang-py">Python 3.6.2</pre>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;background-color:#FFFFFF;">
	3. 安装相关爬虫模块
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# python -m pip install beautifulsoup4&nbsp;lxml&nbsp;pandas&nbsp;html5lib&nbsp;<span>pyqt5&nbsp;selenum</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p>
	<span style="color:#337FE5;font-size:16px;">二.&nbsp;</span><span style="color:#337FE5;font-size:16px;">Beautiful Soup演示</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi ~/scrap1.py
</p>
<p>
	<span style="color:#E53333;">Tip: 这里首先去调用io和sys模块是为了改变默认的标准输出为utf-8, 这么做是为了保证无论我们抓取的源页面是什么格式, 都不会在用BS解析时报</span><span style="color:#E53333;">UnicodeEncodeError.</span>
</p>
<pre class="prettyprint lang-py">import io
import sys
import bs4 as bs
import urllib.request

# 改变标准输出的默认编码为utf-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')

# 获取该页面编码并解码成utf-8
sauce = urllib.request.urlopen(
&nbsp; &nbsp; 'http://flask.showerlee.com/scrapingtest/').read().decode('utf-8')

# 利用BS抓取页面源代码,并利用lxml规范格式
soup = bs.BeautifulSoup(sauce, 'lxml')

# 获取页面源代码
print(soup)

# 获取titile标签源代码
print(soup.title)

# 获取titile标签name
print(soup.title.name)

# 获取titile标签字符
print(soup.title.string)
print(soup.title.text)

# 获取第一个p标签源代码
print(soup.p)

# 获取p标签源代码
print(soup.find_all('p'))

# 获取p标签所有内容
for paragraph in soup.find_all('p'):
&nbsp; &nbsp; print(paragraph.text)

# 获取页面所有内容
print(soup.get_text())

# 获取a标签所有内容
for url in soup.find_all('a'):
&nbsp; &nbsp; print(url.text)

# 获取a标签所有href链接
for url in soup.find_all('a'):
&nbsp; &nbsp; print(url.get('href'))

# 获取nav标签源代码
nav = soup.nav
print(nav)

# 获取nav标签URL
for url in nav.find_all('a'):
&nbsp; &nbsp; print(url.get('href'))

# 获取body标签内容
body = soup.body
for paragraph in body.find_all('p'):
&nbsp; &nbsp; print(paragraph.text)

# 获取div标签下body下的内容
for div in soup.find_all('div', class_='body'):
&nbsp; &nbsp; print(div.text)

# 获取table标签源代码
table = soup.table
# table = soup.find('table')
print(table)

# 获取table每行内容
table_rows = table.find_all('tr')

for tr in table_rows:
&nbsp; &nbsp; td = tr.find_all('td')
&nbsp; &nbsp; row = [i.text for i in td]
&nbsp; &nbsp; print(row)
<div>
	
</div>
</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python scrap1.py</span>
</p>
<pre class="prettyprint lang-py">......</pre>
<p>
	<span style="color:#337FE5;font-size:16px;">三. Pandas</span><span style="color:#337FE5;font-size:16px;">演示</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># vi ~/scrap2.py</span>
</p>
<pre class="prettyprint lang-py">import pandas as pd

dfs = pd.read_html(
    'http://flask.showerlee.com/scrapingtest/', header=0)

for df in dfs:
    print(df)</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python scrap2.py</span>
</p>
<pre class="prettyprint lang-py">  Program Name  Internet Points    Kittens?
0       Python        932914021  Definitely
1       Pascal              532    Unlikely
2         Lisp             1522   Uncertain
3           D#               12    Possibly
4        Cobol                3         No.
5      Fortran            52124        Yes.
6      Haskell               24        lol.</pre>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-size:16px;">四. pyqt5</span><span style="color:#337FE5;font-size:16px;">演示</span>
</p>
<p>
	<span style="color:#000000;">这里我们首先不解析JS, 直接利用Beautiful Soup去抓取p标签下class=jstest的内容</span>
</p>
<p>
	# vi ~/scrap3.py
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">import io
import sys
import bs4 as bs
import urllib.request

# 改变标准输出的默认编码为utf-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')

# 获取该页面编码并解码成utf-8
sauce = urllib.request.urlopen(
    'http://flask.showerlee.com/scrapingtest/').read().decode('utf-8')

# 利用BS抓取页面源代码,并利用lxml规范格式
soup = bs.BeautifulSoup(sauce, 'lxml')

js_test = soup.find('p', class_='jstest')

print(js_test.text)</pre>
<p>
	
</p>
<p># python scrap3.py</p>
<pre class="prettyprint lang-py">No js loaded</pre>
<p><span style="color:#E53333;">可以看到实际抓取的为未被JS处理的标签内容</span> </p>
<p>
	
</p>
<p>
	
</p>
<p>
	这里利用pyqt5<span>去抓取p标签下class=jstest的内容</span>
</p>
<p>
	# vi ~/scrap4.py
</p>
<pre class="prettyprint lang-py">import bs4 as bs
import sys
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QUrl


class Page(QWebEnginePage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebEnginePage.__init__(self)
        self.html = ''
        self.loadFinished.connect(self._on_load_finished)
        self.load(QUrl(url))
        self.app.exec_()

    def _on_load_finished(self):
        self.html = self.toHtml(self.Callable)
        # print('Load finished')

    def Callable(self, html_str):
        self.html = html_str
        self.app.quit()


def main():
    page = Page('http://flask.showerlee.com/scrapingtest/')
    soup = bs.BeautifulSoup(page.html, 'html.parser')
    js_test = soup.find('p', class_='jstest')
    print(js_test.text)


if __name__ == '__main__':
    main()
</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python scrap4.py</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"> </span>
</p>
<pre class="prettyprint lang-py">js loaded successfully</pre>
<p>
	<span style="color:#E53333;">JS解析成功.</span>
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-size:16px;">四. selenum</span><span style="color:#337FE5;font-size:16px;">演示</span>
</p>
<p>
	首先我们需要从官网下载chrome driver, 并放到脚本同路径的driver目录里.
</p>
<p>
	
</p>
<p>
	这里需要查找匹配你当前chrome浏览器版本的driver版本. 这边我的chrome版本为62.0, 所以选择driver版本为2.35.
</p>
<p>
	
</p>
<p>
	# vi selenum.py
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from bs4 import BeautifulSoup
import time, sys, io

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')

def scrape():

	chromedriver = r".\driver\chromedriver.exe"
	URL = "http://flask.showerlee.com/scrapingtest/"

	try:
		driver = webdriver.Chrome(chromedriver)
		driver.set_window_position(-10000, 0)
		driver.get(URL)
		time.sleep(10)
		result = driver.execute_script("return document.body.innerHTML").encode('utf-8')
	except TimeoutException as e:
		print(e)

	soup = BeautifulSoup(result, "lxml")

	print(soup)

	driver.close()

scrape()</pre>
<p><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python selenum.py</span> </p>
<p>
	
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">...</pre>
<p>
	
</p>
<p>
	
</p>
<p>
	更多文档:
</p>
<p><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/</a></p>
<p><a href="http://pandas.pydata.org/pandas-docs/stable/" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/</a></p>
<p><a href="http://pyqt.sourceforge.net/Docs/PyQt5/" rel="nofollow">http://pyqt.sourceforge.net/Docs/PyQt5/</a></p>
<p><a href="https://sites.google.com/a/chromium.org/chromedriver/downloads" rel="nofollow">https://sites.google.com/a/chromium.org/chromedriver/downloads</a></p>
<p><a href="https://chromedriver.storage.googleapis.com/index.html" rel="nofollow">https://chromedriver.storage.googleapis.com/index.html</a></p>
<p>
	
</p>
<p></p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2109">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] 利用Beautiful Soup+Pandas+Pyqt5+Selenum进行python爬虫" href="http://www.showerlee.com/archives/2109">http://www.showerlee.com/archives/2109</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2109/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CentOS6.9部署Python3+Flask+uWSGI+Nginx</title>
		<link>http://www.showerlee.com/archives/2024</link>
		<comments>http://www.showerlee.com/archives/2024#comments</comments>
		<pubDate>Wed, 18 Oct 2017 04:20:20 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Flask]]></category>
		<category><![CDATA[NGINX]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[python3]]></category>
		<category><![CDATA[uwsgi]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=2024</guid>
		<description><![CDATA[最近在业余时间去学习python web开发, 并用Flask做了一个BLOG小程序放到我的个人仓库和Gith [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;"><a href="http://www.showerlee.com/archives/2024/flask01"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2017/10/flask01.png" alt="flask01" width="432" height="204" class="alignnone size-full wp-image-2091" /></a><br />
</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	最近在业余时间去学习python web开发, 并用<a href="http://www.showerlee.com/archives/tag/flask" title="查看Flask中的全部文章" class="tag_link">Flask</a>做了一个BLOG小程序放到我的个人仓库和Github仓库, 这里把自己的文档分享给大家, 仅供参考
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<a href="https://github.com/showerlee/Flaskdev" target="_blank">https://github.com/showerlee/Flaskdev</a>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<a href="https://git.showerlee.com/showerlee/Flaskdev" target="_blank">https://git.showerlee.com/showerlee/Flaskdev</a>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">安装环境</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	OS(virtualbox): CentOS 6.9 x64 (flask.example.com)
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	OS(localhost):&nbsp; Windows 7 x64&nbsp; &nbsp;
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Python: Python3.4/Python2.6.6
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<a href="http://www.showerlee.com/archives/tag/flask" title="查看Flask中的全部文章" class="tag_link">Flask</a>: <a href="http://www.showerlee.com/archives/tag/flask" title="查看Flask中的全部文章" class="tag_link">Flask</a> 0.12.x
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	nWSGI:&nbsp;&nbsp;<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>-2.0.15
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	Nginx:&nbsp; nginx-&nbsp;1.10.2-1.el6
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-family:Helvetica;font-size:16px;background-color:#FFFFFF;">一. 系统环境配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1.关闭iptables和selinux
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># su - root</span><span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# service iptables stop
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># setenforce 0</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/sysconfig/selinux</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	修改
</p>
<pre class="prettyprint lang-bsh">SELINUX=disabled</pre>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;">2.添加本地host DNS</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># vi /etc/hosts</span>
</p>
<pre class="prettyprint lang-bsh">127.0.0.1    flask.example.com</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="font-size:16px;color:#337FE5;">二. Python配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1.安装<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.4源及依赖包
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="vertical-align:baseline;line-height:1.5;"># yum install epel-release -y</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum groupinstall "Development tools" -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum install zlib-devel bzip2-devel openssl-devel ncurses-devel zx-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	2.编译安装<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>.4以及pip package manager
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# wget <a href="https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tar.xz" rel="nofollow">https://www.python.org/ftp/python/3.4.3/Python-3.4.3.tar.xz</a> --no-check-certificate
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# tar xf Python-3.4.3.tar.xz
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd Python-3.4.3
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# ./configure --prefix=/usr/local --with-ensurepip=install
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# make &amp;&amp; make install
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	3.安装<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">virtualenv</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip install --upgrade pip
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	#&nbsp;pip install virtualenv
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;">三. Nginx配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1. 安装nginx package
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# yum install nginx -y
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	2.配置nginx with nWSGI
</p>
<p>
	<span>#&nbsp;vi /etc/nginx/conf.d/flask.conf</span>
</p>
<p>
	<span> </span>
</p>
<pre class="prettyprint">server {
    listen	 80;
    server_name  flask.example.com;  

    charset utf-8;

    access_log  /var/log/nginx/flask_access.log  main;
    error_log   /var/log/nginx/flask_error.log;


    location / { 
        try_files $uri @yourapplication; 
        client_max_body_size 32M;
    }
    location @yourapplication {
        include <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_params;
        <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_pass unix:/tmp/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>.sock;       
        <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_read_timeout 30s;
        <a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>_send_timeout 30s;
    }
}</pre>
<p>
	
</p>
<p>
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-family:Helvetica;font-size:16px;background-color:#FFFFFF;">四. <a href="http://www.showerlee.com/archives/tag/flask" title="查看Flask中的全部文章" class="tag_link">Flask</a>+uWSGI配置</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	1. uWSGI配置
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# mkdir -p /etc/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi /etc/<a href="http://www.showerlee.com/archives/tag/uwsgi" title="查看uwsgi中的全部文章" class="tag_link">uwsgi</a>/uwsgi.ini
</p>
<pre class="prettyprint">[uwsgi]
base = /usr/share/nginx/html/flask
 
python-path = %(base)
app = hello
module = %(app)
callable = app
 
pidfile = /tmp/uwsgi-master.pid
touch-reload = /etc/uwsgi/bin/reload
 
master = true
processes = 5
enable-threads = true
 
limit-as = 512
 
# use unix socket because it is more secure and faster than TCP socket
socket = /tmp/uwsgi.sock
chmod-socket = 660
uid = nginx
gid = nginx
 
vacuum = true
die-on-term = true
emperor = true
 
logto = /var/log/nginx/uwsgi.log</pre>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	2. 配置Flask base folder
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd /usr/share/nginx/html
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# mkdir flask
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# cd flask
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# virtualenv -p /usr/local/bin/<a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a> .py3env
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	3. 开启virtualenv <a href="http://www.showerlee.com/archives/tag/python3" title="查看python3中的全部文章" class="tag_link">python3</a>环境
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#111111;font-size:13px;">#&nbsp;source .py3env/bin/activate</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#337FE5;font-size:16px;"><span style="color:#111111;font-size:13px;">4. 在此环境安装Flask相关模块</span></span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# pip install flask uwsgi&nbsp;PyMySQL flask-wtf passlib
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">5. 写入Flask测试文件</span>
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	# vi hello.py
</p>
<pre class="prettyprint lang-py">from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()</pre>
<p>
	
</p>
<p>
	6. 创建uWSGI启动脚本
</p>
<p>
	# mkdir -p /etc/uwsgi/bin
</p>
<p>
	# vi&nbsp;<span>/etc/uwsgi/bin/uwsgi.sh</span>
</p>
<p>
	<span> </span>
</p>
<pre class="prettyprint lang-bsh">#!/bin/bash
 
# Get function from functions library
. /etc/init.d/functions
 
BASE=/usr/share/nginx/html/flask
UWSGI=$BASE/.py3env/bin
INI=/etc/uwsgi
 
start() {
  echo -n "Starting server ..." 
  touch $INI/bin/reload
  $UWSGI/uwsgi --ini $INI/uwsgi.ini &gt;/dev/null 2&gt;&amp;1 &amp;
  success $"Started"
  echo
}
 
reload() {  
  $UWSGI/uwsgi --reload /tmp/uwsgi-master.pid
  success $ "Reloaded"
  echo
}
 
stop() {
  echo -n "Stopping server ..."
  $UWSGI/uwsgi --stop /tmp/uwsgi-master.pid
  success $ "Stopped"
  echo
}
 
### main logic ###
case "$1" in
  start) 
    start
    ;;
  stop)
    stop
    ;;
  reload)
    reload
    ;;
  restart)
    stop
    start
    ;;
  *)
    echo $"Usage: $0 {start|stop|restart|reload}"
    exit 1
 
esac
exit 0</pre>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"></span>
</p>
<p>
	
</p>
<p>
	7. 修改权限<span style="color:#E53333;">(可执行并保持与nginx启动user一致)</span>
</p>
<p>
	# chmod -R 755 <span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/etc/uwsgi</span>
</p>
<p>
	# chown -R nginx:nginx <span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">/etc/uwsgi</span>
</p>
<p>
	# chmod -R 755 /usr/share/nginx/html/flask
</p>
<p>
	# chown -R nginx:nginx /usr/share/nginx/html/flask
</p>
<p>
	
</p>
<p>
	8.启动nginx+uwsgi
</p>
<p>
	# service nginx start
</p>
<p>
	#&nbsp;/etc/uwsgi/bin/uwsgi.sh start
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	
</p>
<p style="font-family:Helvetica;font-size:13px;vertical-align:baseline;color:#111111;background-color:#FFFFFF;">
	展示效果<span style="color:#E53333;">(保证Windows本地host文件能够解析flask.example.com)</span>
</p>
<p>
	<a href="http://www.showerlee.com/archives/2024/flask"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2017/10/flask.png" alt="flask" width="483" height="164" class="alignnone size-full wp-image-2088" /></a>
</p>
<p>
	
</p>
<p>
	Finished...
</p>
<p>
	
</p>
<p>
	<span style="color:#337FE5;font-size:18px;">Trouble shooting:</span>
</p>
<p>
	1.查看uwsgi log, 发现循环输出如下warning.
</p>
<p>
	# tail -f&nbsp;/var/log/nginx/uwsgi.log
</p>
<p>
	
</p>
<pre class="prettyprint lang-bsh">chdir(): Permission denied [core/emperor.c line 1499]
chdir(): Permission denied [core/emperor.c line 1499]
chdir(): Permission denied [core/emperor.c line 1499]
chdir(): Permission denied [core/emperor.c line 1499]
...</pre>
<p><span style="color:#337FE5;">Solution:</span> </p>
<p>
	
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># cd /usr/share/nginx/html</span>
</p>
<p>
	#&nbsp;<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">source .py3env/bin/activate</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"># python hellp.py</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"> </span>
</p>
<pre class="prettyprint lang-bsh"> * Running on <a href="http://127.0.0.1:5000/" rel="nofollow">http://127.0.0.1:5000/</a> (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 126-450-249</pre>
<p>
	
</p>
<p>
	若无报错提示并显示如上输出, ctrl+C 强制退出. 并重启服务, 该warning即停止.
</p>
<p>
	<span style="color:#E53333;">Tip:&nbsp; 该方法亦可测试你的主方法文件是否有语法格式错误.</span>
</p>
<p>
	#&nbsp;<span>/etc/uwsgi/bin/uwsgi.sh start</span>
</p>
<p>
	该错误会偶尔在开发过程中添加新方法后出现, 暂不清楚原因, 有经验的朋友可以留言.
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;"><br />
</span>
</p>
<p>
	<span style="color:#111111;font-family:Helvetica;font-size:13px;background-color:#FFFFFF;">My Flask APP for the reference:</span>
</p>
<p><a href="https://git.showerlee.com/showerlee/Flaskdev" rel="nofollow">https://git.showerlee.com/showerlee/Flaskdev</a></p>
<p>
	</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/2024">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="CentOS6.9部署Python3+Flask+uWSGI+Nginx" href="http://www.showerlee.com/archives/2024">http://www.showerlee.com/archives/2024</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/2024/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CentOS6升级python到2.7版本</title>
		<link>http://www.showerlee.com/archives/1706</link>
		<comments>http://www.showerlee.com/archives/1706#comments</comments>
		<pubDate>Thu, 29 Oct 2015 07:34:55 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1706</guid>
		<description><![CDATA[1.安装依赖包 #&#160;yum install zlib-devel bzip2-devel opens [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	<span style="line-height:1.5;">1.安装依赖包</span>
</p>
<p>
	#&nbsp;yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel wget xz -y
</p>
<p>
	
</p>
<p>
	2.编译安装python2.7
</p>
<p>
	# cd ~&nbsp;
</p>
<p>
	#&nbsp;wget --no-check-certificate <a href="https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz" rel="nofollow">https://www.python.org/ftp/python/2.7.9/Python-2.7.9.tar.xz</a>
</p>
<p>
	#&nbsp;tar xvfJ Python-2.7.9.tar.xz&nbsp;
</p>
<p>
	#&nbsp;cd Python-2.7.9
</p>
<p>
	# ./configure --prefix=/usr/local&nbsp;LDFLAGS="-Wl,-rpath /usr/local/lib"
</p>
<p>
	#&nbsp;make &amp;&amp; make altinstall
</p>
<p>
	#&nbsp;ln -s /usr/local/bin/python2.7 /usr/local/bin/python
</p>
<p>
	退出SSH并重新登录
</p>
<p>
	# python -V
</p>
<pre class="prettyprint lang-bsh">Python 2.7.9</pre>
<p>
	# which python
</p>
<pre class="prettyprint lang-bsh">/usr/local/bin/python</pre>
<p>
	3.安装python setuptools
</p>
<p>
	#&nbsp;python ez_setup.py
</p>
<p>
	# which easy_install
</p>
<pre class="prettyprint lang-bsh">/usr/local/bin/easy_install</pre>
<p>
	#&nbsp;/usr/local/bin/easy_install-2.7 pip
</p>
<p>
	# ll /usr/local/bin
</p>
<pre class="prettyprint lang-bsh">total 6136
-rwxr-xr-x 1 root root     101 Oct 29 02:34 2to3
-rwxr-xr-x 1 root root     323 Oct 29 02:42 easy_install
-rwxr-xr-x 1 root root     331 Oct 29 02:42 easy_install-2.7
-rwxr-xr-x 1 root root      99 Oct 29 02:34 idle
-rwxr-xr-x 1 root root     287 Oct 29 02:48 pip
-rwxr-xr-x 1 root root     289 Oct 29 02:48 pip2
-rwxr-xr-x 1 root root     293 Oct 29 02:48 pip2.7
-rwxr-xr-x 1 root root      84 Oct 29 02:34 pydoc
lrwxrwxrwx 1 root root      24 Oct 29 02:36 python -&gt; /usr/local/bin/python2.7
-rwxr-xr-x 1 root root 6224569 Oct 29 02:34 python2.7
-rwxr-xr-x 1 root root    1687 Oct 29 02:34 python2.7-config
-rwxr-xr-x 1 root root   18547 Oct 29 02:34 smtpd.py</pre>
<p>
	升级完毕</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1706">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="CentOS6升级python到2.7版本" href="http://www.showerlee.com/archives/1706">http://www.showerlee.com/archives/1706</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1706/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>[Python] 利用HTML页面查看字符串差异</title>
		<link>http://www.showerlee.com/archives/1580</link>
		<comments>http://www.showerlee.com/archives/1580#comments</comments>
		<pubDate>Mon, 28 Sep 2015 08:21:19 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1580</guid>
		<description><![CDATA[1. 比对两个字符串差异. # vi diff.py #!/usr/bin/env python import [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	1. 比对两个字符串差异.
</p>
<p>
	# vi diff.py
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python

import difflib

text1 = '''text1:
This mudule provides classes and fuctions for comparing sequences.
including HTML and context and unified diffs.
difflib document v7.4
add string
'''
text1_lines = text1.splitlines()

text2 = '''text2:
This mudule provides classes and fuctions for Comparing sequences.
including HTML and  context and unified diffs.
difflib document v7.5
''' 
text2_lines = text2.splitlines()

#d = difflib.Differ()
#diff = d.compare(text1_lines, text2_lines)

#print '\n'.join(list(diff))

d = difflib.HtmlDiff()
print d.make_file(text1_lines, text2_lines)</pre>
<p>
	运行脚本并重定向为一个html静态页面
</p>
<p>
	# chmod 755 diff.py
</p>
<p>
	#&nbsp;./diff.py &nbsp;&gt; diff.html
</p>
<p>
	浏览器打开该页面
</p>
<p>
	如图:
</p>
<p>
	<a href="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150928-1.png"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150928-1-1024x186.png" alt="QQ20150928-1" width="1024" height="186" class="alignnone size-large wp-image-1581" /></a>
</p>
<p>
	2. 比对两个配置文件的差异.
</p>
<p>
	# vi diff02.py
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python

import difflib
import sys

try:
	textfile1 = sys.argv[1]
	textfile2 = sys.argv[2]
except Exception, e:
	print "Error: " + str(e)
	print "Usage: %s filename1 filename2" %sys.argv[0]
	sys.exit()

def readfile(filename):
	try:
		with open(filename, 'rb') as fileHandle:
			text = fileHandle.read().splitlines()
		return text
	except IOError as error:
		print ('Read file Error:' + str(error))
		sys.exit()

if not textfile1 or not textfile2:
	print "Usage: %s filename1 filename2" %sys.argv[0]
	sys.exit()

text1_lines = readfile(textfile1)
text2_lines = readfile(textfile2)

d = difflib.HtmlDiff()

print d.make_file(text1_lines, text2_lines)</pre>
<p>#&nbsp;./diff02.py nginx.conf.v1 nginx.conf.v2 &gt;diff02.html</p>
<p>
	
</p>
<p>
	
</p>
<p>
	
</p>
<p><a href="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150929-1.png"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2015/09/QQ20150929-1-1024x579.png" alt="QQ20150929-1" width="1024" height="579" class="alignnone size-large wp-image-1583" /></a></p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1580">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] 利用HTML页面查看字符串差异" href="http://www.showerlee.com/archives/1580">http://www.showerlee.com/archives/1580</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1580/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] SMTP(SSL)发送邮件</title>
		<link>http://www.showerlee.com/archives/1464</link>
		<comments>http://www.showerlee.com/archives/1464#comments</comments>
		<pubDate>Thu, 27 Aug 2015 06:33:45 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1464</guid>
		<description><![CDATA[这里需要注意的是大家使用QQ邮箱(SMTL over SSL)时, 需要首先在其网页客户端后台打开SMTP/P [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	这里需要注意的是大家使用<span>QQ邮箱(<span>SMTL over SSL</span>)时</span>, 需要首先在其网页客户端后台打开SMTP/POP服务, 并且设置QQ邮箱独立密码作为SMTP登陆密码, 这样在使用MUA时就不会报Authentication failed的错误.
</p>
<p>
	QQ邮箱&nbsp;<span style="line-height:1.5;">POP3端口: 995&nbsp;</span><span style="line-height:1.5;">SMTP端口: 587</span>
</p>
<p>
	密码使用QQ邮箱独立密码
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib  
import email.encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import getpass

# Build a new attach instance
msg = MIMEMultipart()

# Mail configuration
Mail_subject = 'Python test mail'
Mail_content = 'Send with pic attachment'
Recipient_list = ['XXX@126.com', 'XXX@qq.com']
SMTP_server = "smtp.qq.com"  
SMTP_port = "587"
Username = raw_input('Please input your Username:')  
Password = getpass.getpass("Please input your Password: ")   
mail_postfix = "qq.com"  

# Mail attachment
def attach(file_path, file_name, type, postfix):
    with open(file_path + "/" + file_name, 'rb') as f:
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase(type, postfix, filename = file_name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename = file_name)
        mime.add_header('Content-ID', '&lt;0&gt;')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        email.encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

  
def send_mail(recipient, title, content): 
    # Mail info
    author = "%s&lt;%s@%s&gt;" %(Username, Username, mail_postfix)
    msg['Subject'] = title  
    msg['From'] = author  
    msg['To'] = ";".join(recipient)

    # Send attachment
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')
    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')
    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')

    try:  
        server = smtplib.SMTP(SMTP_server, SMTP_port)
        server.starttls()
        server.set_debuglevel(1)   
        server.login(Username, Password)  
        server.sendmail(author, recipient, msg.as_string())  
        server.quit()  
        return True  
    except Exception, e:
        print str(e)
        return False


if __name__ == '__main__': 
    if send_mail(Recipient_list, Mail_subject, Mail_content): 
        print "Sent Successfully"  
    else: 
        print "Sent Failure" </pre>
<p>
	
</p>
<div>
	
</div>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1464">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] SMTP(SSL)发送邮件" href="http://www.showerlee.com/archives/1464">http://www.showerlee.com/archives/1464</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1464/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] SMTP发送邮件</title>
		<link>http://www.showerlee.com/archives/1454</link>
		<comments>http://www.showerlee.com/archives/1454#comments</comments>
		<pubDate>Thu, 27 Aug 2015 05:01:51 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1454</guid>
		<description><![CDATA[这里PYTHON脚本实现的是登陆126的SMTP将邮件发送到QQ邮箱. QQ邮箱利用的是加密STMP, 需要加 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	这里<a href="http://www.showerlee.com/archives/tag/python" title="查看PYTHON中的全部文章" class="tag_link">PYTHON</a>脚本实现的是登陆126的SMTP将邮件发送到QQ邮箱.
</p>
<p>
	QQ邮箱利用的是加密STMP, 需要加密版本的童鞋请关注随后的更新.
</p>
<p>
	TIPS: 我的本地环境是MAC系统, Windows环境需要修改相应的字符编码.
</p>
<p>
	
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python
# -*- coding: utf-8 -*-

import smtplib  
import email.encoders
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
import getpass

# Build a new attach instance
msg = MIMEMultipart()

# Mail configuration
Mail_subject = 'Python test mail'
Mail_content = 'Send with attachments'
Recipient_list = ['XXX@126.com', 'XXX@qq.com']
SMTP_server = "smtp.126.com"  
Username = raw_input('Please input your Username:')  
Password = getpass.getpass("Please input your Password: ")   
mail_postfix = "126.com"  

# Mail attachment
def attach(file_path, file_name, type, postfix):
    with open(file_path + "/" + file_name, 'rb') as f:
        # 设置附件的MIME和文件名，这里是png类型:
        mime = MIMEBase(type, postfix, filename = file_name)
        # 加上必要的头信息:
        mime.add_header('Content-Disposition', 'attachment', filename = file_name)
        mime.add_header('Content-ID', '&lt;0&gt;')
        mime.add_header('X-Attachment-Id', '0')
        # 把附件的内容读进来:
        mime.set_payload(f.read())
        # 用Base64编码:
        email.encoders.encode_base64(mime)
        # 添加到MIMEMultipart:
        msg.attach(mime)

  
def send_mail(recipient, title, content): 
    # Mail info
    author = "%s&lt;%s@%s&gt;" %(Username, Username, mail_postfix)
    msg['Subject'] = title  
    msg['From'] = author  
    msg['To'] = ";".join(recipient)

    # send attachment
    msg.attach(MIMEText(content, 'plain', 'utf-8'))
    attach('/Users/XXX/Pictures/com.tencent.ScreenCapture','QQ20150827-1.png', 'image', 'png')
    attach('/Users/XXX/Work/Python','test01.py', 'txt', 'py')
    attach('/Users/XXX/Work/Python','test.zip', 'zip', 'zip')

    try:  
        server = smtplib.SMTP()
        server.set_debuglevel(1) 
        server.connect(SMTP_server)  
        server.login(Username, Password)  
        server.sendmail(author, recipient, msg.as_string())  
        server.quit()  
        return True  
    except Exception, e:
        print str(e)
        return False


if __name__ == '__main__': 
    if send_mail(Recipient_list, Mail_subject, Mail_content): 
        print "Sent Successfully"  
    else: 
        print "Sent Failure" </pre>
<p>
	
</p>
<p>
	</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1454">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] SMTP发送邮件" href="http://www.showerlee.com/archives/1454">http://www.showerlee.com/archives/1454</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1454/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] re(正则表达式)模块详解</title>
		<link>http://www.showerlee.com/archives/1441</link>
		<comments>http://www.showerlee.com/archives/1441#comments</comments>
		<pubDate>Fri, 24 Apr 2015 07:00:54 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1441</guid>
		<description><![CDATA[一、Python中转义字符 &#160; 正则表达式使用反斜杠" \ "来代表特殊形式或用作转义字符，这里跟P [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">一、Python中转义字符</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; 正则表达式使用反斜杠" \ "来代表特殊形式或用作转义字符，这里跟Python的语法冲突，因此，Python用" \\\\ "表示正则表达式中的" \ "，因为正则表达式中如果要匹配" \ "，需要用\来转义，变成" \\ "，而Python语法中又需要对字符串中每一个\进行转义，所以就变成了" \\\\ "。</span><br />
<span style="font-family:Verdana;"> 上面的写法是不是觉得很麻烦，为了使正则表达式具有更好的可读性，Python特别设计了原始字符串(raw string)，需要提醒你的是，在写文件路径的时候就不要使用raw string了，这里存在陷阱。raw string就是用'r'作为字符串的前缀，如 r"\n"：表示两个字符"\"和"n"，而不是换行符了。Python中写正则表达式时推荐使用这种形式。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">二、正则表达式元字符说明：</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">. &nbsp; &nbsp;匹配除换行符以外的任意字符</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">^ &nbsp; &nbsp;匹配字符串的开始</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">$ &nbsp; &nbsp;匹配字符串的结束</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">[] &nbsp; 用来匹配一个指定的字符类别</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">？ &nbsp; <span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">匹配</span>前一个字符字符0次到1次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">* &nbsp; &nbsp;<span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">匹配</span>前一个字符0次到无穷次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">+&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">匹配</span><span style="color:#505050;font-family:Verdana;font-size:14px;line-height:21px;background-color:#FFFFFF;">前一个字符1次到无穷次</span></span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">{} &nbsp; 对于前一个字符重复m次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">{m，n} 对前一个字符重复为m到n次</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\d &nbsp; 匹配数字，相当于[0-9]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\D &nbsp; 匹配任何非数字字符，相当于[^0-9]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\s &nbsp; 匹配任意的空白符，相当于[ fv]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\S &nbsp; 匹配任何非空白字符，相当于[^ fv]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\w &nbsp; 匹配任何字母数字字符，相当于[a-zA-Z0-9_]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\W &nbsp; 匹配任何非字母数字字符，相当于[^a-zA-Z0-9_]</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">\b &nbsp; 匹配单词的开始或结束</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">三、导入正则表达式模块</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">3.1、导入正则表达式模块</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; import &nbsp;re</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">3.2、查看正则表达式模块方法</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; dir(re)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['DEBUG', 'DOTALL', 'I', 'IGNORECASE', 'L', 'LOCALE', 'M', 'MULTILINE', 'S', 'Scanner', 'T', 'TEMPLATE', 'U', 'UNICODE', 'VERBOSE', 'X', '_MAXCACHE', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_alphanum', '_cache', '_cache_repl', '_compile', '_compile_repl', '_expand', '_pattern_type', '_pickle', '_subx', 'compile', 'copy_reg', 'error', 'escape', 'findall', 'finditer', 'match', 'purge', 'search', 'split', 'sre_compile', 'sre_parse', 'sub', 'subn', 'sys', 'template']</span><br />
<span style="font-family:Verdana;"> &gt;&gt;&gt;</span></p>
<p><span style="font-family:Verdana;"> 四、常用的正则表达式处理函数</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.1、re.search</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; &nbsp;re.search 函数会在字符串内查找模式匹配，只到找到第一个匹配然后返回，如果字符串没有匹配，则返回None。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 提示：当我们不会用模块方法的时候用help</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.search)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">search(pattern, string, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第二个参数：表示要匹配的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第三个参数：标致位，用于控制正则表达式的匹配方式</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 实例：下面的例子kuangl&nbsp;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; name="Hello,My name is kuangl,nice to meet you..."</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; k=re.search(r'k(uan)gl',name)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; if k:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">... &nbsp; &nbsp; print k.group(0),k.group(1)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">... else:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">... &nbsp; &nbsp; print "Sorry,not search!"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">...</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">kuangl uan</span><br />
<span style="line-height:1.5;"><br />
</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">4.2、re.match</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp; re.match 尝试从字符串的开始匹配一个模式，也等于说是匹配第一个单词</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.match)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">match(pattern, string, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第二个参数：表示要匹配的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 第三个参数：标致位，用于控制正则表达式的匹配方式</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; 实例：下面的例子匹配Hello单词</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; name="Hello,My name is kuangl,nice to meet you..."</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; k=re.match(r"(\H....)",name)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; if k:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">... &nbsp; &nbsp; &nbsp;print k.group(0),'\n',k.group(1)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">... else:</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">... &nbsp; &nbsp; print "Sorry,not match!"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">...</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">Hello</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">Hello</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp; &nbsp;re.match与re.search的区别：re.match只匹配字符串的开始，如果字符串开始不符合正则表达式，则匹配失败，函数返回None；而re.search匹配整个字</span><span style="font-family:Verdana;line-height:1.5;">串，直到找到一个匹配。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.3、re.findall</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp; re.findall 在目标字符串查找符合规则的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.findall)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">findall(pattern, string, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第二个参数：目标字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;但三个参数：后面还可以跟一个规则选择项</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;返回的结果是一个列表，建中存放的是符合规则的字符串，如果没有符合规则的字符串呗找到，就会返回一个空值。</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;实例：查找邮件账号</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; mail='&lt;user01@mail.com&gt; &lt;user02@mail.com&gt; <a href="mailto:user04@mail.com">user04@mail.com</a>' #第3个故意没有尖括号</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; re.findall(r'(\w+@m....[a-z]{3})',mail)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['user01@mail.com', 'user02@mail.com', 'user04@mail.com']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.4、re.sub</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;re.sub 用于替换字符串的匹配项</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.sub)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">sub(pattern, repl, string, count=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第二个参数：替换后的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第三个参数：字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第四个参数：替换个数。默认为0，表示每个匹配项都替换</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;实例：将空白处替换成-</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; test="Hi, nice to meet you where are you from?"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; re.sub(r'\s','-',test)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">'Hi,-nice-to-meet-you-where-are-you-from?'</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; re.sub(r'\s','-',test,5) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#替换至第5个</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">'Hi,-nice-to-meet-you-where are you from?'</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.5、re.split</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;re.split 用于来分割字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.split)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">split(pattern, string, maxsplit=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;第二个参数：字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;第三个参数：最大分割字符串，默认为0，表示每个匹配项都分割</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&nbsp; &nbsp;实例：分割所有的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; test="Hi, nice to meet you where are you from?"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; re.split(r"\s+",test)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">['Hi,', 'nice', 'to', 'meet', 'you', 'where', 'are', 'you', 'from?']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt; re.split(r"\s+",test,3) &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#分割前三个</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">['Hi,', 'nice', 'to', 'meet you where are you from?']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="line-height:1.5;font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">4.6、re.compile</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;re.compile 可以把正则表达式编译成一个正则对象</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; help(re.compile)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">compile(pattern, flags=0)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第一个参数：规则</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;第二个参数：标志位&nbsp;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&nbsp; &nbsp;实例：</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; test="Hi, nice to meet you where are you from?"</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; k=re.compile(r'\w*o\w*') #匹配带o的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; dir(k)</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; print k.findall(test) &nbsp; &nbsp; #显示所有包涵o的字符串</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">['to', 'you', 'you', 'from']</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt; print k.sub(lambda m: '[' + m.group(0) + ']',test) &nbsp;# 将字符串中含有o的单词用[]括起来</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">Hi, nice [to] meet [you] where are [you] [from]?</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">&gt;&gt;&gt;</span>
</p>
<p style="color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
	<span style="font-family:Verdana;">五、用urllib2、re、os 模块下载文件的脚本</span>
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python

import urllib2
import re
import os
URL='http://image.baidu.com/channel/wallpaper'
read=urllib2.urlopen(URL).read()
pat =  re.compile(r'src="http://.+?.js"&gt;')
urls=re.findall(pat,read)
for i in urls:
    url= i.replace('src="','').replace('"&gt;','')
try:
    iread=urllib2.urlopen(url).read()
    name=os.path.basename(url)
    with open(name,'wb') as jsname:
    jsname.write(iread)
except:
    print url,"url error"</pre>
<p>
	
</p>
<div style="padding:0px;margin:0px;color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
</div>
<p>
	
</p>
<div style="padding:0px;margin:0px;color:#505050;font-family:宋体, 'Arial Narrow', arial, serif;font-size:14px;background-color:#FFFFFF;">
</div>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1441">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] re(正则表达式)模块详解" href="http://www.showerlee.com/archives/1441">http://www.showerlee.com/archives/1441</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1441/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] List(列表),tuple(元组)和array的区别(转)</title>
		<link>http://www.showerlee.com/archives/1430</link>
		<comments>http://www.showerlee.com/archives/1430#comments</comments>
		<pubDate>Thu, 23 Apr 2015 06:56:54 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1430</guid>
		<description><![CDATA[Python中的列表(list)类似于C#中的可变数组（ArrayList），用于顺序存储结构。它可以方便、高 [&#8230;]]]></description>
				<content:encoded><![CDATA[<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	Python中的列表(list)类似于C#中的可变数组（ArrayList），用于顺序存储结构。它可以方便、高效的的添加删除元素，并且列表中的元素可以是多种类型。列表很多操作都跟元组一样，它们的不同在于元组是只读的，那更新列表的操作，比如切片操作来更新一部分元素的操作，就不能用于元组。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	在与array的比较中，值得注意的是，列表会使用更多的存储空间相对于array。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	通过import array导入python的数组类型，就可以使用array类型了。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	例如：
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	from array import array &nbsp;
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	node=array('H') &nbsp;
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	node.append(12) &nbsp;
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	python的array和C的数组很类似，它只能存储同样地数据类型的数据。它所占的存储空间的大小就是数据的大小。如果你相对一致类型的数据进行数学运算，那么，array将是一个很好的选择。并且它可以用于和C的代码做接口。或者可以说array就是披上了python外衣的C的数组。<br />
下面介绍一下常见操作：
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	创建列表
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	sample_list = ['a',1,('a','b')]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	Python 列表操作
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	sample_list = ['a','b',0,1,3]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	得到列表中的某一个值
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	value_start = sample_list[0]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	end_value = sample_list[-1]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	删除列表的第一个值
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	del sample_list[0]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	在列表中插入一个值
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	sample_list[0:0] = ['sample value']
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	得到列表的长度
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	list_length = len(sample_list)
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	列表遍历
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	for element in sample_list:
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	print(element)
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	Python 列表高级操作/技巧<br />
<span style="line-height:1.5;"><br />
</span>
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	<span style="line-height:1.5;">产生一个数值递增列表</span>
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	<span style="line-height:1.5;">num_inc_list = range(30)</span>
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	#will return a list [0,1,2,...,29]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	用某个固定值初始化列表
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	initial_value = 0
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	list_length = 5
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	sample_list = [ initial_value for i in range(10)]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	sample_list = [initial_value]*list_length
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	# sample_list ==[0,0,0,0,0]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	附：python内置类型
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	1、list：列表（即动态数组，C++标准库的vector，但可含不同类型的元素于一个list中）
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	a = ["I","you","he","she"] ＃元素可为任何类型。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	下标：按下标读写，就当作数组处理
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	以0开始，有负下标的使用
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	0第一个元素，-1最后一个元素，
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	-len第一个元 素，len-1最后一个元素
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	取list的元素数量
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	len(list) #list的长度。实际该方法是调用了此对象的__len__(self)方法。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	创建连续的list
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L = range(1,5) #即 L=[1,2,3,4],不含最后一个元素
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L = range(1, 10, 2) #即 L=[1, 3, 5, 7, 9]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	list的方法
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.append(var) #追加元素
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.insert(index,var)
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.pop(var) #返回最后一个元素，并从list中删除之
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.remove(var) #删除第一次出现的该元素
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.count(var) #该元素在列表中出现的个数
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.index(var) #该元素的位置,无则抛异常
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.extend(list) #追加list，即合并list到L上
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.sort() #排序
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L.reverse() #倒序
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	list 操作符:,+,*，关键字del
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	a[1:] #片段操作符，用于子list的提取
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	[1,2]+[3,4] #为[1,2,3,4]。同extend()
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	[2]*4 #为[2,2,2,2]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	del L[1] #删除指定下标的元素
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	del L[1:3] #删除指定下标范围的元素
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	list的复制
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L1 = L #L1为L的别名，用C来说就是指针地址相同，对L1操作即对L操作。函数参数就是这样传递的
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	L1 = L[:] #L1为L的克隆，即另一个拷贝。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	list comprehension
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	[ &lt;expr1&gt; for k in L if &lt;expr2&gt; ]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	2、dictionary： 字典（即C++标准库的map）
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	dict = {‘ob1′:’computer’, ‘ob2′:’mouse’, ‘ob3′:’printer’}
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	每一个元素是pair，包含key、value两部分。key是Integer或string类型，value 是任意类型。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	键是唯一的，字典只认最后一个赋的键值。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	dictionary的方法
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.get(key, 0) #同dict[key]，多了个没有则返回缺省值，0。[]没有则抛异常
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.has_key(key) #有该键返回TRUE，否则FALSE
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.keys() #返回字典键的列表
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.values()
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.items()
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.update(dict2) #增加合并字典
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.popitem() #得到一个pair，并从字典中删除它。已空则抛异常
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.clear() #清空字典，同del dict
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.copy() #拷贝字典
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	D.cmp(dict1,dict2) #比较字典，(优先级为元素个数、键大小、键值大小)
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	#第一个大返回1，小返回-1，一样返回0
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	dictionary的复制
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	dict1 = dict #别名
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	dict2=dict.copy() #克隆，即另一个拷贝。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	3、tuple：元组（即常量数组）
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	tuple = (‘a’, ‘b’, ‘c’, ‘d’, ‘e’)
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	可以用list的 [],:操作符提取元素。就是不能直接修改元素。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	4、string： 字符串（即不能修改的字符list）
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	str = “Hello My friend”
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	字符串是一个整 体。如果你想直接修改字符串的某一部分，是不可能的。但我们能够读出字符串的某一部分。
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	子字符串的提取
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	str[:6]
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	字符串包含 判断操作符：in，not in
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	“He” in str
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	“she” not in str
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	string模块，还提供了很多方法，如
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.find(substring, [start [,end]]) #可指范围查找子串，返回索引值，否则返回-1
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.rfind(substring,[start [,end]]) #反向查找
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.index(substring,[start [,end]]) #同find，只是找不到产生ValueError异常
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.rindex(substring,[start [,end]])#同上反向查找
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.count(substring,[start [,end]]) #返回找到子串的个数
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.lowercase()
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.capitalize() #首字母大写
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.lower() #转小写
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.upper() #转大写
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.swapcase() #大小写互换
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.split(str, ‘ ‘) #将string转list，以空格切分
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	S.join(list, ‘ ‘) #将list转string，以空格连接
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	处理字符串的内置函数
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	len(str) #串长度
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	cmp(“my friend”, str) #字符串比较。第一个大，返回1
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	max(‘abcxyz’) #寻找字符串中最大的字符
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	min(‘abcxyz’) #寻找字符串中最小的字符
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	string的转换
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	oat(str) #变成浮点数，float(“1e-1″) 结果为0.1
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	int(str) #变成整型， int(“12″) 结果为12
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	int(str,base) #变成base进制整型数，int(“11″,2) 结果为2
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	long(str) #变成长整型，
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	long(str,base) #变成base进制长整型，
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	字符串的格式化（注意其转义字符，大多如C语言的，略）
</p>
<p style="font-family:Arial;font-size:14px;text-indent:2em;background-color:#FFFFFF;">
	str_format % (参数列表)</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1430">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] List(列表),tuple(元组)和array的区别(转)" href="http://www.showerlee.com/archives/1430">http://www.showerlee.com/archives/1430</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1430/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[Python] 调取MYSQL数据并插入到CSV文件</title>
		<link>http://www.showerlee.com/archives/1425</link>
		<comments>http://www.showerlee.com/archives/1425#comments</comments>
		<pubDate>Fri, 17 Apr 2015 06:35:12 +0000</pubDate>
		<dc:creator>showerlee</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[PYTHON]]></category>
		<category><![CDATA[其他]]></category>

		<guid isPermaLink="false">http://www.showerlee.com/?p=1425</guid>
		<description><![CDATA[如何利用python脚本将远程数据库查询值,并将该值按照csv中"column A"对应关系整体插入到"col [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>
	如何利用python脚本将远程数据库查询值,并将该值按照csv中"column A"对应关系整体插入到"column B",最近handle了一个case,联想到python天生对数据处理较shell有明显的优势,最后尝试用脚本搞定这个看起来逻辑很简单,但又不简单的data processing.
</p>
<p>
	Target:
</p>
<p>
	column A 是DB内存储的若干Project name,需要通过查询数据库,获取这些project name在DB对应的Project key的具体值,并插入column A后保存.
</p>
<p>
	
</p>
<p>
	
</p>
<pre class="prettyprint lang-py">#!/usr/bin/env python
# encoding: utf-8

import MySQLdb
import csv
import sys

# Define csv list
Csv_content = []
Csv_content_edited = []

# Define project list
Project_names = []

# Define db list
Db_content = []

# Define the file that needs to be handled.
try:
	file_name = sys.argv[1]
	new_file_name = file_name.split('.')[0] + '_new.' + file_name.split('.')[1]
except IndexError:
	pass

def selectDB():
	# Open db connection
	db = MySQLdb.connect("test.com", "testuser", "testuser", "testdb")

	# Use cursor() fuction to get current db cursor
	cursor = db.cursor()

	Csv_content_edited = readContent(file_name)

	for c in range(1,len(Csv_content_edited)):
		Project_names.append(Csv_content_edited[c][0])

	Project_name_string = ",".join(['"' + p + '"' for p in Project_names])

	# SQL "SELECT" statement
	sql = 'select pname,pkey from project where pname in (%s)' %Project_name_string
	
	try:
		# Execute SQL
		cursor.execute(sql)
		# Obtain all the record list
		results = cursor.fetchall()

		for row in results:
			#lower_user_name = row[3]
			Db_content.append(row)

		return Db_content
	except:
		print "Error: unable to fecth data"

	# Close connection
	db.close()


def readContent(file_name):
	# Read the csv file,then put it into list.
	with open(file_name, 'r') as csvfile:
		csv_reader = csv.reader(csvfile, delimiter=',')
		for row in csv_reader:			 
			if row[0]:
				Csv_content.append(row)
	return Csv_content


def insert_col():
	Csv_content_edited = readContent(file_name)
	# Insert null value to each components of "Csv_content_edited" afterward.
	for i in range(0,len(Csv_content_edited)):
		Csv_content_edited[i].insert(1,'')

	# Define the second inserted column title.
	Csv_content_edited[0][1] = "Pkey"
	# Grab the users data from db.
	Db_content = selectDB()
	# print Db_content
	
	for d in range(0,len(Db_content)):
		Pkey = Db_content[d][1]
		Pname = Db_content[d][0]
		for c in range(0,len(Csv_content_edited)):  
			if Csv_content_edited[c][0] == Pname:
				Csv_content_edited[c][1] = Pkey
	# print Csv_content_edited

	pname_list = []
	Csv_content_edited_new = []
	
	for c in range(0,len(Csv_content_edited)):
		if not Csv_content_edited[c][0] in pname_list:
			pname_list.append(Csv_content_edited[c][0])
			Csv_content_edited_new.append(Csv_content_edited[c])
	# print Csv_content_edited_new
	
	return Csv_content_edited_new



# Write the csv file. 
def writeContent():
	with open(new_file_name,'wb') as csvfile:
		csv_writer = csv.writer(csvfile)
		csv_writer.writerows(insert_col())


# Execute the finnal function.	
if __name__ == '__main__':
	try:
		writeContent()
	except (IOError,NameError,IndexError):
		print "Please type the correct file name. e.g: '" + sys.argv[0] + " testfile.csv'"
	else:
		print 'The result file is: %s' %new_file_name

</pre>
<p>Result:</p>
<p>
	
</p>
<p>
	Before the change:
</p>
<p>
	
</p>
<p>
	<a href="http://www.showerlee.com/wp-content/uploads/2015/04/QQ20150417-2.png"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2015/04/QQ20150417-2.png" alt="QQ20150417-2" width="133" height="93" class="alignnone size-full wp-image-1427" /></a>
</p>
<p>
	after the change:
</p>
<p>
	<a href="http://www.showerlee.com/wp-content/uploads/2015/04/QQ20150417-1.png"><img onerror="javascript:this.src='http://www.showerlee.com/wp-content/themes/BYMT/images/images_error.jpg'" src="http://www.showerlee.com/wp-content/uploads/2015/04/QQ20150417-1.png" alt="QQ20150417-1" width="132" height="90" class="alignnone size-full wp-image-1426" /></a>
</p>
<p>
	
</p>
<p>
	</p>
<div>声明: 本文采用 <a rel="external" href="http://creativecommons.org/licenses/by-nc-sa/3.0/deed.zh" title="署名-非商业性使用-相同方式共享 3.0 Unported">CC BY-NC-SA 3.0</a> 协议进行授权</div><div>转载请注明来源：<a rel="external" title="DevOps技术分享" href="http://www.showerlee.com/archives/1425">DevOps技术分享</a></div><div>本文链接地址：<a rel="external" title="[Python] 调取MYSQL数据并插入到CSV文件" href="http://www.showerlee.com/archives/1425">http://www.showerlee.com/archives/1425</a></div>]]></content:encoded>
			<wfw:commentRss>http://www.showerlee.com/archives/1425/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
