如何使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
How do I make a python script executable?
提问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
Add a shebang line to the top of the script:
#!/usr/bin/env python
Mark the script as executable:
chmod +x myscript.py
Add the dir containing it to your
PATH
variable. (If you want it to stick, you'll have to do this in.bashrc
or.bash_profile
in your home dir.)export PATH=/path/to/script:$PATH
在脚本的顶部添加一个 shebang 行:
#!/usr/bin/env python
将脚本标记为可执行:
chmod +x myscript.py
将包含它的目录添加到您的
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
回答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.py
with 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
-e
stands 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 myscript
from any directory.
之后,您可以myscript
从任何目录运行。