1

I have some Python 2.7 code which takes input from the user and stores it as variables.

I would like to execute a test.sh Bash script but using the Python variables which I have created.

For example, what I want to accomplish: ./test.sh -a "VARIABLE1" -b "VARIABLE2" -c "VARIABLE3" The -a, -b, & -c are Bash options and the variables are the code that goes with them.

This is the code I have so far:

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

subprocess.call(['sh', './test.sh'])
Armaan
  • 75
  • 1
  • 7

1 Answers1

2

You can use shlex:

test.sh:

if [[ ${#@} > 0 ]]; then
  while [ "$1" != "" ]; do
    case $1 in
      -u | --user )
        shift
        user="$1"
        ;;
      -a|--age )
        shift
        age="$1"
        ;;
    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
Dr Claw
  • 636
  • 4
  • 15
  • Thank you. Is there a way for this to all be done within the test.py script? – Armaan Dec 30 '20 at 16:22
  • what you mean by doing all with the test.py ? convert the bash script into python ? – Dr Claw Dec 30 '20 at 16:26
  • I want the contents of the Bash script to stay as they are. Just need the py script with the variables to call the Bash script in a specific way. i.e. ./test.sh -a "VARIABLE1" -b "VARIABLE2" -c "VARIABLE3" – Armaan Dec 30 '20 at 16:50
  • what wrong with that ? `cmd = "bash test.sh -u " + Name + " -a " + Age` it's doing what you want . – Dr Claw Dec 30 '20 at 16:57
  • Is there a way to validate the output of the subprocess.call? When I print I just see "0" – Armaan Dec 30 '20 at 17:18
  • This is another question .. but you can use `res = subprocess.check_output(shlex.split(cmd))` but check for `subprocess.Popen()` instead. – Dr Claw Dec 30 '20 at 17:26