庆典:字符串插值
我从一个Python模块返回一个字符串,消费的bash脚本中。
I am returning strings from a python module, for consumption within a bash script.
这是我迄今为止:
SCRIPT_DIR=/somepath/to/scripts/folder
cd $SCRIPT_DIR/eod
python_cmd='import sys;
sys.path.append("/somepath/to/scripts/folder/utils");
import settings as st;
print " ".join(st.foo())'
# Fix indentation for Python
python_cmd=${python_cmd//' '/''}
my_array=(`python -c "$python_cmd"`)
我想使用的干理念在上面的代码段。但是,字符串重复 / somepath /至/脚本/文件夹
中的脚本。我想的$ SCRIPT_DIR定义传递到PYTHON_CMD - 但是我想(替换用$ SCRIPT_DIR / utils的的PYTHON_CMD路径字符串,并将其与失败,错误如下:
I want to use the DRY philosophy in the snippet above. However, the string/somepath/to/scripts/folder
is repeated in the script. I would like to pass the definition of $SCRIPT_DIR into the python_cmd - however I tried (replacing the path string in python_cmd with $SCRIPT_DIR/utils and it failed with the following error:
Traceback (most recent call last):
File "<string>", line 3, in <module>
ImportError: No module named settings
我在做什么错了?
What am I doing wrong?
注意:
我运行bash 4.1.5
I am running bash 4.1.5
不要刻意去传递字符串在所有。相反,在Python文本修改的sys.path
中,修改bash脚本PYTHONPATH环境变量。它更容易,并且是preferred方式反正影响导入路径。
Don't bother to pass the string in at all. Instead of modifying sys.path
in the Python text, modify the PYTHONPATH environment variable in the bash script. It's easier, and is the preferred way to affect the import path anyway.
如何设置路径的一个例子:
An example of how to set the path:
SCRIPT_DIR=/somepath/to/scripts/folder
cd $SCRIPT_DIR/eod
export PYTHONPATH=$SCRIPT_DIR
python_cmd='import settings as st;
print " ".join(st.foo())'
我也不得不说,这似乎是一个奇怪的方式来胶体成分在一起,但我没有足够的信息来推荐一种更好的方式。
I also have to say, this seems like an odd way to glue components together, but I don't have enough information to recommend a better way.