这就是我制作可执行脚本的方式。它不考虑eggs 或类似的东西。这只是一个我希望能够执行的简单脚本。我假设您使用的是 linux。
#! /usr/bin/env python
import sys
def main():
#
# Do something ... Whatever processing you need to do, make it happen here.
# Don't shove everything into main, break it up into testable functions!
#
# Whatever this function returns, is what the exit code of the interpreter,
# i.e. your script, will be. Because main is called by sys.exit(), it will
# behave differently depending on what you return.
#
# So, if you return None, 0 is returned. If you return integer, that
# return code is used. Anything else is printed to the console and 1 (error)
# is returned.
#
if an_error_occurred:
return 'I\'m returning a string, it will be printed and 1 returned'
# Otherwise 0, success is returned.
return 0
# This is true if the script is run by the interpreter, not imported by another
# module.
if __name__ == '__main__':
# main should return 0 for success, something else (usually 1) for error.
sys.exit(main())
现在,如果你的权限设置正确,你就可以执行这个脚本了。
需要意识到的是,当您的脚本被处理时,每一行都在解释器中执行。这是真的,不管处理器如何“得到它”。那就是将脚本作为模块导入并作为脚本执行,它们的工作原理基本相同,因为它们都执行模块的每一行。
一旦您意识到您的脚本只是在运行时执行,您就会意识到函数的顺序并不重要。函数声明是函数声明。当您调用函数时才是最重要的。
所以,一般来说,你的脚本布局是这样的
def func1():
pass
def func2():
pass
def main():
return 0
if __name__ == '__main__':
sys.exit(main())
您首先创建要使用的功能,然后再使用它们。希望对您有所帮助。