简体   繁体   English

停止操作而不停止python中的模块

[英]Stop an operation without stopping the module in python

Well, I have made a module that allows you to copy a file to a directory easier. 好吧,我制作了一个模块,使您可以轻松地将文件复制到目录。 Now, I also have some "try's" and "except's" in there to make sure it doesn't fail in the big messy way and doesn't close the terminal, but I also want it to display different error messages when a wrong string or variable is put in, and end the module, but not the...if I may say, Terminal running it, so I did this: 现在,我在其中也有一些“ try”和“ except”,以确保它不会以很大的混乱并不会关闭终端,但是我也希望当错误的字符串显示不同的错误消息或变量被放入,并结束模块,但不结束...如果我可以说,终端运行它,那么我这样做了:

def copy():
    import shutil
    import os
    try:
        cpy = input("CMD>>> Name of file(with extension): ")
        open(cpy, "r")
    except:
        print("ERROR>>> 02x00 No such file")
    try:
        dri = input("CMD>>> Name of Directory: ")
        os.chdir(dri)
        os.chdir("..")
    except:
        print("ERROR>>> 03x00 No such directory")
    try:
        shutil.copy(cpy, dri)
    except:
        print("ERROR>>> 04x00 Command Failure")

Problem is that it doesn't end the module if there is no file or directory, only at the finish. 问题是,如果没有文件或目录,它只会在最后才结束模块。

You may be thinking that when an exception is raised, Python just stops what it's doing, but that's not quite true. 您可能会想,当引发异常时,Python会停止其正在执行的操作,但事实并非如此。 The except: block actually catches the exception raised, and is supposed to handle it. except:块实际上捕获了引发的异常,并且应该处理它。 After an except: block finishes, Python will continue on executing the rest of the code in the file. except:块完成之后,Python将继续执行文件中的其余代码。

In your case, I'd put a return after each print(...) . 就您而言,我会在每次print(...)后都放一个return print(...) That way, after Python prints out an error message, it will also return from the copy() function rather than continuing to ask for more input. 这样,Python打印出错误消息后,它还将从copy()函数返回,而不是继续请求更多输入。

If you did want to make the module exit on error... 如果您确实想使模块在错误时退出...

Here's how you'd do it. 这是您的操作方式。

def copy():
    import shutil
    import os
    import sys
    try:
        cpy = input("CMD>>> Name of file(with extension): ")
        open(cpy, "r")
    except:
        sys.exit("ERROR>>> 02x00 No such file")
    try:
        dri = input("CMD>>> Name of Directory: ")
        os.chdir(dri)
        os.chdir("..")
    except:
        sys.exit("ERROR>>> 03x00 No such directory")
    try:
        shutil.copy(cpy, dri)
    except:
        sys.exit("ERROR>>> 04x00 Command Failure")

sys.exit(0) (for success) and sys.exit(1) (for failure) are usually used but, since you want to output the error, the above example will output the error string to stderr. 通常使用sys.exit(0)(表示成功)和sys.exit(1)(表示失败),但是由于要输出错误,因此上面的示例会将错误字符串输出到stderr。

Here's a link for more info on sys.exit() . 这是有关sys.exit()的更多信息的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM