最近有一个小项目,有如下的需求:
# coding=utf-8
from distutils.core import setup
import os
def get_all_dir(path):
"""
获取指定路径下的所有文件
"""
all_file = []
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
all_file.append(dirpath)
return all_file
if __name__ == '__main__':
all_file = get_all_dir('A') + get_all_dir('B') # 获取相对路径下A和B两个文件夹下的所有文件
setup(name='Example', # 所要安装的软件名
version="1.0", # 版本
description="This is example", # 对所安装软件的描述
author="author", # 作者
author_email='my email', # 邮箱
packages=all_file, # 要打包的文件
package_data={'': ['*.*']}, # 所有文件类型都打包
classifiers=[
'Development Status :: 5 - Production/Stable',
'Operating System :: Microsoft :: Windows',
'Natural Language :: Chinese (Simplified)',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Python Modules'
], # 需要参照https://pypi.python.org/pypi?%3Aaction=list_classifiers,用于发布在PYPI上
install_requires=[
'pyserial==3.2.1'
], # 依赖包,如果没有安装,会提示缺少,并安装失败
)
python setup.py bdist_msi
# coding=utf-8
import os
import sys
import subprocess
config_file = r"C:\Python27\Lib\site-packages\B\lib\configuration\config.cfg"
import sys
from subprocess import check_call
### 设置系统环境变量所需代码
if sys.hexversion > 0x03000000:
import winreg
else:
import _winreg as winreg
ENV_VARAIABLE = 'Result_Path'
class Win32Environment:
def __init__(self, scope):
assert scope in ('user', 'system')
self.scope = scope
if scope == 'user':
self.root = winreg.HKEY_CURRENT_USER
self.subkey = 'Environment'
else:
self.root = winreg.HKEY_LOCAL_MACHINE
self.subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
def getenv(self, name):
key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_READ)
try:
value, _ = winreg.QueryValueEx(key, name)
except WindowsError:
value = ''
return value
def setenv(self, name, value):
key = winreg.OpenKey(self.root, self.subkey, 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key, name, 0, winreg.REG_EXPAND_SZ, value)
winreg.CloseKey(key)
try:
check_call('''\
"%s" -c "import win32api, win32con; assert win32api.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')"''' % sys.executable)
except Exception as e:
print e.message
### 设置系统环境变量所需代码 end
def search_content(str, lists):
"""
查找str是否存在于lists中,不存在就退出程序
"""
for i in lists:
if str in i:
return lists.index(i)
print "The section not found"
os._exit(1)
def run_command_line(command_line):
"""
运行command line
"""
print("run:" + command_line)
p = subprocess.Popen(command_line, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
(stdout, stderr) = p.communicate()
try:
print("stdout:" + stdout)
print("stderr:" + stderr)
except:
pass
def main():
# 静默安装MSI安装包
run_command_line("msiexec /i " + sys.path[0] + r"\Example-1.0.win32.msi /qb REBOOT=SUPPRESS")
# 接受参数
section = sys.argv[1]
attribute = sys.argv[2]
change = sys.argv[3]
# 读取配置文件内容
file = open(config_file, 'r')
content = file.readlines()
file.close()
# 修改配置文件的某个属性值
index = search_content(section, content)
is_change = False
for change_str in content[index + 1:]:
if "[" in change_str:
if not is_change:
print "Property does not exist or not in this section"
break
if attribute in change_str:
content[content.index(change_str)] = change_str[:change_str.index("=") + 1] + change + "\n"
is_change = True
break
# 把修改后的内容写入配置文件
file = open(config_file, 'w')
for i in content:
file.write(i)
file.close()
if __name__ == "__main__":
# 如果没有参数,就默认直接安装MSI安装包
# 如果有参数,但是参数个数不足,直接报错退出
if len(sys.argv) == 1 and sys.argv[0] == "commonlib.exe":
run_command_line("msiexec /i " + sys.path[0] + r"\Example-1.0.win32.msi /qb REBOOT=SUPPRESS")
elif len(sys.argv) != 4:
print "Usage: commonlib.py "
sys.exit(1)
else:
main()
# 设置系统环境变量
e = Win32Environment(scope="system")
e.setenv(ENV_VARAIABLE, r'C:\Local')
print "Setup Success!"
# -*- mode: python -*-
block_cipher = None
a = Analysis(['Example.py'], # 主要打包的主py文件
pathex=['C:\\Users\\abc\\Documents'], # 打包路径
binaries=None,
datas=None,
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
a.datas+= [('Exmaple.msi', r'C:\Users\abc\Documents\Example-1.0.win32.msi', 'DATA'),]# 附加文件,打包时加入到EXE文件中,让我们可以在py文件中调用
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas, # 打包文件列表
name='examlpe',# exe文件的名字
debug=False,
strip=False,
upx=True,
console=True )
pyinstaller Example.spec
运行成功后,会生成build和dist两个文件夹,我们依然只看dist文件夹,里面example.exe就是我们所需要的