在CPython當中,我們可以透過Cython的技術,將Python程式碼加以編譯來保護程式碼,並加速程式的執行。一般作法需要另外準備setup.py,並透過命令列來加以編譯。為了簡化步驟,我寫了以下的script。在Anaconda Spyder執行該script,隨即跳出檔案選擇視窗。選擇要編譯的.pyx檔即可生成.pyc檔。
import os
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
pyx_path = filedialog.askopenfilename(initialdir = "d:/demo",
title = "Select file",
filetypes = (("pyx files","*.pyx"),
("all files","*.*")))
pyx_dir = os.path.dirname(pyx_path)
os.chdir(pyx_dir)
pyx_name = os.path.basename(pyx_path)
setup = '''from distutils.core import setup
from Cython.Build import cythonize
setup(name='', ext_modules=cythonize("{}"))'''.format(pyx_name)
with open('setup.py', 'w') as f:
f.write(setup)
os.environ['path']+=';C:\ProgramData\Anaconda3'
os.system('python setup.py build_ext --inplace')
os.startfile(pyx_dir)
沒有留言:
張貼留言