用点斜杠运行python脚本./

时间:2013-04-05 15:47:45

标签: python

我在我的主目录中安装了两个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

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

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

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

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


DEIT:

./myscript.py无法使用#!/home/luban/bin/python下的包装CentOS 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

所以我认为当我使用包装器./时,它可能是#!/home/luban/bin/python的Bash 3.2.25错误?

1 个答案:

答案 0 :(得分:5)

您是否考虑过:

#!/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。