Search code examples
pythonexceptioncmdpathsystem

How to make Python "not recognized as an internal or external command" an exception


I have this block of code:

path = askdirectory(title='Choose folder')
os.chdir(path)   

try:        
    os.system('currency.py')
except:
    #Error message       
    ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)

What I want to accomplish is that when the user chooses the wrong folder (the one in which the 'currency.py' file is not in), it throws this little Error message box. Instead, when I purposely choose the wrong folder, it says:

"currency.py "is not recognized as an internal or external command

But it doesn't show me the error window. Is there a way to make python recognize this error as an exception? Thank you!


Solution

  • It appears you are using Python to run a Python file using the operating system shell. You can run the file by importing it and (if needed) instantiating it.

    try:
      # import the python file
      import currency.py
      # instantiate the class/function if required
    except ImportError:
        ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)
    

    Nevertheless you can avoid using the try/catch scenario by seeing if the file exists, if not, display your error message:

    if os.path.isfile(file_path):
        os.system('currency.py')
    else:
        ctypes.windll.user32.MessageBoxW(0, u"Error", u"Error", 0)