如何将变量添加到 Python subprocess.call 中的 Bash 脚本

How to add variables to Bash script in Python subprocess.call

我有一些 Python 2.7 代码,它接受用户的输入并将其存储为变量。

我想执行 test.sh Bash 脚本,但使用我创建的 Python 变量。

例如,我想要完成的事情:./test.sh -a "VARIABLE1" -b "VARIABLE2" -c "VARIABLE3" -a、-b 和 -c 是 Bash 选项,变量是它们附带的代码。

这是我目前的代码:

Name = input("What is your name?")
Age = input("What is your age?")
City = input("What is your city?")

subprocess.call(['sh', './test.sh'])

您可以使用 shlex:

test.sh:

if [[ ${#@} > 0 ]]; then
  while [ "" != "" ]; do
    case  in
      -u | --user )
        shift
        user=""
        ;;
      -a|--age )
        shift
        age=""
        ;;
    esac
    shift
  done
fi

echo "$user:$age"

test.py:

import subprocess 
import shlex

Name = input("What is your name? ")
Age = input("What is your age? ")

cmd = "bash test.sh -u " + Name + " -a " + Age 
subprocess.call(shlex.split(cmd))
$ python2 test.py 
What is your name? 'vinzz'
What is your age? '25'
vinzz:25