从xcode宏运行python脚本时如何使用标准python路径

2024-05-17 03:20:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用Xcode的用户脚本菜单运行Python脚本。

我遇到的问题是,当从XCode运行脚本时,我通常的os.sys.path(取自~/.profile)似乎不像在终端(或使用IPython)运行脚本时那样被导入。我得到的只是默认路径,这意味着我不能像

#!/usr/bin/python
import myScript

myScript.foo()

其中myScript是我添加到路径中的文件夹中的模块。

我可以很容易地手动将一个特定的路径附加到os.sys.path,但是我必须在每个脚本中为每个要使用模块的路径执行此操作

有没有办法把它设置成和我在其他地方一样的路径?

编辑:在进一步研究之后,似乎从Xcode执行的脚本使用的路径与普通脚本完全不同。在Xcode中运行脚本得到的路径是:

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

我确信我的常规路径中没有/Developer/usr/bin。有人知道这条路是从哪里来的吗?


Tags: 模块path用户路径脚本developerbinos
3条回答

一个快速但有技巧的方法是为python创建一个包装脚本。

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

然后用

#!/Users/you/bin/mypython

只需将路径添加到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
>>> 

在mac上,.profile中的环境变量对终端外部的应用程序不可见。

如果希望xcode应用程序可以使用环境变量(如PATH、PYTHONPATH等),则应将其添加到在~/.MacOSX/environment.plist创建的新plist文件中。

有关更多详细信息,请参见apple开发者网站上的EnvironmentVars文档。

相关问题 更多 >