Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
86 views
in Technique[技术] by (71.8m points)

How to build a single python file from multiple scripts?

I have a simple python script, which imports various other modules I've written (and so on). Due to my environment, my PYTHONPATH is quite long. I'm also using Python 2.4.

What I need to do is somehow package up my script and all the dependencies that aren't part of the standard python, so that I can email a single file to another system where I want to execute it. I know the target version of python is the same, but it's on linux where I'm on Windows. Otherwise I'd just use py2exe.

Ideally I'd like to send a .py file that somehow embeds all the required modules, but I'd settle for automatically building a zip I can just unzip, with the required modules all in a single directory.

I've had a look at various packaging solutions, but I can't seem to find a suitable way of doing this. Have I missed something?

[edit] I appear to be quite unclear in what I'm after. I'm basically looking for something like py2exe that will produce a single file (or 2 files) from a given python script, automatically including all the imported modules.

For example, if I have the following two files:

[foomodule.py]
def example():
    print "Hello"

[arprogram.py]
import module
module.example()

And I run:

cd ar
set PYTHONPATH=foo
program.py

Then it will work. What I want is to be able to say:

magic program.py

and end up with a single file, or possibly a file and a zip, that I can then copy to linux and run. I don't want to be installing my modules on the target linux system.

question from:https://stackoverflow.com/questions/9002275/how-to-build-a-single-python-file-from-multiple-scripts

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found this useful:

http://blog.ablepear.com/2012/10/bundling-python-files-into-stand-alone.html

In short, you can .zip your modules and include a __main__.py file inside, which will enable you to run it like so:

python3 app.zip

Since my app is small I made a link from my main script to __main__.py.

Addendum:

You can also make the zip self-executable on UNIX-like systems by adding a single line at the top of the file. This may be important for scripts using Python3.

echo '#!/usr/bin/env python3' | cat - app.zip > app
chmod a+x app

Which can now be executed without specifying python

./app

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...