简体   繁体   English

如何使python脚本可全局执行? OSX

[英]How do you make a python script globally executable? OSX

I've read many of the other answers on here to try and get this working, but for some reason it won't. 我已经阅读了许多其他答案,以尝试使其正常运行,但是由于某些原因,它却无法解决。 I've already changed permissions and made the .py executable with chmod +x <myscript.py> , and I've copied the file into my /usr/local/bin which is already in my PATH by default on OSX, however, I still can't execute the script unless I'm in the directory where it's located. 我已经更改了权限,并使用chmod +x <myscript.py>使.py可执行文件,并将文件复制到OSX上默认情况下已在我的PATH中的/ usr / local / bin中,除非我位于脚本所在的目录中,否则我仍然无法执行该脚本。

In addition, I'm a little confused on how the header works. 另外,我对标头的工作方式有些困惑。 I currently have #!/usr/bin/python because when I changed it to #!/usr/local/bin to match the directory, when I ran the script my terminal said I had a "bad interpreter." 我目前拥有#!/usr/bin/python因为当我将其更改为#!/usr/local/bin以匹配目录时,当我运行脚本时,我的终端说我有一个“错误的解释器”。

I know this topic has been on here a lot, but the other fixes haven't worked. 我知道这个话题已经讨论了很多,但是其他修复没有用。 Thanks in advance. 提前致谢。

If you run your script like this: 如果您像这样运行脚本:

./Untitled.py

Bash will try to find the script in the current directory -- because you've invoked the script with a file path (a relative one in this case). Bash会尝试在当前目录中查找脚本-因为您已经使用文件路径(在这种情况下为相对路径)调用了脚本。

However, if you run the script like this: 但是,如果您像这样运行脚本:

Untitled.py

Bash will search your PATH for an executable with that name. Bash将在您的PATH搜索具有该名称的可执行文件。 Assuming that you've made the script executable (with chmod ) and that script resides in a directory in your PATH , the script should run. 假设您已将该脚本设置为可执行文件(使用chmod ),并且该脚本位于PATH的目录中,则该脚本应该运行。

Regarding the she-bang line, rather than hard-coding to a specific Python ( /usr/bin/python ), a more common approach would be this: 关于she-bang行,而不是硬编码到特定的Python( /usr/bin/python ),更常见的方法是:

#! /usr/bin/env python

Your script will be executed by whichever Python is active at the moment (for example, you might be using virtualenv or pyenv to switch between Pythons, depending on your current project). 脚本将由当前处于活动状态的任何Python执行(例如,您可能会使用virtualenvpyenv在Python之间进行切换,具体取决于当前项目)。

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

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