简体   繁体   English

在Python中使用函数的正确方法?

[英]Correct way to use function in Python?

Question is - where and how to use try/except and if/else operators? 问题是-在哪里以及如何使用try/exceptif/else运算符?

For example - I have function: 例如-我有功能:

# copy php.cgi script
def cpcgi(src, dst):
        try:
                shutil.copy(src, dst)
                if os.path.isfile(dst + '/php.cgi'):
                        return True
        except:
                print 'Something going wrong!'

Function stored in separate file. 功能存储在单独的文件中。 Next, from script it calls like: 接下来,从脚本中调用如下:

import createvhostFuncts as fun

print 'Copying php.cgi file...'
if fun.cpcgi(vdir + 'php-cgi/php.cgi', (vdir + 'php-cgi/' + username + '/' + domain)):
        print 'Done.\n'
else:
        exit('Error! Exit now.\n')

But - there is lot of functions in createvhostFuncts.py . 但是createvhostFuncts.py有很多功能。 Thus, I have big list of if/else calls in script and it's looks very... Odd? 因此,我在脚本中有大量的if/else调用列表,看起来非常...奇怪吗? Useless? 无用?

So - what correct way to call functions and where better use try/except - inside function, or in script? 那么-调用函数的正确方法是什么?在函数内部还是在脚本中更好地使用try/except

UPD : UPD

For example - in BASH I can use somethig like next: 例如-在BASH中,我可以使用somethig,如下所示:

#!/usr/bin/env bash

func(){
        echo "Ya!"
}

if func; then
        echo $?
        echo "Printed"
else
        echo $?
        echo "Can't echo!"
fi

And run it with next result: 并运行下一个结果:

$ ./m
Ya!
0
Printed

Or with error: 或有错误:

#!/usr/bin/env bash

func(){
        eCCCcho "Ya!"
}

if func; then
        echo $?
        echo "Printed"
else
        echo $?
        echo "Can't echo!"
fi


$ ./m
./m: line 4: eCCCcho: command not found
127
Can't echo!

In Python they usually don't use function return value to denote the success status (like they do in C or Go), rather the function should raise an exception if something goes wrong. 在Python中,它们通常不使用函数返回值来表示成功状态(就像在C或Go中那样),而是如果出现问题,则函数应引发异常。

def cpcgi(src, dst):
    shutil.copy(src, dst)
    if not os.path.isfile(dst + '/php.cgi')
        raise WhateverError("Failed to copy {0}".format(src))

You can intercept the exception from the calling side (within your script) or let it fall through, which in your case will cause the script termination with a stack trace. 您可以从调用方(在脚本内)拦截该异常,也可以使其通过,在您的情况下,这将导致该脚本以堆栈跟踪终止。 Then you don't need to wrap every single call with try..except . 然后,您不需要使用try..except来包装每个调用。

(A side note) If you also don't want the stack trace to be displayed, you can use sys.excepthook , like this: (旁注)如果您也不想显示堆栈跟踪,则可以使用sys.excepthook ,如下所示:

def report(type, value, traceback):
    print "Error during execution {0}".format(value)

sys.excepthook = report

It may look odd in a large file to have many try/catch blocks. 在大型文件中有许多try / catch块可能看起来很奇怪。 It is agreed that this is acceptable and functions should throw an error instead of returning values to denote success or failure. 公认这是可以接受的,函数应该抛出错误而不是返回表示成功或失败的值。

If no error is thrown you continue like normal 如果没有错误,您将像往常一样继续

Here Is how I would be writing your code. 这就是我将如何编写您的代码。 In both cases it reaches the end of the script: 在两种情况下,它都到达脚本的末尾:

def cpcgi(src, dst):
    shutil.copy(src, dst)
    if not os.path.isfile(dst + '/php.cgi'):
        raise FailedCopyError("Could not copy {} to {}".format(src,dst))

import createvhostFuncts as fun

print 'Copying php.cgi file...'
try:
    fun.cpcgi(vdir + 'php-cgi/php.cgi', (vdir + 'php-cgi/' + username + '/' + domain)):

    # We have not encountered any errors so continue within the same code block

    a = 10
    b = 20
    c = 30

    # We encountered no errors

except FailedCopyError as e:
    # We have encountered an errof so break out of the try block.
    # We do not re-enter the try block, continue below.
    print(e) # This will print more information about the error


# We can continue here

print('The Try/Catch took care of everything')
print('Continue as if nothing happened')
d = 40
e = 50

It's definitely work reading the official python documentation 阅读官方python文档绝对是工作

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

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