Search code examples
pythoncommand-lineattributesparameter-passingexe

How to pass input values in python executable file?


Some times, when we call an .exe file in command prompt, we also pass some parameters or attributes in one command. which are mostly following hyphen "--" or simply following a space. For example, app.exe parameters or app.exe --parameter="value". How we can create such type type of exe files in python.

For this I created a python file "file.py" which has following code :

variable = input()
print("You have entered "+variable)

After exporting it into "file.exe" I tried to call it as :file.exe "any_text But it doesn't work but I try to call it as :file.exe --variable="any_text". but still not worked. Let me know how to create such type of .exe files. Thanks in advance.


Solution

  • When creating an executable file in Python that which accepts command-line arguments, better to use the argparse module.

    Example:

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('--variable', help='Input variable')
    
    args = parser.parse_args()
    
    print("You have entered " + args.variable)
    

    Then, when run the script, you can pass in the value of the "--variable" argument such as:

    file.exe --variable any_text