0

I have a batch file which is data.sh . so I am running this using python

and data.sh code is something like this

configure()
{
    read -p '--> Enter  key ID: ' key_id
    read -p '--> Enter  secret key: ' secret_key

    echo "$key_id"
    echo "$secret_key"
}

I am running this something like this

import subprocess

rc = subprocess.call("data.sh")

I want to pass these both pass key_id and secret_key using python code. how I can achieve this ?

TNN
  • 391
  • 1
  • 5
  • 12
  • `configure()` isn't set up to read values from the command line, so you can't. You'll have to rewrite it. Also, shell scripts aren't batch files. – MattDMo Nov 12 '20 at 23:47
  • Does this answer your question? [How do I write to a Python subprocess' stdin?](https://stackoverflow.com/questions/8475290/how-do-i-write-to-a-python-subprocess-stdin) – Brian McCutchon Nov 13 '20 at 00:33
  • @MattDMo You don't have to rewrite it. The OP can just write to the stdin of the subprocess. – Brian McCutchon Nov 13 '20 at 00:36

2 Answers2

0

Like MattDMo said in the comment, configure does not use any command line args. If you change it to use command line args ($1 is the first command line arg, $2 is the second etc...), you can change the subprocess.call() function call to use a list of arguments. The first arg passed in the list will be the executable and the other arguments will be passed to the the executable as command line args. See the docs for subprocess.call here. There's a good example calling the ls executable with a command line arg of -l. You wouldn't need to use any dashes(like -l in the ls example), you could just pass the key id as the first argument, and the secret key as the second. This would look like the following:

Python:

rc = subprocess.call(["data.sh", key_id, secret_key])

Shell:

configure()
{
    key_id=$1
    secret_key=$2
    echo "$key_id"
    echo "$secret_key"
}
Dylan Fox
  • 68
  • 5
0

If you don't want to change the script to take command-line arguments, you can do

subprocess.Popen(["./data.sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True).communicate('key123\nabcd')
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134