Introduction
It's wired that Python don't have the feature that can compile python code as binary file. Thus, I plan to write a simple program as python loader generator.
The technique of this program is quite low level, I just create a "c language" based binary file to execute the target python script.
Below are the core python script for this project
#! /usr/bin/python
######################################################################
#
# Project: PyQtLoader
# Version: 1.0
# Date: Thu May 28 00:00:00 2009
# Author: Xin-Yu Lin
# E-mail: nxforce@yahoo.com
# WebSite: http://nxforce.blogspot.com
# Description: Python Code Loader
#
######################################################################
############### import modules #######################################
import os
import py_compile
import Ui_PyQtLoaderClass
from PyQt4 import QtCore, QtGui
############### PyQtLoaderClass Start ################################
class PyQtLoaderClass(QtGui.QWidget):
def __init__(self, parent = None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_PyQtLoaderClass.Ui_PyQtLoaderClass()
self.ui.setupUi(self)
self.filePath = ''
def onGenerateClicked(self):
if(self.filePath == ''):
self.onExportClicked()
else:
#py_compile.compile(self.filePath)
splitext = os.path.splitext(self.filePath)
srcFileName = splitext[0]+'.c'
file = open(srcFileName, 'w')
file.write("#include <stdio.h>\nint main(void){ system(\"python ./" + os.path.basename(self.filePath) + "\");return 0;}\n")
file.close()
os.system("gcc -o "+splitext[0]+" "+srcFileName)
os.remove(srcFileName)
QtGui.QMessageBox.information(self, 'Message', " Done! ", QtGui.QMessageBox.Ok)
def onExportClicked(self):
filePath = self.ui.fileDialog_export.getOpenFileName(self, 'Open File', QtCore.QDir.homePath()+'/Desktop', "python(*.py)")
self.ui.lineEdit_path.setText(filePath)
self.filePath = str(filePath)
############### PyQtLoaderClass End ##################################
As you can see, all coding, compiling processes can be done in runtime. After the processing completed, you will see a binary file which has the same filename with your python script.
Screenshot
The usage is very very simple, just click the left-hand side's button to load your python script, and than click the 'Generate' to create the binary loader.
#For each loader, it will takes about 60 KBs of memory.
0 意見:
Post a Comment