5

我在我的主目录中安装了两个 python 2.7.3

   one is for Linux:           /home/luban/Linux/Python/2.7.3
   another is for Solaris:   /home/luban/SunOS/Python/2.7.3

然后我在 /home/luban/bin 中创建一个名为“python”的包装器,以便在我在不同系统上工作时调用不同的 python。

[luban@lunbanworks 1] ~ > cat /home/luban/bin/python

#!/bin/sh

CMD=`basename $0`

OS=`uname -s`


CMD_PATH="/home/luban/$OS/Python/2.7.3/bin"


if [ -x "${CMD_PATH}/${CMD}" ];then

    export PATH="${CMD_PATH}:${PATH}"

    exec ${CMD_PATH}/${CMD} ${1+"$@"}

else

    echo "${CMD} is not available for ${OS}" 1>&2

exit 1

fi

 

[luban@lunbanworks 2] `ls -l /home/luban/bin/python`

-rwxrwxr-x  1 luban lunban  221 Apr  5 19:11 python*

我使用下面的脚本来测试包装器/home/luban/bin/python

[luban@lunbanworks 3] ~ > cat myscript.py

    #!/home/luban/bin/python

    myname="lunban"

    print "myname is %s" % myname

[luban@lunbanworks 4] chmod +x myscript.py

我想用./ run myscript.py

[luban@lunbanworks 5] ~ >./myscript.py

    myname=luban: Command not found.
    lpr: Unable to access "myname" - No such file or directory

使用/home/luban/bin/python myscript.py可以工作:

[luban@lunbanworks 5] ~ > `/home/luban/bin/python myscript.py`

    myname is luban

在我将 shebang 行更改为 后#!/home/luban/Linux/Python/2.7.3/bin/python,使用./可以执行脚本。

[luban@lunbanworks 6] ~ >cat myscript.py

    #!/home/luban/Linux/Python/2.7.3/bin/python
    myname="lunban"

    print "myname is %s" % myname

[luban@lunbanworks 7] ~ >./myscript.py

    myname is luban

为什么我#!/home/luban/Linux/Python/2.7.3/bin/python在myscript.py开头使用的时候,./myscript.py可以工作,

#!/home/luban/bin/python但是如果我在我的python脚本中使用包装器,./ 用来运行脚本,它不能工作吗?

#!/home/luban/bin/python我只在Linux下安装python时使用了很多脚本#!/home/luban/,它们可以运行./,我不想更改它们,

./那么,如果我想将包装器#!/home/luban/bin/python保留为 shebang 行,如何让运行 python 脚本?


代特:

./myscript.py不能使用下面的包装#!/home/luban/bin/pythonCentOS 5.4, Bash 3.2.25

今天,我有一个测试CentOS 6.4, Bash 4.1.2

我添加了

echo '$0 =' $0
echo '${COMMAND_PATH}/${COMMAND} ${1+"$@"} =' ${COMMAND_PATH}/${COMMAND} ${1+"$@"}

进入包装器#!/home/luban/bin/python进行跟踪。

./myscript.py与包装器一起使用#!/home/luban/bin/python

[luban@lunbanworks 20] ./myscript.py 
      $0 =  /home/luban/bin/python
      ${COMMAND_PATH}/${COMMAND} ${1+"$@"} =  /home/luban/Linux/Python/2.7.3/bin/python ./myscript.py
      myname is luban

所以我想当./我使用包装器时它可能是一个 Bash 3.2.25 错误#!/home/luban/bin/python

4

1 回答 1

6

你有没有考虑过:

#!/usr/bin/env python

这通常对我有用,只要在搜索路径中找到 python。

在您的情况下,您希望您的个人资料在个人资料设置中具有以下内容:

# Adjust for your preferred shell
export PATH=/home/luban/Linux/Python/2.7.3:/home/luban/SunOS/Python/2.7.3:$PATH

然后,当你的 python 脚本使用 "#!/usr/bin/env python" shebang 运行时,它会为你找到合适的 python。

于 2013-04-05T16:12:24.600 回答