python - 找不到目录时停止python程序关闭

标签 python python-2.7 error-handling directory operating-system

我用python创建了一个DOS克隆,我有一个命令cd,它允许您更改目录。唯一的问题是,如果您拼写错误或键入了不存在的目录,则程序将关闭,并出现回溯错误。我基本上是在寻找它不是要完全关闭程序,而是print一个类似于'requested_directory' Is not a directory!的语句,并允许您键入其他目录。

香港专业教育学院尝试了几件事,主要是错误处理,但没有成功。我以为我仍然不太了解错误处理或错误使用它。

任何帮助深表感谢。

这是我用来更改目录的代码(elif,因为我还有更多命令。cmd是原始输入。)

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

这是输入错误目录时的输出
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'

最佳答案

我相信您需要handle错误。

try:
    os.chdir(desired_directory)
except OSError as e:
    print e.args[0]

关于python - 找不到目录时停止python程序关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56310544/

相关文章:

python - 在 TensorFlow 中从头开始训练 Inception

python-2.7 - PDF 格式的 scikit 学习文档

python - Django——模型不存在,但 Django 仍然加载它们

python - 常数的不定积分

python - Python2.7 找不到 psycopg2 模块

python - 在字符串中搜索字符集

python - DRF通过功能传输错误

drupal - 注意 Drupal 中的 : unserialize() [function. 反序列化]

c# - ValidateRequest 每个控件

python - 用python调用同一个类中的变量