顯示具有 python 標籤的文章。 顯示所有文章
顯示具有 python 標籤的文章。 顯示所有文章

2016-03-13

[Python Basic Syntax] Assert 指令

05:39 Posted by ZMH , No comments

Assert 指令

assert可以引發exception,只是其為引發AssertionError

assert 一串指令
其背後運作原理如下:
if __debug__:
    if not 一串指令:
        raise AssertionError

assert 一串指令, 一串指令(2)
其背後運作原理如下:
if __debug__:
    if not 一串指令:
        raise AssertionError(一串指令(2))

在平時python直譯器啟動時__debug__會被設成True而執行assert內部code
但如果加上參數"-O" 即會將__debug__設成False,導致不執行assert
如此的功能可以用於單元測試,確保一些變數按照我們的要求走,不然就會導致引起AssertionError

2016-01-27

Python打包成執行檔(Python 3.5 | PyInstaller 3.1)

06:52 Posted by ZMH , 6 comments

Python 3.5 嘗試 PyInstaller 3.1

Introduction

Python是個很方便的語言,但是當你需要將程式分享給他人使用時,這種script language需要安裝相對應的直譯器和環境,大幅降低檔案分享的容易程度,因此我們能藉由一些第三方軟體來將python的程式碼打包成Windows、Linux或Mac可以執行的執行檔(ex: exe..)

目前我知道能打包python的工具有py2exe、pyinstaller、cx-freeze

雖然py2exe很小巧方便,但似乎不支援python3.5
所以本篇嘗試使用 pyinstaller!

安裝(在command line下指令)

安裝指令(若不清楚pip可看這篇)
pip install pyinstaller
或是更新
pip install --upgrade pyinstaller

使用方式

這套件功能很強大,官方檔案
pyinstaller [options] script [script ...] | specfile
不加任何參數,即可將檔案打包成一個資料夾(包含執行檔+引入的函式庫)
pyinstaller myscript.py
若要將整個資料夾打包成一個執行檔
pyinstaller -F myscript.py
其他功能未來介紹,或請參閱官方檔案

問題

  1. 若產生"failed to create process."
    目前推測可能有些bug導致無法解析含空格的檔案路徑(EX:預設的Python 3.5即有空格),因此可以選擇把python裝在沒有含空格的路徑,重新install所以相關檔案。
    或是:
    cd /path.../python 3.5/Scripts
    python pyinstaller-script.py path/YourScript.py