1. 程式人生 > >使用py2exe生成獨立的exe檔案

使用py2exe生成獨立的exe檔案

今天寫一個python小指令碼,在windows下將當前狀態下,所有的task的名字輸出到一個檔案裡,然後將這個指令碼轉化成exe檔案。

先看一下python指令碼TaskNameList.py:

Python程式碼
  1. import subprocess  
  2. # running the command "tasklist" in cmd.exe
  3. popen = subprocess.Popen("tasklist",stdout=subprocess.PIPE,shell= True)  
  4. namelist = []  
  5. # get the task name
  6. for line in
     popen.stdout.readlines()[3:]:  
  7.     name = line.split()[0]  
  8.     if name notin namelist:  
  9.         namelist.append(name)  
  10. popen.stdout.close()  
  11. # wirte the name into the file TaskNameList
  12. file = open(r".\TaskNameList.txt",'w')  
  13. file.writelines('\n'.join(namelist))      
  14. file.close()  

接下來我用了第三方的軟體py2exe,將python指令碼軟化為exe可執行檔案,在看完了py2exe官網上的tutorial後,寫一個setup.py指令碼

Python程式碼
  1. from distutils.core import setup  
  2. import py2exe  
  3. setup(console=["'TaskNameList.py"])  

 執行python setup.py py2exe後,會生成兩個資料夾dist 和build,build檔案對我們沒有多大用處,而在dist資料夾下,會有一個TaskNameList.exe可執行檔案,這就我們要的exe檔案,但是,執行這個檔案的提前是不能脫離dist這個資料夾,在這個資料夾下的其它檔案都是在exe執行時會呼叫到的,所以要想移動這個檔案到,要連同dist這個資料夾一起移動,否則,單獨移動exe檔案,它是無法正常執行的。所以 最好的能生成一個將exe所呼叫的檔案和其本身都繫結到一起的exe檔案。

在查閱了資料後,我重寫了一setup.py方法:

Python程式碼
  1. from distutils.core import setup  
  2. import py2exe  
  3. import sys  
  4. includes = ["encodings""encodings.*"]    
  5. sys.argv.append("py2exe")  
  6. options = {"py2exe":   { "bundle_files"1 }    
  7.                 }   
  8. setup(options = options,  
  9.       zipfile=None,   
  10.       console = [{"script":'TaskNameList.py'}])  

這次直接執行python setup.py,就可以生成一個獨立的exe檔案了,當然這個檔案還是在dist資料夾下。

這個檔案比之前那個的最重要的改進在於兩個引數:

Python程式碼
  1. "bundle_files"1

 我們可以看看官網給出的有效的bundle_files的值:

3 (default)

don't bundle

2

bundle everything but the Python interpreter

1

bundle everything, including the Python interpreter

Python程式碼
  1. zipfile=None,   

zipfile = None指定把library.zip也打包進exe 裡了。

附:

  給生成的exe檔案加上圖示:

Python程式碼
  1. from distutils.core import setup  
  2. import py2exe  
  3. import sys  
  4. includes = ["encodings""encodings.*"]    
  5. sys.argv.append("py2exe")  
  6. options = {"py2exe":   { "bundle_files"1 }    
  7.                 }   
  8. setup(options = options,  
  9.       zipfile=None,   
  10.       console = [{"script":'TaskNameList.py', 'icon_resources':[(1, 'logo.ico')]}])