Windows 7 下 Python3 整体复制方式的机器间迁移
所用的某计算机 B 运行 Windows7 x64 旗舰版操作系统,
需要在该计算机安装 Python3.7 及 numpy、scipy、Pillow、Spyder 等,
但该机器无法连接互联网,无法通过网路安装。
另有一台计算机 A 安装好了上面的全套组件,想将其 Python3.7 整个文件夹复制到
计算机 B,进行快速的布设。
过程如下:
1 复制 Python3.7 安装文件和 计算机 A 上的全套组建所在的 Python3.7 文件夹所有内容
到计算机 B
2 计算机 B 运行 Python3.7 安装文件,完成 Python3.7 的安装
3 将计算机 A 复制来的 Python3.7 文件夹覆盖步骤 2 安装好的组件
4 运行计算机 B 的 Python 组件,报错。提示运行 python.exe 或 pythonw.exe 出错。
出错信息显示运行所用的python.exe 或 pythonw.exe 的路径为在机器 A 上的路径,
与其在计算机 B 上的真实路径不一致,按照计算机 A 路径设置找不到可执行文件。
5 查找上述路径信息保存位置,定位到 Scripts 路径下各组件的 exe 文件中。
6 用十六进制编辑器,将路径信息替换为机器 B 的正确路径,运行正常。
7 编写了 Python 脚本,实现批量处理,将所有 exe 文件路径信息查找一遍。
脚本如下,使用时修改 to_be_replaced 和 to_be_replaced 即可:
'''
将一台机器上的Python3文件复制到另外机器上后,
修改.exe文件内部包含的 python.exe 或 pythonw.exe
路径信息的脚本。
本脚本只枚举给定路径下的文件,不递归搜索子目录。
Coder: Farman
Date : 2018-07-18
'''
import os
def replace(contents, to_be_replaced, replaced_with):
front = contents.rfind(to_be_replaced)
if front == -1:
tail = -1
else:
tail = front + len(to_be_replaced)
if front == -1:
replaced = b''
else:
replaced = contents[:front] + replaced_with + contents[tail:]
return replaced
def fix_file(file_name, to_be_replaced, replaced_with):
print('Fix:', file_name, end = ' ---> ')
try:
f = open(file_name, 'r+b')
contents = f.read()
f.close()
contents = replace(contents, to_be_replaced, replaced_with)
if len(contents) == 0:
print('Not found -', to_be_replaced)
else:
try:
f = open(file_name, 'w+b')
f.write(contents)
f.close()
print('Success.')
except:
print('Failed to write.')
except:
print('Failed to open.', file_name)
return
def fix_files(file_names, to_be_replaced, replaced_with):
for file_name in file_names:
fix_file(file_name, to_be_replaced, replaced_with)
return
def enum_files(work_path, file_ext):
work_path = work_path.rstrip('\\') + '\\'
files = os.listdir(work_path)
filtered_files = []
for f in files:
if os.path.isdir(f):
continue
elif f.rfind(file_ext) == len(f) - len(file_ext):
filtered_files.append(work_path + f)
else:
pass
return filtered_files
if __name__ == '__main__':
files_to_check = enum_files('.', 'exe')
to_be_replaced = br'#!c:\users\farman-x220\appdata\local\programs\python\python37\python.exe'
replaced_with = br'#!C:\Users\Administrator\AppData\Local\Programs\Python\Python37\python.exe'
fix_files(files_to_check, to_be_replaced, replaced_with)
to_be_replaced = br'#!c:\users\farman-x220\appdata\local\programs\python\python37\pythonw.exe'
replaced_with = br'#!C:\Users\Administrator\AppData\Local\Programs\Python\Python37\pythonw.exe'
fix_files(files_to_check, to_be_replaced, replaced_with)