Anirudh
Anirudh

Reputation: 43

How to get bash script take input from python script

I am new to programming in python and wanted to try something out.

I have a bash script, which takes in parameters like User name, Full name etc. This is the bash script I have

#!/bin/sh

echo -n "username: "
read username

echo -n "First name: "
read first

echo -n "Last name: "
read last

echo "$username", "$first", "$last"

I am trying to call the bash script via python. Except I want to enter the parameters in python and it needs to be parsed to the bash script. Any help will be greatly appreciated.

Python code to call the bash script

import os

import sys

os.system("pwd")

os.system("./newuser1.list" )

Upvotes: 1

Views: 2401

Answers (1)

Andreas Lorenzen
Andreas Lorenzen

Reputation: 4230

You are not specific to your python version, but here is something that works with 2.7.

As I understand, you want to take input in the python script and pass it to the bash script. You can use raw_input("Prompt") in python 2, and just input("Prompt") for python 3. When passing the params to the shell script, simply append them to the string passed to the shell.

As such:

import os

user_name = raw_input("Enter username: ")
first_name = raw_input("Enter firstname: ")
last_name = raw_input("Enter lastname: ")

os.system("./test.sh {0} {1} {2}".format(user_name, first_name, last_name))

For the shell script, grab the params with the $1, $2... environment style variables. Put them in variables like below, or just use them directly.

The shell script (For the example i named it test.sh):

#!/bin/sh

userName=$1
firstName=$2
lastName=$3

echo "$userName, $firstName, $lastName"

Is this what you were looking for?

Upvotes: 2

Related Questions