[Python] argparse "parse_args" fails when packaged in exe via pyinstaller

Discussão em 'Python' iniciado por Stack, Maio 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'm packaging my script into an EXE with pyinstaller, which works great! However, when I do this, I lose the ability to read parameters via CMD window. My code is structured like so:

    import argparse
    import sys

    class CLI():
    def __init__(self, args:list, foo, bar):
    self.foo = foo
    self.bar = bar
    self.parser = argparse.ArgumentParser(description='parser')
    self.add_args() # Add arguments to self.parser

    self._args = self.parser.parse_args(args) # This line never runs or does nothing

    def add_args(self):
    self.parser.add_argument('-w', help='Hello World')

    if __name__ == "__main__":

    foo = 1
    bar = 2
    cli = CLI(args=sys.argv[1:], foo=foo, bar=bar)


    I also use the following script to package this code into an EXE with pyinstaller:

    pyinstaller --noconfirm --onefile --windowed "script.py"


    I can't tell for the life of me why it fails to execute parse_args when launching via EXE. Normal .py script works fine, and I've verified that the args variable is passed in successfully and contains the arguments I pass in.To pass in args, I'm using a CMD windows to execute a command such as script.py -h.

    I've seen some folks discussing this behavior in this thread, and I implemented the above based on some comments there. Unfortunately, it's still not working.

    Using the code above, I expect argparse to execute the same actions it performs when passing in arguments via script.exe -h as it does via python script.py -h. I'm not seeing anywhere that this configuration is explicitly unsupported, so any ideas?

    EDIT: Included minimum reproducible example and example pyinstaller script that reproduces this behavior.

    Continue reading...

Compartilhe esta Página