简体   繁体   English

如何为 python 脚本创建别名,类似于黑色?

[英]How to make alias for python script, similar to black?

I am wondering how to make an entry point to call a python script, similar to black .我想知道如何创建一个入口点来调用 python 脚本,类似于black
eg:例如:
black my_script.py

Say I have a python file called fix_newline.py .假设我有一个名为fix_newline.py的 python 文件。

Instead of calling python fix_newline.py path/to/my_script.py in the directory of fix_newline.py , I'd like to assign the name fix_newline to python path/to/fix_newline.py .我不想在fix_newline.py的目录中调用python fix_newline.py path/to/my_script.py ,而是将名称fix_newline分配给python path/to/fix_newline.py

The ultimate goal is to call fix_newline from anywhere in my directory tree, as long as I am in the same environment (eg ~/.bash_profile ).最终目标是从我的目录树中的任何地方调用fix_newline ,只要我在相同的环境中(例如~/.bash_profile )。

I believe I found a way to make an alias via packaging to PyPI as suggested by @Chris_Rands and link provided by @CharlesDuffy:我相信我找到了一种方法,按照@Chris_Rands 的建议和@CharlesDuffy 提供的链接,通过打包到 PyPI 来制作别名:

setup(
    ...,
    entry_points={"console_scripts": ["realpython=reader.__main__:main"]},
)

The entry_point kwarg in setup function in setup.py should be the trick. setup.pysetup function 中的entry_point kwarg 应该是诀窍。

  1. Add path/to to your PATH variable .bash_profile .path/to添加到您的PATH变量.bash_profile (If you have a lot of scripts, consider installing them in a fixed location like ~/bin/ , so that you don't add a lot of unnecessary directories to your PATH . (如果您有很多脚本,请考虑将它们安装在固定位置,例如~/bin/ ,这样您就不会在PATH中添加很多不必要的目录。

  2. Make sure you script is executable and has an appropriate shebang.确保您的脚本是可执行的并且具有适当的 shebang。

  3. Drop the .py from the script name.从脚本名称中删除.py

You could also use a Bash alias for this: https://tldp.org/LDP/abs/html/aliases.html您也可以为此使用 Bash 别名: https://tldp.org/LDP/abs/html/aliases.html

Make sure you use absolute path to python and fix_newline.py on your machine:确保在您的机器上使用 python 和fix_newline.py的绝对路径:

alias fix_newline='/path/to/your/python /path/to/fix_newline.py'

Then you can use with:然后你可以使用:

fix_newline file.txt

If you want this alias to be permanent make sure to put this configuration in you ~/.bashrc file: https://tldp.org/LDP/abs/html/sample-bashrc.html如果您希望此别名永久存在,请确保将此配置放入您的~/.bashrc文件中: https://tldp.org/LDP/abs/html/sample-bashrc.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM