How to concatenate multiple Python source files into a single file?

早过忘川 提交于 2019-11-30 16:28:02

If this is on google app engine as the tags indicate, make sure you are using this idiom

def main(): 
    #do stuff
if __name__ == '__main__':
    main()

Because GAE doesn't restart your app every request unless the .py has changed, it just runs main() again.

This trick lets you write CGI style apps without the startup performance hit

AppCaching

If a handler script provides a main() routine, the runtime environment also caches the script. Otherwise, the handler script is loaded for every request.

Szymon Lipiński

I think that due to the precompilation of Python files and some system caching, the speed up that you'll eventually get won't be measurable.

Doing this is unlikely to yield any performance benefits. You're still importing the same amount of Python code, just in fewer modules - and you're sacrificing all modularity for it.

A better approach would be to modify your code and/or libraries to only import things when needed, so that a minimum of required code is loaded for each request.

Without dealing with the question, whether or not this technique would boost up things at your environment, say you are right, here is what I would have done.

I would make a list of all my modules e.g. my_files = ['foo', 'bar', 'baz']

I would then use os.path utilities to read all lines in all files under the source directory and writes them all into a new file, filtering all import foo|bar|baz lines since all code is now within a single file.

Of curse, at last adding the main() from __init__.py (if there is such) at the tail of the file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!