简体   繁体   English

如何从类似于 pip 或 howdoi 命令的任何终端实例将 python 脚本作为全局命令运行?

[英]How to run python script as global command from any terminal instance similar to pip or howdoi command?

Problem to solve要解决的问题

I have a python script called myscript.py in a directory.我在目录中有一个名为myscript.py的 python 脚本。
To run myscript.py , I have to open terminal in the same directory and do python myscript.py or python path_to_the_py_file要运行myscript.py ,我必须在同一目录中打开终端并执行python myscript.pypython path_to_the_py_file

What I want to achieve我想要达到的目标

I can open a instance of terminal anywhere, anytime and do myscript or myscript arguments -options .我可以随时随地打开终端实例并执行myscriptmyscript arguments -options By doing this, I should be able to run the script.通过这样做,我应该能够运行脚本。

I want to implement something like pip command or the howdoi package.我想实现类似pip命令或howdoi package 之类的东西。


When I enter myscript in terminal I should not get:当我在终端中输入myscript时,我不应该得到:
myscript: The term 'myscript' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.



If you have any confusion please ask in comments.如果您有任何困惑,请在评论中提问。 if the title needs improvement, feel free to edit the question.如果标题需要改进,请随时编辑问题。

There seems to be quite a few things in this question.这个问题似乎有很多东西。

First, you want to make you file executable.首先,你想让你的文件可执行。

chmod +x /path/to/your/script.py

Then, since this is an interpreted language, you'll have to specify the interpreter in a shebang at the top of the file.然后,由于这是一种解释性语言,您必须在文件顶部的 shebang 中指定解释器。

#!/usr/bin/env python

OR或者

#!/usr/bin/env python3

Finally, you'll have to put it in your PATH environment variable, which can be done in a variety of ways, simplest might be symlink in ~/bin or ~/.local/bin, depending on what you have.最后,您必须将它放在您的 PATH 环境变量中,这可以通过多种方式完成,最简单的可能是 ~/bin 或 ~/.local/bin 中的符号链接,具体取决于您所拥有的。

Also, this will make script.py available as an executable, you can rename it or rename its symlink to just script if you don't want.py.此外,这将使 script.py 可作为可执行文件使用,如果您不需要.py,您可以重命名它或将其符号链接重命名为仅脚本。

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

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