【发布时间】:2017-09-13 04:37:06
【问题描述】:
我想以前有人问过这个问题,但是我找不到以前的问题。
假设我有一个 python 脚本 helloPython.py,它会打印一些东西。现在我想从 bash 脚本中调用该脚本,这可以通过 like this 完成。到目前为止一切都很好。
但是,正确的 python 路径不一定总是在 PATH 中找到的第一个 python 可执行文件,因此我声明了一个包含默认路径的全局变量并使用a read in function 使用户能够为 python 可执行文件提供自定义路径。
详细来说,这是我的代码:
#!/bin/bash
PYTHON="/usr/bin/python" #default address
function helloPython {
return PYTHON helloPython.py;
}
function readin {
## Read in the options
for i in "$@"
do
case $i in
-p=*|--python=*)
PYTHON="${i#*=}"
shift
;;
*)
;;
esac
done
}
readin
helloPython
这给出:“返回:PYTHON:需要数字参数”
或者,return $(PYTHON helloPython.py); 给出“PYTHON: command not found”,return $($(PYTHON) checkPythonVersion.py); 给出“PYTHON: command not found \n checkPythonVersion.py: command not found”
所以现在我的问题是:如何使用全局变量 PYTHON 以便可以在 bash 中执行 python 脚本?
【问题讨论】:
-
顺便说一句,这里没有非全局变量。即使
i是全局的,并且在您运行readin之后与之前不同。要在 bash 中使用本地,您需要在分配给它之前在函数中显式声明它:local i或declare i。 -
(我还建议您将默认的 Python 解释器设置为
python,以便它遵循本地配置的 PATH,而不是硬编码/usr/bin)。 -
Bash 中的函数只能返回 0(零)到 255 之间的整数。
标签: bash