为了只传递一个参数,你可以有一个这样的 python 脚本:
import subprocess
correctBc4jfiles = ["1","2","3"]
subprocess.call(["/bin/bash", "/path/to/mail.sh"] + correctBc4jfiles)
并有一个像这样的 bash 脚本:
#!/bin/bash
# I want to know the number of files the correctBc4jfiles variable holds
echo "$#"
# I want to iterate this variable correctBc4jfiles. how will i iterate it in shell script.
for A in "$@"; do
echo "$A"
done
# I want to assign the value of the correctBc4jfiles variable into another array variable which belongs to the shell script itself.
ANOTHER=("${@}")
# for A in "${ANOTHER[@]}"; do ...
我们可以将多个变量从 python 传递到 shell 脚本吗?就像在这种情况下我们只传递一个变量correctBc4jfiles?我怎样才能做到这一点?
您必须让您的 python 脚本传递每个变量的值的数量,例如:
import subprocess
var0 = ["|1|", "|2|", "|3|"]
var1 = ["|4|", "|5|", "|6|"]
subprocess.call(["/bin/bash", "script.sh"] + [str(len(var0))] + var0 + [str(len(var1))] + var1)
让 bash 解释它:
#!/bin/bash
varprefix='var'
varindex=0
declare -i count
while [[ $# -gt 0 ]]; do
count=$1
if [[ count -gt 0 ]]; then
eval "${varprefix}$(( varindex++ ))=(\"\${@:2:count}\")"
shift "$count"
fi
shift
done
set | grep ^var ## Just show what variables were made.
它给出这样的输出:
var0=([0]="|1|" [1]="|2|" [2]="|3|")
var1=([0]="|4|" [1]="|5|" [2]="|6|")
varindex=2
varprefix=var
因此,您已经可以使用 varX。
如果您不喜欢 varX 格式,您可以将值复制到所需的数组变量:
myarray1=("${var0[@]}")
myarray2=("${var1[@]}")