如何在Mac OS X的终端中运行python脚本而不必键入完整路径? [英] How can I run my python script from the terminal in Mac OS X without having to type the full path?

查看:96
本文介绍了如何在Mac OS X的终端中运行python脚本而不必键入完整路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mac OS 10.6 Snow Leopard上运行,并且试图将目录添加到PATH变量中,这样我可以通过在终端提示下键入以下内容来运行编写的小脚本:python alarm.py.

I'm on Mac OS 10.6 Snow Leopard and I'm trying to add a directory to my PATH variable so I can run a tiny script I wrote by just typing: python alarm.py at the terminal prompt.

我将路径放在.profile文件中,当我回显$ PATH时似乎显示了该路径,但是python仍然找不到我放在该目录中的脚本.

I put the path in my .profile file and it seems to show up when I echo $PATH, but python still can't find script the that I've put in that directory.

这是我的主目录中.profile文件的内容:

Here's the contents of my .profile file in my home directory:

~ toby$ vim .profile 
export PATH=/Users/tobylieven/Documents/my_scripts:$PATH

这是echo $ PATH的输出,看起来一切正常:

Here's the output of echo $PATH, where all seems well:

~ toby$ echo $PATH
/Users/tobylieven/Documents/my_scripts:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin

这是我要运行的脚本:

~ toby$ ls /Users/tobylieven/Documents/my_scripts 
-rwxrwxrwx@ 1 tobylieven  staff  276 17 Jan 21:17 alarm.py

这是我要用来运行脚本的命令和我收到的失败消息:

Here's the command I'm trying to use to run the script and the fail message I'm getting instead:

~ toby$ python alarm.py 
python: can't open file 'alarm.py': [Errno 2] No such file or directory

如果有人知道我可能在做什么错,那就太好了. 非常感谢.

If anyone has an idea what I might be doing wrong, that'd be great. Thanks a lot.

推荐答案

PATH仅适用于可执行文件,不适用于python脚本.将以下内容添加到Python脚本的开头:

PATH is only for executables, not for python scripts. Add the following to the beginning of your Python script:

#!/usr/bin/env python

然后运行

sudo chmod a+x /Users/tobylieven/Documents/my_scripts/alarm.py

然后,您只需键入alarm.py即可执行程序.

Then, you can type just alarm.py to execute your program.

这篇关于如何在Mac OS X的终端中运行python脚本而不必键入完整路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆