Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用bash脚本设置PYTHONPATH并运行nosetests_Python_Bash_Nose - Fatal编程技术网

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

使用bash脚本设置PYTHONPATH并运行nosetests,python,bash,nose,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 PYT

下面的脚本设置了一个干净的
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
此脚本应与nosetest命令一起运行,以允许测试在需要时导入所有必要的模块,而不会出现任何问题:

/path/to/script/PythonPath.sh&&nosetests


但是,当我运行上述命令时,我在其中一个模块上得到一个
ImportError
,表明它不存在。我在脚本的末尾添加了一个
echo
语句来帮助调试,而
PYTHONPATH
正是它应该的样子。我还尝试手动设置了
PYTHONPATH
,但似乎无法重现相同的问题。

您无法以这种方式在bash中设置环境变量。脚本最终会在自己的进程中运行,在那里设置环境,而不会返回到您的进程中。在这种情况下,您可以
source
脚本以使其影响当前环境:

source ./path/to/script/PythonPath.sh && nosetests <tons of other arguments>
当我源文件时,我得到:

/tmp/scratch$ . PythonPath.sh
/tmp/scratch$ echo $PYTHONPATH
/tmp/scratch/../../../module1:/tmp/scratch/../../../module2:/tmp/scratch/../../../module3:/tmp/scratch/../../../module4

那么,当您手动设置它时,它可以工作?@vicg是的,这是正确的。子shell不会影响父shell,只需在脚本内部运行您的测试。当我在脚本上运行
源代码
时,
PYTHONPATH
上的echo语句复制了脚本中引用的所有目录和Python文件的长字符串,而不是通常的语法(即
/dir/module1:/dir/module2
)。此外,问题仍然存在。目录或模块名中是否有空格?如果您不这样做,引用将非常重要,它们可以是驼峰式大小写,也可以用下划线分隔。您能否提供一个示例,说明文件来源后
PYTHONPATH
的值?我无法重现你所描述的。当然
Directory1/thisIsAModule.py*另一个目录/module2.py*配置/
#!/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
/tmp/scratch$ . PythonPath.sh
/tmp/scratch$ echo $PYTHONPATH
/tmp/scratch/../../../module1:/tmp/scratch/../../../module2:/tmp/scratch/../../../module3:/tmp/scratch/../../../module4