gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:14:59 25 4
gpt4 key购买 nike

我有以下脚本可以设置干净的 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 <tons of other arguments>

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

最佳答案

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

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

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

此外,您还有无用的额外引号,并且至少有 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

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

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

关于python - 使用 bash 脚本设置 PYTHONPATH 并运行 nosetests,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com