如何使python脚本可执行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27494758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:52:35  来源:igfitidea点击:

How do I make a python script executable?

pythonmacoscommand-line

提问by ctrlz

How can I run a python script with my own command line name like 'myscript' without having to do 'python myscript.py' in the terminal?

如何使用我自己的命令行名称(如“myscript”)运行 python 脚本,而不必在终端中执行“python myscript.py”?

采纳答案by tzaman

  1. Add a shebang line to the top of the script:

    #!/usr/bin/env python

  2. Mark the script as executable:

    chmod +x myscript.py

  3. Add the dir containing it to your PATHvariable. (If you want it to stick, you'll have to do this in .bashrcor .bash_profilein your home dir.)

    export PATH=/path/to/script:$PATH

  1. 在脚本的顶部添加一个 shebang 行:

    #!/usr/bin/env python

  2. 将脚本标记为可执行:

    chmod +x myscript.py

  3. 将包含它的目录添加到您的PATH变量中。(如果你想让它坚持下去,你必须在你的家庭目录中.bashrc.bash_profile在你的家庭目录中这样做。)

    export PATH=/path/to/script:$PATH

回答by dAn

I usually do in the script:

我通常在脚本中这样做:

#!/usr/bin/python
... code ...

And in terminal:

在终端:

$: chmod 755 yourfile.py
$: ./yourfile.py

permission table

权限表

回答by merrydeath

The best way, which is cross-platform, is to create setup.py, define an entry point in it and install with pip.

最好的跨平台方式是在其中创建setup.py、定义入口点并使用pip.

Say you have the following contents of myscript.py:

假设您有以下内容myscript.py

def run():
    print('Hello world')

Then you add setup.pywith the following:

然后添加setup.py以下内容:

from setuptools import setup
setup(
    name='myscript',
    version='0.0.1',
    entry_points={
        'console_scripts': [
            'myscript=myscript:run'
        ]
    }
)

Entry point format is terminal_command_name=python_script_name:main_method_name

入口点格式为 terminal_command_name=python_script_name:main_method_name

Finally install with the following command.

最后使用以下命令安装。

pip install -e /path/to/script/folder

-estands for editable, meaning you'll be able to work on the script and invoke the latest version without need to reinstall

-e代表可编辑,这意味着您将能够处理脚本并调用最新版本而无需重新安装

After that you can run myscriptfrom any directory.

之后,您可以myscript从任何目录运行。