Search code examples
pythonpyinstaller

windows Command prompt vanishes after running a python script converted to .exe using pyinstaller


I am using python3.7

I wrote a script which takes some inputs (e.g. a=input("enter a value")

it runs smoothly if i go to its path and run it on command prompt. I can give input also and run . If i give wrong input it shows an error or exception(traceback)

So i converted it to .exe using pyinstaller

when i run .exe , it asks for input as expected ,it runs and vanishes , i can't see any output. if i give a wrong input it suddenly vanishes without showing any traceback

I read many questions regarding this on stackoverflow and google , so i added an input statement at end to make program wait before exiting,

but it doesn't works in case of wrong input or if i use sys.exit("test failed") in some cases it just vanishes ,how to resolve and keep cmd window open?

Adding script for e.g.:

import sys
x = int(input("  enter a number :"))
y = int(input("  enter a number :"))
if x>100 or y > 100 :
    sys.exit("ERROR :value out of range")
z=x+y;
print(z)
input('press enter to exit')

if inputs are less than 100 and integer then script(.exe file) runs smoothly and i get message "press enter to exit"

but if input number greater than 100 or if i put a "string or float" in input , cmd window vanishes without display any traceback

whereas if i run py file from cmd then i get proper traceback for wrong input.


Solution

  • You could use try-except and input() function, so that when there is any error, it will wait for the user to interact.

    Look at this example -

    a = input('Please enter a number: ')
    
    try:
        int(a) # Converts into a integer type
    
    except ValueError as v:
        # This will run when it cannot be converted or if there is any error
        print(v) # Shows the error
        input() # Waits for user input before closing
    

    For your e.g code, try this -

    import sys
    
    try:
        x = int(input("  enter a number :"))
        y = int(input("  enter a number :"))
    
    except ValueError as v:
        print(v)
        input('Press any key to exit ')
        sys.exit()
    
    if x>100 or y > 100 :
        try:
            sys.exit("ERROR :value out of range")
    
        except SystemExit as s:
            print(s)
            input('Press any key to exit ')
            sys.exit()
        
    z=x+y
    
    print(z)
    

    You will see that the command prompt does not close immediately