2014年11月6日 星期四

Visual Studio - 自訂巨集變數

開發環境:Visual Studio 2013

事件狀況:使用QT時,會需要QTDIR這個巨集變數(macro variable),該變數正常要定義在.vcxproj.user這個檔案中,可是在某些狀況下,專案會找不到QTDIR這個變數,QT沒有自動建立。

解決方法:
  1. 開啟屬性管理員視窗,從檢視(View)→屬性管理員(Property Manager)。
  2. 展開專案項目與組態項目,會看到字尾.user的屬性項目。
  3. 開啟.user的屬性項目,點選通用屬性(Common Properties)→使用者巨集(User-Defined Macros)。
  4. 點選加入巨集,就可以自訂QTDIR這個巨集變數,值就是QT函式庫的路徑。

2014年7月29日 星期二

Python - 自訂訊息格式

Python有很好用的logging函式庫,並不必要自己去定義打印訊息的方法。下面僅是提供一個簡單的例子,說明如果想要取得呼叫來源的檔名和行數,可以利用traceback的堆疊訊息。
import traceback
import os, time

def __formalizeMessage(message):
    FILE, LINE, FUNCTION, TEXT = (0, 1, 2, 3)
    stack = traceback.extract_stack(limit = 3)
    return "{file}({line}) - {message}".format(file = os.path.split(stack[0][FILE])[-1], line = stack[0][LINE], message = message)

def printError(message):
    print("{0} [Error] {1}".format(time.asctime(), __formalizeMessage(message)))

def main():
    printError("Hello")  # The line number is 12.

if __name__ == "__main__":
    main()

打印出來的訊息為:
Wed Jul 30 14:56:05 2014 [Error] test.py(12) - Hello

2014年7月24日 星期四

Python - 序數轉換

忘了是在哪裡看到的,不常用,不過是一個滿有趣的寫法,利用python的dict,能將數字1變成1st,數字2變成2nd,數字3變成3rd,數字4變成4th等。
## Returns the ordinal number of a given integer, as a string. eg. 1 -> 1st, 2 -> 2nd, 3 -> 3rd, etc.
def ordinal(num):
    num = int(num)
    if 10 <= num % 100 < 20:
        return "{0}th".format(num)
    else:
        ords = {1 : "st", 2 : "nd", 3 : "rd"}.get(num % 10, "th")
        return "{0}{1}".format(num, ords)

Python - 移除目錄和檔案

不管用什麼程式語言,都會遇到一個狀況,就是要刪除檔案或目錄時,沒有一個簡易型函式能一起處理檔案和目錄。沒辦法,只好自己用已有的函式拼湊一個符合目標的函式。
import os, shutil

## Remove a file or directory.
def remove(path) :
    retval = False
    try:
        if os.path.exists(path):
            if os.path.isdir(path):
                shutil.rmtree(path, ignore_errors = True)
                retval = True
            elif os.path.isfile(path):
                os.remove(path)
                retval = True
        else:
            retval = True
    except OSError as e:
        print(e)
    except Exception as e:
        print(e)
    return retval

Python - URL判斷

Python的urllib能夠容易地處理request和response,也能夠協助URL的拆裝,但似乎少了一個檢查是不是URL的函式,在這裡提供一個簡易型函式,可以分辨是否帶有通訊協定的URL。(不限於http或https,只要有通訊協定的語法都可以)
import os
import urllib.parse

def isURL(path):
    return not os.path.isdir(path)\
        and not os.path.isfile(path)\
        and urllib.parse.urlparse(path).scheme != ""

Python - 檔案IO

Python對於檔案IO很友好,擁有一些常用的函式庫,最基本的莫過於open這個內建函式。
with open("text.txt", mode = "w") as file:
    file.write("Hello")
如果單純使用open,勢必要記得呼叫close關閉檔案串流,而且還要配合一些exception使用try except;但如果配合with ... as ...使用,則close的動作可以交給python,即使有exception發生,python也會呼叫close。

有些文章會說使用with ... as ...等於try ... except ... finally ...,但事實上使用with ... as ...還是有可能會發生exception,關鍵就在於檔名,如果open一個空字串,則整個with ... as ...還是會拋出exception,所以最好習慣上在with外頭加一層try ... except ...。

2014年7月23日 星期三

Python - namedtuple

C++中有struct型態可以快速建立一個輕型類別,在該類別中可以含有一些屬性,並用object.attribute的方式存取。在Python則能使用namedtuple做到這件事情。
from collections import namedtuple

## Component definition
Component_t = namedtuple("Component", ["data", "size", "source"])

## Create a component.
def Component(data, size, source):
    return Component_t(data, size, source)

## Convert a list of parameters into a component of module.
#  @param   array is a list.
def toComponent(array):
    return Component_t._make(array)


## Usage
comp1 = Component(data = "hello", size = 5, source = "test.txt")
print(comp1.data)

array = ["world", 5, "test.txt"]
comp2 = toComponent(array)
print(comp2.data)