使用py2exe生成獨立的exe檔案
今天寫一個python小指令碼,在windows下將當前狀態下,所有的task的名字輸出到一個檔案裡,然後將這個指令碼轉化成exe檔案。
先看一下python指令碼TaskNameList.py:
Python程式碼- import subprocess
- # running the command "tasklist" in cmd.exe
- popen = subprocess.Popen("tasklist",stdout=subprocess.PIPE,shell= True)
- namelist = []
- # get the task name
-
for line in
- name = line.split()[0]
- if name notin namelist:
- namelist.append(name)
- popen.stdout.close()
- # wirte the name into the file TaskNameList
- file = open(r".\TaskNameList.txt",'w')
- file.writelines('\n'.join(namelist))
- file.close()
接下來我用了第三方的軟體py2exe,將python指令碼軟化為exe可執行檔案,在看完了py2exe官網上的tutorial後,寫一個setup.py指令碼
- from distutils.core import setup
- import py2exe
- setup(console=["'TaskNameList.py"])
執行python setup.py py2exe後,會生成兩個資料夾dist 和build,build檔案對我們沒有多大用處,而在dist資料夾下,會有一個TaskNameList.exe可執行檔案,這就我們要的exe檔案,但是,執行這個檔案的提前是不能脫離dist這個資料夾,在這個資料夾下的其它檔案都是在exe執行時會呼叫到的,所以要想移動這個檔案到,要連同dist這個資料夾一起移動,否則,單獨移動exe檔案,它是無法正常執行的。所以 最好的能生成一個將exe所呼叫的檔案和其本身都繫結到一起的exe檔案。
在查閱了資料後,我重寫了一setup.py方法:
Python程式碼- from distutils.core import setup
- import py2exe
- import sys
- includes = ["encodings", "encodings.*"]
- sys.argv.append("py2exe")
- options = {"py2exe": { "bundle_files": 1 }
- }
- setup(options = options,
- zipfile=None,
- console = [{"script":'TaskNameList.py'}])
這次直接執行python setup.py,就可以生成一個獨立的exe檔案了,當然這個檔案還是在dist資料夾下。
這個檔案比之前那個的最重要的改進在於兩個引數:
Python程式碼- "bundle_files": 1
我們可以看看官網給出的有效的bundle_files的值:
3 (default) |
don't bundle |
2 |
bundle everything but the Python interpreter |
1 |
bundle everything, including the Python interpreter |
- zipfile=None,
zipfile = None指定把library.zip也打包進exe 裡了。
附:
給生成的exe檔案加上圖示:
Python程式碼- from distutils.core import setup
- import py2exe
- import sys
- includes = ["encodings", "encodings.*"]
- sys.argv.append("py2exe")
- options = {"py2exe": { "bundle_files": 1 }
- }
- setup(options = options,
- zipfile=None,
- console = [{"script":'TaskNameList.py', 'icon_resources':[(1, 'logo.ico')]}])