Search code examples
pythonargumentscross-compilingpyinstallerpy2exe

Creating exe from py which passes argument by default on execution?


If we assume this is the test.py code:

import sys
 
for arg in sys.argv:
    print arg
print "Hello World!"

By using tools like auto-py-to-exe or pyinstaller or py2exe or ..., How can we make an exe which passes an specific argument on execution by default ? For example: By using a tool we make an test.exe from the test.py and by executing the test.exe it will use foobar as arg, The output of the test.exe execution is:

foobar
Hello World!

I have already tested auto-py-to-exe and pyinstaller but there is not such an option in both. I should mention that i am more interested in using [any] tools and not just modifying the python source. Because the modifying might be a hard task in bigger sources.


Solution

  • I would recommend using pythons ArgumentParser (https://docs.python.org/2/howto/argparse.html) and just set a default= value for your argument.

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("argument", default="foobar")
    args = parser.parse_args()
    
    print arg
    print "Hello World!"
    

    You can also restructure your called python script to implement a "main" method with the arguments you need:

    def main(argument):
        print argument
        print "Hello World!"
    

    For your specific executables just create separate wrapper-scripts:

    foobar.py

    from test import main
    test("foobar")
    

    anotherfoobar.py

    from test import main
    test("anotherfoobar")
    

    Now you can use pyinstaller to create executables of foobar.py and anotherfoobar.py separatly.