Gather all Python modules used into one folder?

后端 未结 3 458
花落未央
花落未央 2021-01-12 04:58

I don\'t think this has been asked before-I have a folder that has lots of different .py files. The script I\'ve made only uses some-but some call others & I don\'t kno

相关标签:
3条回答
  • 2021-01-12 05:23
    # zipmod.py - make a zip archive consisting of Python modules and their dependencies as reported by modulefinder
    # To use: cd to the directory containing your Python module tree and type
    # $ python zipmod.py archive.zip mod1.py mod2.py ...
    # Only modules in the current working directory and its subdirectories will be included.
    # Written and tested on Mac OS X, but it should work on other platforms with minimal modifications.
    
    import modulefinder
    import os
    import sys
    import zipfile
    
    def main(output, *mnames):
        mf = modulefinder.ModuleFinder()
        for mname in mnames:
            mf.run_script(mname)
        cwd = os.getcwd()
        zf = zipfile.ZipFile(output, 'w')
        for mod in mf.modules.itervalues():
            if not mod.__file__:
                continue
            modfile = os.path.abspath(mod.__file__)
            if os.path.commonprefix([cwd, modfile]) == cwd:
                zf.write(modfile, os.path.relpath(modfile))
        zf.close()
    
    if __name__ == '__main__':
        main(*sys.argv[1:])
    
    0 讨论(0)
  • 2021-01-12 05:29

    Freeze does pretty close to what you describe. It does an extra step of generating C files to create a stand-alone executable, but you could use the log output it produces to get the list of modules your script uses. From there it's a simple matter to copy them all into a directory to be zipped up (or whatever).

    0 讨论(0)
  • 2021-01-12 05:32

    Use the modulefinder module in the standard library, see e.g. http://docs.python.org/library/modulefinder.html

    0 讨论(0)
提交回复
热议问题