Related
This question already has answers here:
Create a single executable from a Python project [closed]
(3 answers)
Closed 1 year ago.
I'm building a Python application and don't want to force my clients to install Python and modules.
So, is there a way to compile a Python script to be a standalone executable?
You can use PyInstaller to package Python programs as standalone executables. It works on Windows, Linux, and Mac.
PyInstaller Quickstart
Install PyInstaller from PyPI:
pip install pyinstaller
Go to your program’s directory and run:
pyinstaller yourprogram.py
This will generate the bundle in a subdirectory called dist.
pyinstaller -F yourprogram.py
Adding -F (or --onefile) parameter will pack everything into single "exe".
pyinstaller -F --paths=<your_path>\Lib\site-packages yourprogram.py
running into "ImportError" you might consider side-packages.
pip install pynput==1.6.8
still runing in Import-Erorr - try to downgrade pyinstaller - see Getting error when using pynput with pyinstaller
For a more detailed walkthrough, see the manual.
You can use py2exe as already answered and use Cython to convert your key .py files in .pyc, C compiled files, like .dll in Windows and .so on Linux.
It is much harder to revert than common .pyo and .pyc files (and also gain in performance!).
You might wish to investigate Nuitka. It takes Python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.
You will probably also get a performance improvement if you use it. It is recommended.
Yes, it is possible to compile Python scripts into standalone executables.
PyInstaller can be used to convert Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris, and AIX. It is one of the recommended converters.
py2exe converts Python scripts into only executable on the Windows platform.
Cython is a static compiler for both the Python programming language and the extended Cython programming language.
I would like to compile some useful information about creating standalone files on Windows using Python 2.7.
I have used py2exe and it works, but I had some problems.
It has shown some problems for creating single files in Windows 64 bits: Using bundle_files = 1 with py2exe is not working;
It is necessary to create a setup.py file for it to work. http://www.py2exe.org/index.cgi/Tutorial#Step2;
I have had problems with dependencies that you have to solve by importing packages in the setup file;
I was not able to make it work together with PyQt.
This last reason made me try PyInstaller http://www.pyinstaller.org/.
In my opinion, it is much better because:
It is easier to use.
I suggest creating a .bat file with the following lines for example (pyinstaller.exe must be in in the Windows path):
pyinstaller.exe --onefile MyCode.py
You can create a single file, among other options (https://pyinstaller.readthedocs.io/en/stable/usage.html#options).
I had only one problem using PyInstaller and multiprocessing package that was solved by using this recipe: https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Multiprocessing.
So, I think that, at least for python 2.7, a better and simpler option is PyInstaller.
And a third option is cx_Freeze, which is cross-platform.
pyinstaller yourfile.py -F --onefile
This creates a standalone EXE file on Windows.
Important note 1: The EXE file will be generated in a folder named 'dist'.
Important note 2: Do not forget --onefile flag
You can install PyInstaller using pip install PyInstaller
NOTE: In rare cases there are hidden dependencies...so if you run the EXE file and get missing library error (win32timezone in the example below) then use something like this:
pyinstaller --hiddenimport win32timezone -F "Backup Program.py"
I like PyInstaller - especially the "windowed" variant:
pyinstaller --onefile --windowed myscript.py
It will create one single *.exe file in a distination/folder.
You may like py2exe. You'll also find information in there for doing it on Linux.
Use py2exe.... use the below set up files:
from distutils.core import setup
import py2exe
from distutils.filelist import findall
import matplotlib
setup(
console = ['PlotMemInfo.py'],
options = {
'py2exe': {
'packages': ['matplotlib'],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgobject-2.0-0.dll',
'libgdk_pixbuf-2.0-0.dll']
}
},
data_files = matplotlib.get_py2exe_datafiles()
)
I also recommend PyInstaller for better backward compatibility such as Python 2.3 - 2.7.
For py2exe, you have to have Python 2.6.
For Python 3.2 scripts, the only choice is cx_Freeze. Build it from sources; otherwise it won't work.
For Python 2.x I suggest PyInstaller as it can package a Python program in a single executable, unlike cx_Freeze which outputs also libraries.
Since it seems to be missing from the current list of answers, I think it is worth mentioning that the standard library includes a zipapp module that can be used for this purpose. Its basic usage is just compressing a bunch of Python files into a zip file with extension .pyz than can be directly executed as python myapp.pyz, but you can also make a self-contained package from a requirements.txt file:
$ python -m pip install -r requirements.txt --target myapp
$ python -m zipapp -p "interpreter" myapp
Where interpreter can be something like /usr/bin/env python (see Specifying the Interpreter).
Usually, the generated .pyz / .pyzw file should be executable, in Unix because it gets marked as such and in Windows because Python installation usually registers those extensions. However, it is relatively easy to make a Windows executable that should work as long as the user has python3.dll in the path.
If you don't want to require the end user to install Python, you can distribute the application along with the embeddable Python package.
py2exe will make the EXE file you want, but you need to have the same version of MSVCR90.dll on the machine you're going to use your new EXE file.
See Tutorial for more information.
You can find the list of distribution utilities listed at Distribution Utilities.
I use bbfreeze and it has been working very well (yet to have Python 3 support though).
Not exactly a packaging of the Python code, but there is now also Grumpy from Google, which transpiles the code to Go.
It doesn't support the Python C API, so it may not work for all projects.
Using PyInstaller, I found a better method using shortcut to the .exe rather than making --onefile. Anyway, there are probably some data files around and if you're running a site-based app then your program depends on HTML, JavaScript, and CSS files too. There isn't any point in moving all these files somewhere... Instead what if we move the working path up?
Make a shortcut to the EXE file, move it at top and set the target and start-in paths as specified, to have relative paths going to dist\folder:
Target: %windir%\system32\cmd.exe /c start dist\web_wrapper\web_wrapper.exe
Start in: "%windir%\system32\cmd.exe /c start dist\web_wrapper\"
We can rename the shortcut to anything, so renaming to "GTFS-Manager".
Now when I double-click the shortcut, it's as if I python-ran the file! I found this approach better than the --onefile one as:
In onefile's case, there's a problem with a .dll missing for the Windows 7 OS which needs some prior installation, etc. Yawn. With the usual build with multiple files, no such issues.
All the files that my Python script uses (it's deploying a tornado web server and needs a whole freakin' website worth of files to be there!) don't need to be moved anywhere: I simply create the shortcut at top.
I can actually use this exact same folder on Ubuntu (run python3 myfile.py) and Windows (double-click the shortcut).
I don't need to bother with the overly complicated hacking of .spec file to include data files, etc.
Oh, remember to delete off the build folder after building. It will save on size.
Use Cython to convert to C, compile, and link with GCC.
Another could be, make the core functions in C (the ones you want to make hard to reverse), compile them and use Boost.Python to import the compiled code (plus you get a much faster code execution). Then use any tool mentioned to distribute.
I'm told that PyRun is also an option. It currently supports Linux, FreeBSD and Mac OS X.
This question already has answers here:
Create a single executable from a Python project [closed]
(3 answers)
Closed 1 year ago.
I'm building a Python application and don't want to force my clients to install Python and modules.
So, is there a way to compile a Python script to be a standalone executable?
You can use PyInstaller to package Python programs as standalone executables. It works on Windows, Linux, and Mac.
PyInstaller Quickstart
Install PyInstaller from PyPI:
pip install pyinstaller
Go to your program’s directory and run:
pyinstaller yourprogram.py
This will generate the bundle in a subdirectory called dist.
pyinstaller -F yourprogram.py
Adding -F (or --onefile) parameter will pack everything into single "exe".
pyinstaller -F --paths=<your_path>\Lib\site-packages yourprogram.py
running into "ImportError" you might consider side-packages.
pip install pynput==1.6.8
still runing in Import-Erorr - try to downgrade pyinstaller - see Getting error when using pynput with pyinstaller
For a more detailed walkthrough, see the manual.
You can use py2exe as already answered and use Cython to convert your key .py files in .pyc, C compiled files, like .dll in Windows and .so on Linux.
It is much harder to revert than common .pyo and .pyc files (and also gain in performance!).
You might wish to investigate Nuitka. It takes Python source code and converts it in to C++ API calls. Then it compiles into an executable binary (ELF on Linux). It has been around for a few years now and supports a wide range of Python versions.
You will probably also get a performance improvement if you use it. It is recommended.
Yes, it is possible to compile Python scripts into standalone executables.
PyInstaller can be used to convert Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris, and AIX. It is one of the recommended converters.
py2exe converts Python scripts into only executable on the Windows platform.
Cython is a static compiler for both the Python programming language and the extended Cython programming language.
I would like to compile some useful information about creating standalone files on Windows using Python 2.7.
I have used py2exe and it works, but I had some problems.
It has shown some problems for creating single files in Windows 64 bits: Using bundle_files = 1 with py2exe is not working;
It is necessary to create a setup.py file for it to work. http://www.py2exe.org/index.cgi/Tutorial#Step2;
I have had problems with dependencies that you have to solve by importing packages in the setup file;
I was not able to make it work together with PyQt.
This last reason made me try PyInstaller http://www.pyinstaller.org/.
In my opinion, it is much better because:
It is easier to use.
I suggest creating a .bat file with the following lines for example (pyinstaller.exe must be in in the Windows path):
pyinstaller.exe --onefile MyCode.py
You can create a single file, among other options (https://pyinstaller.readthedocs.io/en/stable/usage.html#options).
I had only one problem using PyInstaller and multiprocessing package that was solved by using this recipe: https://github.com/pyinstaller/pyinstaller/wiki/Recipe-Multiprocessing.
So, I think that, at least for python 2.7, a better and simpler option is PyInstaller.
And a third option is cx_Freeze, which is cross-platform.
pyinstaller yourfile.py -F --onefile
This creates a standalone EXE file on Windows.
Important note 1: The EXE file will be generated in a folder named 'dist'.
Important note 2: Do not forget --onefile flag
You can install PyInstaller using pip install PyInstaller
NOTE: In rare cases there are hidden dependencies...so if you run the EXE file and get missing library error (win32timezone in the example below) then use something like this:
pyinstaller --hiddenimport win32timezone -F "Backup Program.py"
I like PyInstaller - especially the "windowed" variant:
pyinstaller --onefile --windowed myscript.py
It will create one single *.exe file in a distination/folder.
You may like py2exe. You'll also find information in there for doing it on Linux.
Use py2exe.... use the below set up files:
from distutils.core import setup
import py2exe
from distutils.filelist import findall
import matplotlib
setup(
console = ['PlotMemInfo.py'],
options = {
'py2exe': {
'packages': ['matplotlib'],
'dll_excludes': ['libgdk-win32-2.0-0.dll',
'libgobject-2.0-0.dll',
'libgdk_pixbuf-2.0-0.dll']
}
},
data_files = matplotlib.get_py2exe_datafiles()
)
I also recommend PyInstaller for better backward compatibility such as Python 2.3 - 2.7.
For py2exe, you have to have Python 2.6.
For Python 3.2 scripts, the only choice is cx_Freeze. Build it from sources; otherwise it won't work.
For Python 2.x I suggest PyInstaller as it can package a Python program in a single executable, unlike cx_Freeze which outputs also libraries.
Since it seems to be missing from the current list of answers, I think it is worth mentioning that the standard library includes a zipapp module that can be used for this purpose. Its basic usage is just compressing a bunch of Python files into a zip file with extension .pyz than can be directly executed as python myapp.pyz, but you can also make a self-contained package from a requirements.txt file:
$ python -m pip install -r requirements.txt --target myapp
$ python -m zipapp -p "interpreter" myapp
Where interpreter can be something like /usr/bin/env python (see Specifying the Interpreter).
Usually, the generated .pyz / .pyzw file should be executable, in Unix because it gets marked as such and in Windows because Python installation usually registers those extensions. However, it is relatively easy to make a Windows executable that should work as long as the user has python3.dll in the path.
If you don't want to require the end user to install Python, you can distribute the application along with the embeddable Python package.
py2exe will make the EXE file you want, but you need to have the same version of MSVCR90.dll on the machine you're going to use your new EXE file.
See Tutorial for more information.
You can find the list of distribution utilities listed at Distribution Utilities.
I use bbfreeze and it has been working very well (yet to have Python 3 support though).
Not exactly a packaging of the Python code, but there is now also Grumpy from Google, which transpiles the code to Go.
It doesn't support the Python C API, so it may not work for all projects.
Using PyInstaller, I found a better method using shortcut to the .exe rather than making --onefile. Anyway, there are probably some data files around and if you're running a site-based app then your program depends on HTML, JavaScript, and CSS files too. There isn't any point in moving all these files somewhere... Instead what if we move the working path up?
Make a shortcut to the EXE file, move it at top and set the target and start-in paths as specified, to have relative paths going to dist\folder:
Target: %windir%\system32\cmd.exe /c start dist\web_wrapper\web_wrapper.exe
Start in: "%windir%\system32\cmd.exe /c start dist\web_wrapper\"
We can rename the shortcut to anything, so renaming to "GTFS-Manager".
Now when I double-click the shortcut, it's as if I python-ran the file! I found this approach better than the --onefile one as:
In onefile's case, there's a problem with a .dll missing for the Windows 7 OS which needs some prior installation, etc. Yawn. With the usual build with multiple files, no such issues.
All the files that my Python script uses (it's deploying a tornado web server and needs a whole freakin' website worth of files to be there!) don't need to be moved anywhere: I simply create the shortcut at top.
I can actually use this exact same folder on Ubuntu (run python3 myfile.py) and Windows (double-click the shortcut).
I don't need to bother with the overly complicated hacking of .spec file to include data files, etc.
Oh, remember to delete off the build folder after building. It will save on size.
Use Cython to convert to C, compile, and link with GCC.
Another could be, make the core functions in C (the ones you want to make hard to reverse), compile them and use Boost.Python to import the compiled code (plus you get a much faster code execution). Then use any tool mentioned to distribute.
I'm told that PyRun is also an option. It currently supports Linux, FreeBSD and Mac OS X.
I'm working on a project for which I need to a module. I want to know how to import some other module in python that is not installed.
When I write
import xaut
It gives error no module named xaut.
I have xaut-0.4.5 that I downloaded from following link.
Please help me how to use it.
Well I think following will help
Extract your zip file
Open the command line (a linux terminal or cmd on windows). I am on linux so I have a terminal.
Now enter the directory that you have extracted.
In it is a directory "python" cd into it.
If you run the ls command (if on windows run dir) you will see that in this directory there is a script "setup.py". We need to execute it for installation.
Execute this script by giving command python setup.py install
This will hopefully install it and then you would be able to import it.
Basically you have only downloaded the package. To make a package work you also need to install it. So when you download a package always search for a setup.py file.
This is certainly a duplicate question. You can look up how to add a python module to the path in windows.
here is an example
How to add to the pythonpath in windows 7?
Distutils offers existing solutions to build a Windows self-extracting EXE. Notably, I can create the package even if I'm on Ubuntu (which is essential given our automated build process).
How do I build an osx installer from an Ubuntu machine?
(This is for python 2.7)
Py2app, cx_freeze, and py2exe are for creating standalone applications, not installers.
You can use Python distutils to create a zip file of your package, and then wrap the zip file in a script that self-extracts and installs the package, like this: http://www.noah.org/wiki/Self-extracting_Python_Script
Or, if you want to create an installer that displays a GUI with a click-through license, then you need OS X PackageMaker to create an mpkg file. I don't think there's a Linux equivalent. If you want to try building an mpkg by hand, try this answer: PackageMaker for creating Mac packages on Windows/Linux
You could do the following, since OS X has a UNIX foundation. (I'm assuming it also has some standard utilities like uudecode and unzip.);
Create a zipfile for your package with the standard Python packaging tools, like distutils.
Use uuencode file.zip file.zip >uu.txt to convert this zip-file to text.
Create a shell-script.
Put the text generated by uuencode as a here-document in that shell-script, that is fed to uudecode, to recreate the zipfile. This should be the second command in the shell-script. The first commands should check for neccesary utilities.
Use whatever Python setup tools you have to install the zipfile.
Do any post-install stuff you want.
Remove the zip-file.
To install the program, run the shell-script. On UNIX, this script should be run as root. Don't know how OS X handles that, though. Below is an example (the included zipfile contains two files with only random noise) ;
#!/bin/sh
# Install script for foo
# Check for special programs that are used in this script.
PROGS="uudecode unzip python"
for P in $PROGS; do
which $P >/dev/null 2>&1
if [ $? -ne 0 ]; then
echo "$(basename $0): The program \"$P\" cannot be found."
exit 1
fi
done
uudecode <<"EOF"
begin 644 test.zip
M4$L#!`H``````(<!K$`````````````````$`!P`9F]O+U54"0`#OHZM3ZB.
MK4]U>`L``03I`P``!.D#``!02P,$"#``````A`&L0$EXM>H``#````(```<`
M'`!F;V\O8F%R550)``.XCJU/N(ZM3W5X"P`!!.D#```$Z0,``)DCNBVSM81_
MA%IQ!+LKC\;\19[/E]F!`J2J*2:9B_8#MC^KM*]]9P1]?1Y1#1+/H%Q"'2J'
M,;$7:C9E+WC]%M(BAUFN]4D\$%F63!^CA8O>'0C(-!YD?$\GQ[;M:?#>=A/[
M61XK<A/]\.?!0$QX<5]T\9<ZP$;_?PRMV-3O(NK)/<MTI,!RYA&OWRK6<8%4
M_1!T/+-'7H^V#C[AK)+U?T>UCU."G]D(+JU[8Z#1EI89#'^10B:8.2$$9Q*#
MY:L4MK'^TVF)A5)9\%"/FF+1T#;]8\,I)$CCHHF#E&,D.GVM1=2N];4J?6WR
M0+YH]DXZ"UQ$GVA^F(`5L![=/<ROX]9RQCRWJ=?+G4Y>56[H=8:!:GTA_V;V
M2V$%U5([0D;T19H]P7+^448+^&M3;[/VJDEJ-SU=Q8U=3,IV^<)A>C)]?#XG
M?-9$B#YZGML`!&`\-CP["]B'FC&K7Z)T6K_&W1K5?M&K8D&^'C^J;H[Q4/ST
M(>QL].68#X)_0#`?9<R3#:4Y#A'X-<NT9C\OM3:4[<)`)LEO#E=*/=0U#]VY
M_R!__:Q'_FP3((*8^6JQ"$_H&BIWDD.6<"3D,'<1^=^.9F^2Z7.:OE"1,SV[
M)M(9!&V(4):?M7^JFR^P"!H4U+(*A;U#Z0QA+]5ZIS]B1;K)&#LJ-Y,L9SQ.
M^Q-"&^##KQG94$L#!`H``````(8!K$#%*"OR``(````"```'`!P`9F]O+V)A
M>E54"0`#O(ZM3[R.K4]U>`L``03I`P``!.D#``!NFMNGLA(C_K!_F=T%?;P3
M#TUC7%4F+!Y#A8<SFK[;E3M.%J`YT>1AVMNJPFOE58Q["7<#AWQFZ!SG_-RW
M*4`##P.7\>+LGTBNTLH-7)CB(LJDMD)COV5'H]O8G_4I&C:PFTVC%4P=+X*B
M%A^I^$>BO+<!D\&8&GS:&VLQHJJ[!NFW0H5FD6+:'OUT2--U1HXQ2R?JF2,9
M(/#>A(/SU#.78MTFADG`ZZTK!6:Z6\;I`2?D6I;FE=_0V?4>_0MC;$0$P?H%
MDHQ]MCK4;,5W=<IZV<)<`7A_B7<_=U,:X[8/$_&/518\NNBDYS,\<',K2C]9
M4M.5UL/R<\'0E>G#$>`I>/[UX$QM.+T\LF4;D^WF6FX3.(L?2V<5B%5)$!5[
ME47K#7\&D*3Y>I)8#45-HL(!F7+$)%7C9,$_YYL]EG='3BN9W[&9!$.<.U?E
M#0L?=6#%J/32)NAMI48M",_)0#JRR!*Y2P:ZE#JWD)5/#UK!!3]*2M47V1GE
M'X0(FN%_*3BX_X'(6X!ONLKN!U/&_ML-L:^FD/24Q)S*-D8)Z>F4Y^+$]\_'
MB\$$;#D__S_RT(Y]MMK?B#%F1&C`>,)'7:12DX=F)T,/!*^(M*[,^N;6E4";
M31K\AG0#[#4L9MB.`1Z!`%#K5G)P<]0!?P\$RFUC/S:Y_Y\0*:\+$U+JEM%"
M9E!+`0(>`PH``````(<!K$`````````````````$`!#`````````$`#M00``
M``!F;V\O550%``.^CJU/=7#+``$$Z0,```3I`P``4$L!`AX#"#``````A`&L
M0$EXM>H``#````(```<`&````````````*2!/#```&9O;R]B87)55`4``[B.
MK4]U>`L``03I`P``!.D#``!02P$"'#,*``````"&`:Q`Q2#K\#`"`````#``
M!P`8````````````I(%_`#``9F]O+V)A>E54!0`#O(ZM3W5X"P`!!.D#```$
:Z0,``%!+!08``````P`#`.0```#`!```````
`
end
EOF
# Unpack your zipfile
unzip test.zip
# Go into the created subdirectory and install
cd foo
python setup.py install
# whatever post-install stuff you want goes here...
cd ..
rm -rf foo test.zip
py2app is the Mac counterpart to py2exe, but I don’t know if you can run it from Ubuntu.
pyinstaller can create OSX executables, but I've only used it on OSX myself, so I don't know if it works from Ubuntu.
I learned about this program reading the documentation for kivy, here: http://kivy.org/docs/guide/packaging-macosx.html
I hope some of this is helpful.
You have similar trouble that I suffered with.
On mac. I bet you want use dmg package instead of Installer unless you really need to install driver or some sort of DRM.
So I'll just assume that you want make your .app directory and packaging it as dmg file so that you can distribute your application easily.
To build a .app directory out of python code, you might wanna use Pyinstaller.
Pros
It's Cross Platform.
Works good on mac, windows, linux
You can control everything on command line.
It's still actively developing.
It packs required dependencies automatically and doesn't create conflict with installed Python on local machine.
Good Documentation.
Cons
bit of inconsistency between new version and old version.
To build .app using Pyinstaller, here's related document link
and to build dmg file, you can use free options out there, but for me, DMG Canvas was pretty useful.
Pros
support command line
support template (Create pretty background and folders using GUI and reuse it on command line)
support license agreement
Cons
Not Free
As far as I know, there's no unified solution from .py to build .app file and to dmg or installer.
So you should write some code to automatize it, but it's pretty straight forward, since both of them support
Command line.
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:
[\foo\module.py]
def example():
print "Hello"
[\bar\program.py]
import module
module.example()
And I run:
cd \bar
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.
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
Use stickytape module
stickytape scripts/blah --add-python-path . > /tmp/blah-standalone
This will result with a functioning script, but not necessarily human-readable.
You can try converting the script into an executable file.
First, use:
pip install pyinstaller
After installation type ( Be sure you are in your file of interest directory):
pyinstaller --onefile --windowed filename.py
This will create an executable version of your script containing all the necessary modules. You can then transfer (copy and paste) this executable to the PC or machine you want to run your script.
I hope this helps.
You should create an egg file. This is an archive of python files.
See this question for guidance: How to create Python egg file
Update: Consider wheels in 2019
The only way to send a single .py is if the code from all of the various modules were moved into the single script and they your'd have to redo everything to reference the new locations.
A better way of doing it would be to move the modules in question into subdirectories under the same directory as your command. You can then make sure that the subdirectory containing the module has a __init__.py that imports the primary module file. At that point you can then reference things through it.
For example:
App Directory: /test
Module Directory: /test/hello
/test/hello/__init__.py contents:
import sayhello
/test/hello/sayhello.py contents:
def print_hello():
print 'hello!'
/test/test.py contents:
#!/usr/bin/python2.7
import hello
hello.sayhello.print_hello()
If you run /test/test.py you will see that it runs the print_hello function from the module directory under the existing directory, no changes to your PYTHONPATH required.
If you want to package your script with all its dependencies into a single file (it won't be a .py file) you should look into virtualenv. This is a tool that lets you build a sandbox environment to install Python packages into, and manages all the PATH, PYTHONPATH, and LD_LIBRARY_PATH issues to make sure that the sandbox is completely self-contained.
If you start with a virgin Python with no additional libraries installed, then easy_install your dependencies into the virtual environment, you will end up with a built project in the virtualenv that requires only Python to run.
The sandbox is a directory tree, not a single file, but for distribution you can tar/zip it. I have never tried distributing the env so there may be path dependencies, I'm not sure.
You may need to, instead, distribute a build script that builds out a virtual environment on the target machine. zc.buildout is a tool that helps automate that process, sort of like a "make install" that is tightly integrated with the Python package system and PyPI.
I've come up with a solution involving modulefinder, the compiler, and the zip function that works well. Unfortunately I can't paste a working program here as it's intermingled with other irrelevant code, but here are some snippets:
zipfile = ZipFile(os.path.join(dest_dir, zip_name), 'w', ZIP_DEFLATED)
sys.path.insert(0, '.')
finder = ModuleFinder()
finder.run_script(source_name)
for name, mod in finder.modules.iteritems():
filename = mod.__file__
if filename is None:
continue
if "python" in filename.lower():
continue
subprocess.call('"%s" -OO -m py_compile "%s"' % (python_exe, filename))
zipfile.write(filename, dest_path)
Have you taken into considerations Automatic script creation of distribute the official packaging solution.
What you do is create a setup.py for you program and provide entry points that will be turned into executables that you will be able run. This way you don't have to change your source layout while still having the possibility to easily distribute and run you program.
You will find an example on a real app of this system in gunicorn's setup.py