Freeze a program created with Python's `click` pacage
Asked Answered
O

1

10

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"
Orest answered 13/7, 2017 at 20:10 Comment(1)
Did you try adding a main function?Thoroughbred
A
11

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)
Armoured answered 26/7, 2017 at 22:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.