如何在Xcode宏中运行Python脚本时使用标准Python路径

2 投票
6 回答
10238 浏览
提问于 2025-04-11 20:47

我想通过Xcode的用户脚本菜单来运行Python脚本。

我遇到的问题是,通常我在~/.profile中设置的os.sys.path似乎在Xcode中运行脚本时没有被导入,而在终端(或使用IPython)中运行时是可以的。这样一来,我只能使用默认的路径,这就意味着我不能像这样做:

#!/usr/bin/python
import myScript

myScript.foo()

这里的myScript是我已经添加到路径中的一个模块。

我可以手动把特定的路径添加到os.sys.path中,但我必须在每一个脚本中为每一个想要使用的模块路径都这样做,实在是太麻烦了。

有没有办法设置一下,让它使用我在其他地方用的同样的路径呢?

补充:经过进一步调查,我发现从Xcode执行的脚本使用的PATH和正常的完全不同。在Xcode中运行脚本时,我得到的路径是:

PATH=/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin

而我确定我的正常路径中没有/Developer/usr/bin。有没有人知道这个路径是从哪里来的?

6 个回答

1

只需要把路径添加到 sys.path 里面就可以了。

>>> import sys
>>> sys.path
['', ... lots of stuff deleted....]
>>> for i in sys.path:
...     print i
... 

/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload
/Library/Python/2.5/site-packages
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjC
>>> sys.path.append("/Users/crm/lib")
>>> for i in sys.path:
...     print i
... 

/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python25.zip
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-darwin
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/plat-mac/lib-scriptpackages
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk
/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-dynload
/Library/Python/2.5/site-packages
/System/Library/Frameworks/Python.framework/Versions/2.5/Extras/lib/python/PyObjC
/Users/crm/lib
>>> 
1

一个快速但有点不太正规的办法是为 Python 写一个包装脚本。

cat > $HOME/bin/mypython << EOF
#!/usr/bin/python
import os
os.path = ['/list/of/paths/you/want']
EOF

然后用这个脚本来启动你所有的 XCode 脚本。

#!/Users/you/bin/mypython
4

在Mac电脑上,你在.profile文件里设置的环境变量,其他应用程序是看不到的,只有在终端里才可以用。

如果你想让某个环境变量(比如PATH、PYTHONPATH等)在Xcode应用程序中也能用,你需要把它添加到一个新的plist文件里,这个文件你可以放在~/.MacOSX/environment.plist。

想了解更多细节,可以查看苹果开发者网站上的EnvironmentVars文档。

撰写回答