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'])
1
  • This does not work, the print output is simply "0". Commented Dec 30, 2020 at 16:42

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you. Is there a way for this to all be done within the test.py script?
what you mean by doing all with the test.py ? convert the bash script into python ?
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"
what wrong with that ? cmd = "bash test.sh -u " + Name + " -a " + Age it's doing what you want .
Is there a way to validate the output of the subprocess.call? When I print I just see "0"
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.