如何制作可在 shell 中使用的可执行文件 - Python

1 投票
7 回答
5672 浏览
提问于 2025-04-17 06:00

我有一个Python脚本,想知道怎么才能让它变得可执行;换句话说,我该怎么用像bash这样的命令行来运行它。

我知道第一步是在第一行加上 #! /usr/bin/env python,但是接下来我需要把函数按特定顺序排列吗(比如说,主函数放在最上面还是最下面)。还有,我需要把我的Python文件后缀保持为.py吗(我能不能直接调用函数 Dosomething)?

简单来说,你能给我提供一个简单的指南吗?就是一些让Python文件变得可执行时需要注意的重要点。

7 个回答

1

删除第一个空格。也就是说,

#!/usr/bin/env python

这应该是你文件的第一行。然后,确保你把文件的权限设置为可执行,使用:

chmod u+x your_script.py

Python脚本是按顺序执行的。如果你的文件里有很多函数,通常在文件的最后会有这样的内容:

if __name__ == '__main__':
    main()

这里的main()是你脚本开始执行的地方。我们这样做的原因,而不是直接调用main(),是因为这样可以让你的脚本像一个模块一样工作,而不需要任何修改;如果你只是简单地写一行代码来调用main(),那么你的模块在执行时就会直接运行脚本的主函数。这个if语句只是用来检查你的脚本是否在__main__命名空间中运行,也就是说,它是作为一个脚本在运行。

1

你需要在文件的第一行添加一个叫做 sha bang 的东西,举个例子:

#!/usr/bin/python

或者

#!/usr/bin/env python

这样做,然后你还需要让这个文件可以执行,方法是运行:

chmod +x Dosomething

除此之外你不需要做其他的事情,文件名可以随便起,比如 Dosomething。你的 PATH 可能没有包含这个文件所在的目录,所以你应该这样运行它(假设你当前的工作目录就是这个文件所在的地方):

./Dosomething
4

这是我制作可执行脚本的方法。这个脚本不考虑任何复杂的东西,比如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())

你先创建想要使用的函数,然后再使用它们。希望这对你有帮助。

撰写回答