The most stupid method is described above. Its disadvantage is that there is too much redundancy and the waste of space is too large.
Today we will introduce an optimization method, which only extractsProgramUsed.
After work, paste implementation firstCode, And then add the principle if you have time in the next day.
#-*-Coding: GBK-*-import sysimport osimport shutil # obtain the path def getmodulespath (): lst = [] # sys. modules is a dictionary in the following format: # {'SITE': <module 'SITE' from 'd: \ python27 \ Lib \ site. pyc'>, for V in SYS. modules. itervalues (): S = STR (v) if "from" in S: Data = S. split ("'") lst. append (data [-2]) else: Print "module:", sreturn lst # extract file def extractfiles (destdir, files): destdir. replace ("/", "\") if destdir [-1]! = '\': Destdir + = '\' for F in files: DEST = filiterpath (destdir, f) copyf (DEST, F) # Remove the maximum absolute path def filiterpath (destdir, srcfile) from the filter path: DEST = destdirmaxlen = 0for path in SYS. path: lenp = Len (PATH) If lenp <Len (srcfile) and Path = srcfile [: lenp]: If maxlen <lenp: deST = destdir + srcfile [lenp + 1:] maxlen = lenpdest. replace ("/", "\") if '. 'In DEST: # Remove the file name P = DeST. rfind ('\') If P> = 0: DEST = Dest [: p] Return DEST # copy file # If the target path does not exist, Def copyf (destdir, srcfile) is created: If not OS. path. isfile (srcfile): Print "error: File % s not exist! "% Srcfilereturn falseif not OS. path. isdir (destdir): OS. mkdir (destdir) print "make dir:", destdirtry: shutil. copy2 (srcfile, destdir) print "copy file: % s to % s" % (srcfile, destdir) handle T ioerror: Print "error: copy % s to % s faild "% (srcfile, destdir) return falsereturn truedef test (): A = getmodulespath () extractfiles (" testpg \ ",) # The extracted files are stored in the testpg directory.
Note: You can call the test () method to extract data at the end of the C ++ program, all the py files used by the program are extracted (including self-written and System ^ o ^ ).Then, the extracted pyfile is compressed into python27.zip and stored in the C ++ program directory together with python27.dll.
The principle is also very simple:
SYS. Modules stores all the modules since the program runs and the absolute path of The py file where the module is located. This is also the all modules on which the program runs. Package these files into pythonxx.zip and place them in the C ++ application directory. Then, the program can automatically search for The py file in the ZIP file.
Remove the absolute path. Remove the maximum length path based on the python path in SYS. Path. For example:
SYS. path = ['d :\\ python27 ', 'd :\\ python27 \ Lib', 'd: \ python27 \ Lib-TK ',...], the path of a py file is D: \ python27 \ Lib \ AAA \ BBB \ XXX. PY, the relative path should be AAA \ BBB, rather than Lib \ AAA \ BBB.
Directory organization after packaging: