简体   繁体   English

如何从任何目录的终端执行python命令行实用程序

[英]How to execute a python command line utility from the terminal in any directory

I have just written a python script to do some batch file operations. 我刚刚编写了python脚本来执行一些批处理文件操作。 I was wondering how i could keep it in some common path like rest of the command line utilities like cd, ls, grep etc. 我想知道如何将其保留在其他命令行实用程序(如cd,ls,grep等)中的某些通用路径中。

What i expect is something like this to be done from any directory - 我所期望的是可以从任何目录执行此操作-

$ script.py arg1 arg2 $ script.py arg1 arg2

Just put the script directory into the PATH environment variable, or alternatively put the script in a location that is already in the PATH. 只需将脚本目录放入PATH环境变量中,或将脚本放在PATH中已经存在的位置。 On Unix systems, you usually use /home/<nick>/bin for your own scripts and add that to the PATH. 在Unix系统上,通常将/home/<nick>/bin用于自己的脚本,并将其添加到PATH。

Add the directory it is stored in to your PATH variable? 将存储目录添加到您的PATH变量中? From your prompt, I'm guessing you're using an sh-like shell and from your tags, I'm further assuming OS X. Go into your .bashrc and make the necessary changes. 根据您的提示,我猜您正在使用类似sh的shell,并且您的标签中还假设使用OSX。进入您的.bashrc并进行必要的更改。

An alternative approach is to create a python package with entry points and install the program, rather than changing $PATH (using setuptools in setup.py ). 一种替代方法是使用入口点创建python软件包并安装程序,而不是更改$PATH (使用setup.py setuptools )。 This has some advantages: 这具有一些优点:

  • Works outside of shells 在壳外工作
  • Reduces the amount of system-wide configuration, or at least puts it all in side the package. 减少系统范围内的配置量,或至少将其全部放在包装中。

See Explain Python entry points? 请参阅解释Python入口点? and python: simple example for a python egg with a one-file source file? python:带有一个文件源文件的python egg的简单示例? for details. 有关详细信息。

This has the advantage of keeping all your settings in one place. 这样的好处是可以将所有设置都放在一个位置。

You can use the --develop option so that you can still edit your code in place and the --user option to avoid messing python for other users. 您可以使用--develop选项,以便仍可以就地编辑代码,使用--user选项可以避免其他用户混淆python。

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

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