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

时间:2019-05-26 04:03:13

标签: python python-2.7 directory

我正在用python创建DOS克隆,我有一个命令cd,该命令可让您更改目录。唯一的问题是,如果您拼写错误或键入了不存在的目录,则程序将关闭,并出现回溯错误。我基本上是在寻找它不是要完全关闭程序,而是要print这样的语句,例如' ' 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'

2 个答案:

答案 0 :(得分:0)

我相信您需要handle错误。

emails <- c("blah@my.blah.com;etc@etc.edu;me@me.gov",
            "yay@something.gov;yes@my.blah.com;maybe@maybe.net;stuff@my.blah.com",
            "someemail@nothing.gov")

sapply(emails, function(x) {
    m <- gregexpr("[^;]+@my\\.blah\\.com", x)
    regmatches(x, m)
})
names(matches) <- seq(1:length(matches))
matches

$`1`
[1] "blah@my.blah.com"

$`2`
[1] "yes@my.blah.com"   "stuff@my.blah.com"

$`3`
character(0)

答案 1 :(得分:0)

使用异常处理:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.done_button: Button! defined in kotlinx.android.synthetic.main.activity_main 
Unresolved reference: it    
Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public val Activity.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val Dialog.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main
public val android.support.v4.app.Fragment.nickname_edit: EditText! defined in kotlinx.android.synthetic.main.activity_main

> Task :app:buildInfoGeneratorDebug