使用bash脚本设置PYTHONPATH并运行nosetests

ILo*_*oon 2 python bash nose

我有以下脚本设置干净PYTHONPATH:

#!/bin/bash

# Get the directory the script is in
DIR=$(cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)

$ Walk up to root of branch dir
DIR=$DIR/../../..

PYTHONPATH=$DIR/module1
PYTHONPATH=$PYTHONPATH:$DIR/module2
PYTHONPATH=$PYTHONPATH:$DIR/module3
PYTHONPATH=$PYTHONPATH:$DIR/module4
export PYTHONPATH
Run Code Online (Sandbox Code Playgroud)

该脚本应该与nosetest命令一起运行,以允许测试在需要时导入所有必需的模块而不会出现任何问题:

./path/to/script/PythonPath.sh && nosetests <tons of other arguments>

但是,当我运行上面的命令时,我得到一个ImportError模块,声明它不存在.我echo在脚本的末尾添加了一个语句来帮助调试,PYTHONPATH它完全是应该的.我也试过PYTHONPATH手动设置,似乎无法重现同样的问题.

Eri*_*ouf 6

你不能用bash这样设置环境变量.该脚本最终在自己的进程中运行,在那里设置环境而不是回到你的环境中.在这种情况下,您可以source.脚本让它影响您当前的环境:

source ./path/to/script/PythonPath.sh && nosetests <tons of other arguments>
Run Code Online (Sandbox Code Playgroud)

要么

. ./path/to/script/PythonPath.sh && nosetests <tons of other arguments>
Run Code Online (Sandbox Code Playgroud)

此外,您有额外的报价,没有帮助,至少1行缺少评论字符.这是一个包含这些修复的脚本:

#!/bin/bash

# Get the directory the script is in
DIR=$(cd $( dirname ${BASH_SOURCE[0]} ) && pwd)

# Walk up to root of branch dir
DIR=$DIR/../../..

PYTHONPATH=$DIR/module1
PYTHONPATH=$PYTHONPATH:$DIR/module2
PYTHONPATH=$PYTHONPATH:$DIR/module3
PYTHONPATH=$PYTHONPATH:$DIR/module4
export PYTHONPATH
Run Code Online (Sandbox Code Playgroud)

当我获取该文件时,我得到:

/tmp/scratch$ . PythonPath.sh
/tmp/scratch$ echo $PYTHONPATH
/tmp/scratch/../../../module1:/tmp/scratch/../../../module2:/tmp/scratch/../../../module3:/tmp/scratch/../../../module4
Run Code Online (Sandbox Code Playgroud)