不同的语句取决于代码的退出状态

时间:2013-07-07 00:27:28

标签: python exit-code

这是一个与我编写的代码无关的一般性问题。我想知道你是如何得到一个代码来打印出类似的东西, script successful如果退出状态为0script failed,则为{{1}}。我知道我以前读过这个地方,但我不记得在哪里。我只是在寻找处理退出代码的python函数。谢谢!

2 个答案:

答案 0 :(得分:1)

你可以使用try-except,就像这样。

设置要执行的脚本的一些路径。

file_path =“C:\\ python \\ your_script.py”

try:
    #Execute the script
    execfile(file_path)
    print 'script successful'

except Exception, err:
    print 'Error from your_script: ', err
    print 'script failed'

Python异常处理技术的有用文章。

http://doughellmann.com/2009/06/python-exception-handling-techniques.html

答案 1 :(得分:1)

就个人而言,我会将您的代码组织成函数,例如:

def download_image(url):
    # code to get image goes here
    # save image to disk
    # get file size or check if it exists
    if file_ok:
        return True
    else:
        return False

然后你的主要功能看起来像这样:

def main():
    url = 'http://www.reddit.com/images/logo.png'
    if download_image(url):
        print('script successful!')
    else:
        print('download failed...')

通过提供漂亮的模块化代码,单个部分负责小型工作,您将有很多机会检查失败和成功。

相关问题