Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Freeze a program created with Python's `click` pacage

I've got a command line program that uses Python's click package. I can install and run it locally, no problem with:

pip install --editable . # (or leave out the editable of course)

Now, I'd like to create an executable file that can be distributed and run standalone. Typically, since I'm in a Windows environment, I would use one of py2exe, pyinstaller or cx_Freeze. However, none of these packages work.

More specifically, they all generate an executable, but the executable does nothing. I suspect this problem is because my main.py script doesn't have a main function. Any suggestions would be very helpful, thanks in advance!

Can reproduce the issues with code copied from here.

hello.py

import click

@click.command()
def cli():
    click.echo("I AM WORKING")

setup.py

from distutils.core import setup
import py2exe

setup(
name="hello",
version="0.1",
py_modules=['hello'],
install_requires=[
    'Click'
],
entry_points="""
[console_scripts]
hello=hello:cli
""",
console=['hello.py']
)

If someone could supply a working setup.py file to create an executable and any other required files, that would be much appreciated.

From the console:

python setup.py py2exe
# A bunch of info, no errors
cd dist
hello.exe
# no output, should output "I AM WORKING"
like image 637
fenkerbb Avatar asked Jul 13 '17 20:07

fenkerbb


1 Answers

I much prefer pyinstaller to the other alternatives, so I will cast an answer in terms of pyinstaller.

Starting click app when frozen

You can detect when your program has been frozen with pyinstaller, and then start the click app like:

if getattr(sys, 'frozen', False):
    cli(sys.argv[1:])

Building an exe with pyinstaller

This simple test app can be built simply with:

pyinstaller --onefile hello.py

Test Code:

import sys
import click

@click.command()
@click.argument('arg')
def cli(arg):
    click.echo("I AM WORKING (%s)" % arg)

if getattr(sys, 'frozen', False):
    cli(sys.argv[1:])

Testing:

>dist\test.exe an_arg
I AM WORKING (an_arg)
like image 136
Stephen Rauch Avatar answered Oct 14 '22 08:10

Stephen Rauch