如何为Python脚本定义系统范围的别名?

时间:2021-09-29 16:56:32

I am working on Mac OS X and I have a Python script which is going to be called by other scripts and programs (Apple's launchd in particular). I could call it with

我正在使用Mac OS X,我有一个Python脚本,将被其他脚本和程序调用(特别是Apple推出)。我可以打电话给它

python /Users/xyz/long/absolute/path/to/script.py arg1 arg2

Since the location of the script might change, I want to decouple other scripts and the launchd configuration files from the actual location, so that a call to the script looks like

由于脚本的位置可能会发生变化,因此我想将其他脚本和launchd配置文件与实际位置分离,以便对脚本的调用看起来像

script arg1 arg2

Defining an alias for Bash in $HOME/.bash_profile does not work, since launchd does not know about the alias.

在$ HOME / .bash_profile中为Bash定义别名不起作用,因为launchd不知道别名。

What is the best way to define a "sytem-wide alias" or something equivalent?

定义“系统范围别名”或等效的最佳方法是什么?

2 个解决方案

#1


I usually make a symbolic link and put it in /usr/bin (assuming /usr/bin is part of your PATH)

我通常会创建一个符号链接并将其放在/ usr / bin中(假设/ usr / bin是PATH的一部分)

(In a terminal. You may have to use sudo ln -s depending on the permissions.

(在终端中。您可能必须使用sudo ln -s,具体取决于权限。

ln -s /Users/xyz/long/absolute/path/to/script.py /usr/bin/script.py

If you take Rory's advice and put the #!/usr/bin/python at the beginning of the script, you'll also need to make the script executable.

如果您接受Rory的建议并将#!/ usr / bin / python放在脚本的开头,那么您还需要使脚本可执行。

chmod a+x /Users/xyz/long/absolute/path/to/script.py

#2


As well as doing a symlink, you can put "#! /path/to/python" at the start of the script and make it executabe. Then you don't have to call it with "python /Users/big/long/path/script.py"

除了执行符号链接之外,您还可以在脚本的开头放置“#!/ path / to / python”并使其成为可执行文件。然后你不必用“python /Users/big/long/path/script.py”来调用它

#1


I usually make a symbolic link and put it in /usr/bin (assuming /usr/bin is part of your PATH)

我通常会创建一个符号链接并将其放在/ usr / bin中(假设/ usr / bin是PATH的一部分)

(In a terminal. You may have to use sudo ln -s depending on the permissions.

(在终端中。您可能必须使用sudo ln -s,具体取决于权限。

ln -s /Users/xyz/long/absolute/path/to/script.py /usr/bin/script.py

If you take Rory's advice and put the #!/usr/bin/python at the beginning of the script, you'll also need to make the script executable.

如果您接受Rory的建议并将#!/ usr / bin / python放在脚本的开头,那么您还需要使脚本可执行。

chmod a+x /Users/xyz/long/absolute/path/to/script.py

#2


As well as doing a symlink, you can put "#! /path/to/python" at the start of the script and make it executabe. Then you don't have to call it with "python /Users/big/long/path/script.py"

除了执行符号链接之外,您还可以在脚本的开头放置“#!/ path / to / python”并使其成为可执行文件。然后你不必用“python /Users/big/long/path/script.py”来调用它