怎么将python代码封装成一个程序

Python067

怎么将python代码封装成一个程序,第1张

如何将python程序封装成exe可执行文件

将python程序直接转成exe程序的方法很多,主流的工具有PyInstaller、cx_freeze、py2exe等,论及优缺点,可谓各有千秋。然而,再好的工具在使用的时候也会遇到各种各样的问题。这里无法比较哪个好那个坏,不同工具对不同类型程序的处理能力不同,也许你用这个方法转化出来的程序出问题了,换个方法就行了。本文主要介绍py2exe的安装和使用。

py2exe的安装

点此下载和64位python2.7配套版本。

傻瓜式安装,就是一步一步往下点。

py2exe的使用

将python安装路径添加到系统环境变量Path值中。(若已添加,请忽略此步)

建立setup.py文件,文件中输入以下代码:

from distutils.core import setupimport py2exe

setup(console=["将要转换的文件名称.py"])123

在终端(cmd)输入以下命令: 

setup.py py2exe 

这样便完成了从.py文件到 .exe文件的转换,生成的软件在dist文件夹内。

这里需要注意的是:不同python程序不能一概而论,具体情况需要具体讨论。

例:当运行出错,提示缺少sip文件时,setup.py可修改为:

from distutils.core import setupimport py2exe

setup(console=[{"script":"main.py"}], options={"py2exe":{"includes":["sip"]}})123

例:当你不想dos窗口停留,需要其一闪而过时,setup.py可修改为:

from distutils.core import setup  

import py2exe  

setup(window=['name.py'])  #这里console改为window那么dos窗口不出现

Python:常用函数封装:

def is_chinese(uchar):

"""判断一个unicode是否是汉字"""

if uchar >= u'\u4e00' and uchar<=u'\u9fa5':

return True

else:

return False

def is_number(uchar):

"""判断一个unicode是否是数字"""

if uchar >= u'\u0030' and uchar<=u'\u0039':

return True

else:

return False

def is_alphabet(uchar):

"""判断一个unicode是否是英文字母"""

if (uchar >= u'\u0041' and uchar<=u'\u005a') or (uchar >= u'\u0061' and uchar<=u'\u007a'):

return True

else:

return False

def is_other(uchar):

"""判断是否非汉字,数字和英文字符"""

if not (is_chinese(uchar) or is_number(uchar) or is_alphabet(uchar)):

return True

else:

return False

def B2Q(uchar):

"""半角全角"""

inside_code=ord(uchar)

if inside_code<0x0020 or inside_code>0x7e: #不是半角字符就返回原来的字符

return uchar

if inside_code==0x0020: #除了空格其他的全角半角的公式为:半角=全角-0xfee0

inside_code=0x3000

else:

inside_code+=0xfee0

return unichr(inside_code)

def Q2B(uchar):

"""全角转半角"""

inside_code=ord(uchar)

if inside_code==0x3000:

inside_code=0x0020

else:

inside_code-=0xfee0

if inside_code<0x0020 or inside_code>0x7e: #转完之后不是半角字符返回原来的字符

return uchar

return unichr(inside_code)

def stringQ2B(ustring):

"""把字符串全角转半角"""

return "".join([Q2B(uchar) for uchar in ustring])

def uniform(ustring):

"""格式化字符串,完成全角转半角,大写转小写的工作"""

return stringQ2B(ustring).lower()

def string2List(ustring):

"""将ustring按照中文,字母,数字分开"""

retList=[]

utmp=[]

for uchar in ustring:

if is_other(uchar):

if len(utmp)==0:

continue

else:

retList.append("".join(utmp))

utmp=[]

else:

utmp.append(uchar)

if len(utmp)!=0:

retList.append("".join(utmp))

return retList