Search code examples
pythoncx-freeze

cx_Freeze generated EXE prints no Console output


I am facing a difficulty compiling Python script with cx_Freeze 5.0. The script compiles correctly, EXE is generated. Before all the requirements were met, a series of error messages were printed to the console. After adding all requirements, running the EXE makes no output to console. The program stops silently without printing anything. If run directly from Python it works as expected:

>python testScript.py -p 12 aaa/bbb.ccc
Test script with the following params:
Namespace(input_file='aaa/bbb.ccc', param=12)

I think the issue is related to argparse package I use.

Below is a little test script and compile script I wrote that reproduces teh behaviour.

from sys import exit, argv
import os
import argparse

if __name__ == "__main__":   
    parser = argparse.ArgumentParser(prog=os.path.basename(argv[0]),
        description='Command line parser test.')
    parser.add_argument('input_file',
                        metavar='path/to/file',
                        help='path to source file)')
    parser.add_argument('-p','--param', required=False,
                        metavar='par',
                        type=int, default=1,
                        help='test parameter')

    try:
        args = parser.parse_args()
    except argparse.ArgumentError:
        exit("Use -h option for help on using.")

    if args.input_file is None:
        parser.print_usage()
        exit(0)

#%% display parameters
    print "Test script with the following params:"
    print args

cx_Freeze compile script:

from cx_Freeze import version, setup, Executable
import sys

print "Compilation using cx_Freeze version", version

productName = "testScript"

build_exe_options = {"packages": ["sys","os","argparse"]}

exe_options = Executable(
                          script = productName+".py",
                          targetName = productName+".exe",
                          base = None
                         )
setup(
      name=productName,
      version="0.0",
      author="mstankie",
      description="test script",
      options = {"build_exe": build_exe_options},
      executables=[exe_options]
)

Why the program prints nothing to the console?


Solution

  • The problem wasn't related to argparse... Finally I tried printing the contents of __name__. It seems, if run directly from Python interpreter the variable contains '__main__', but

    the variable __name__ when run as cx_Freeze-compiled EXE, contains 'nameofthegeneratedexe__main__' string.

    Changing the line if __name__ == "__main__": (no. 5 in the listing above) to:

    if "__main__" in __name__:
    

    solved the issue.