- 第一個 Python 練習
- Environment:
- windows 8
- Python 3.4
- IDE:
- Visual Studio 2013 + Python Tool for Visual Studio (PTVS)
- PyScripter
- test other IDE:
- Sublime Text
- PyCharm: seems to need more resources to run it, like busy CPU.
- Target:
- 跟 python 親近一點
- write function in another file
- read/write file (IO) with utf-8 encoding
- access MariaDB/MySQL database
- use GitHub: workingrichard/PythonFirst
Practice:
- 如眾所皆知(而我不太熟悉)的,需要用到的 module,必須使用 import module_name 的方式加入。如果要使用其他 py 檔案的功能,也必須使用 import 主檔名。
- 前面有空格或 tab 是重要的,表示為前一行的 block 區塊。因此,在 Python 中沒有 begin/end, 或是 { } 來表示 block。
- 也不需要分號(;)。咦? 有加也沒事?! 看來,Python 容錯蠻大的。
- py 內容如果有非 ascII code 的碼,則必須小心 py 檔案本身的 encoding。
- 存取檔案:
- 可以使用 with open() as f 的方式,如此離開範圍,就會自動 close file handler。
- 另一種寫法是使用 yield return 的方式回傳每一行,如此可以不需將檔案內容全部讀進 memory 再回傳。
- 存取 MariaDB/MySQL,必須先安裝 MySQL Connector/Python。
- 試過使用 pip or easy-install 安裝 mysql,似乎都沒有成功。
- mysql.connector 似乎沒有支援 with as 的方式。
- sample code 如下。
- 記錄一下,以供參考。
------------------------------
PythonApplication1.py
import os;
import modFile
import AccessMariaDB
print('Hello World')
fname = modFile.outputFile(20)
print("get it: " + fname)
contents = modFile.readFile(fname)
print("lines: " + str(len(contents)))
for s in contents:
print(s)
print("testing yield return....");
for s in modFile.readFileYield(fname):
print(s.replace("\r\n", "").replace("\n",""))
AccessMariaDB.ReadURLTask()
modFile.py
#coding=utf-8
#檔案有中文字,使用 Big5 可以,utf-8 不行。必須將檔案 encoding 也另存成 utf-8 才行。
import os
def outputFile(n):
strs = list()
for i in range(0, n):
strs.append("str" + str(i))
for s in strs:
print(s)
print(strs)
dir = os.getcwd() #os.path.dirname(os.path.abspath(__file__))
dir = os.path.join(dir, "_data")
if not os.path.exists(dir):
os.mkdir(dir)
fname = os.path.join(dir, "test.txt")
print(fname)
f = None
with open(fname, 'w', encoding="utf-8") as f:
for i in range(0, len(strs)):
f.write(str(i) + "\t" + strs[i] + "\t測試\r\n")
return fname
def readFile(fname):
contents = list()
if not os.path.exists(fname):
print("file not exist: " + fname)
return contents
with open(fname, encoding = "utf-8") as sr:
for line in sr:
contents.append(line)
return contents
def readFileYield(fname):
if not os.path.exists(fname):
return;
with open(fname, encoding = "utf-8") as sr:
for line in sr:
yield line
AccessMariaDB.py
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Richard
#
# Created: 06/06/2015
# Copyright: (c) Richard 2015
# Licence:
#-------------------------------------------------------------------------------
import mysql.connector
#from mysql.connector import (connection)
#import MySQLdb
#def main():
# pass
#if __name__ == '__main__':
# main()
def ReadURLTask():
conn = mysql.connector.MySQLConnection(user = 'root', password = '12345', host = 'localhost', database = 'mytask')
cursor = conn.cursor()
cursor.execute("select version();")
data = cursor.fetchone()
print("DB version: " + data[0])
cursor.execute("select * from urltask")
for x in cursor.fetchall():
for y in x:
print(y)
cursor.execute("select id, url from urltask")
for (id, url) in cursor:
print(str(id) + " : " + url)
conn.close()
return
0 意見:
張貼留言