0

Im creating a DOS clone with python and I have a command cd which allows you to change directory. The only problem is that if you misspell or type a non-existent directory, the program closes with a traceback error. Im basically looking for it not to completely close the program but instead print a statement like 'requested_directory' Is not a directory! and allow you to type in a different directory.

Ive tried a couple things, mainly error handling, but to no prevail. Im assuming that im still not quite understanding error handling or using it incorrectly.

Any help is much appreciated.

This is the code im using to change directories (elif because i have many more commands. cmd is a raw input.)

elif 'cd' in cmd:
        desired_directory = cmd.split(' ')[1]
        if desired_directory == "..":
            os.chdir('..')
        else:
            os.chdir(desired_directory)

This is the output when an incorrect directory is typed in

Traceback (most recent call last):
  File "/Users/jrosmac/PycharmProjects/untitled/JDOS/SYS64/jdosos.py", line 47, in <module>
    os.chdir(desired_directory)
OSError: [Errno 2] No such file or directory: 'raw_input goes here'
JROS
  • 71
  • 1
  • 2
  • 11
  • Possible duplicate of [How to find if directory exists in Python](https://stackoverflow.com/questions/8933237/how-to-find-if-directory-exists-in-python) – Eric May 26 '19 at 04:10
  • @Eric from what i have found on stack overflow, nothing explains what to do if you misspell the directory when changing – JROS May 26 '19 at 04:18

2 Answers2

0

I believe you need to handle the error.

try:
    os.chdir(desired_directory)
except OSError as e:
    print e.args[0]
Buckeye14Guy
  • 831
  • 6
  • 12
  • I should be using 3.x but im lazy and 2.7 was what i learned in the few years of school i did for programming. I might start changing the whole program over soon. – JROS May 26 '19 at 04:14
0

Use exception handing:

try:
    os.chdir(target)
except OSError as e:
    # handle the failure of the chdir call
Dan D.
  • 73,243
  • 15
  • 104
  • 123