How to get bash script take input from python script - python

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" )

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?

Related

How do I pass a variable created in a python script to be used in a bash script? [duplicate]

This question already has answers here:
Passing multiple variables from python script to shell script
(3 answers)
Closed 2 years ago.
I am using Python 3.6.3.
I have created a python script 'create.py'. This python script calls and runs a bash script 'verify.sh'.
The 'verify.sh' script sends an email:
#!/bin/sh
emailGroup="dummy#email.com"
echo "The variable of interest is x(insert here): $1 " | mail -s "The variable of interest is x(insert here)" ${emailGroup}
So in my python script 'x' is determined. I want to insert x into the 'verify.sh' script above so that it goes out with the email.
If that's really the full extent of your verify.sh script, you can remove it entirely.
import subprocess
sent = subprocess.run(
['mail', '-s', 'The variable of interest is x(insert here)', 'dummy#email.com'],
input='The variable of interest is x(insert here): {0}'.format(x),
text=True, check=True)
If you are on an earlier version of Python than 3.7, you will want to use universal_newlines=True instead of text=True.
You don't really need mail -s either; see e.g. How to send an email with Python?
Here's an example of how to do that.
First the Python script:
#!/usr/bin/python3
import subprocess
recipient = "me#stackoverflow.com"
subject = "Python Script Calls Bash Script"
body = "This is a test, yes it is, yes it is."
notify_script = "/home/me/Scripts/notify"
subprocess.run([notify_script, recipient, subject, body])
Second the Bash script:
#!/bin/bash
recipient="$1"
subject="$2"
body="$3"
dummy_mailer -r "$recipient" -s "$subject" -b "$body"
Any number of args (see ARG_MAX) can be sent from the Python script using subprocess.run(), simply add or remove them from the list given to run(). e.g.
subprocess.run([path_to_script, arg_1])
subprocess.run([path_to_script, arg_1, arg_2])
subprocess.run([path_to_script, arg_1, arg_2, arg_3, arg_4])

How to nest script that inputs variable for automation purposes?

I'm creating a python script (cmd_exec.py) to open another python script (entername.py). How do I nest it so the script inputs string and execute the enter button all automatically? Trying to remember the question about ASCII input code for enter, but can't find it. So that when I run the cmd_exec.py in powershell, it would display "Hello foo":
cmd_exec.py:
import subprocess, sys
p = subprocess.Popen(["powershell.exe", "py C:\\Users\\uname\\PProjects\\cmdauto\\entername.py"], stdout=sys.stdout)
p.communicate()
I want maname variable to get inserted in the entername.py script and the script to execute/press enter button. So that when I run the cmd_exec.py script, I would see it doing all by itself and prints out "Hello foo"
entername.py:
maname = "foo"
person = input('Enter your name: ')
print('Hello', person)
Not sure if this helps or if this will work for you but in Bash you can specify input with the '<' operator.
For instance if you have a python file program.py and your inputs are in input.txt you can run
$ python3 program.py < input.txt
You may want to take this approach unless have other constraints
You may be looking for sys.argv and subprocess.getstatusoutput()
import subprocess
maname = "foo"
person = input('Enter your name: ')
print('Hello', person)
# not sure why powershell is here, normally would be only `python C:\\Users\\uname\\PProjects\\cmdauto\\entername.py {person}`
x = subprocess.getstatusoutput(f"powershell.exe 'py C:\\Users\\uname\\PProjects\\cmdauto\\entername.py {person}'")
print(x)
# (0, 'python f:\\entername.py')
# entername.py
import sys
person = int(sys.argv[1]) # get the 2nd item on `argv` list, the 1st is the script name

I can't run python file interactivly with terminal

I'm using OSX Mac terminal to run python 2.7.10.
for example:
I have a file called "myfile.py"
so when I want to run it on the terminal it would be like this:
python Desktop/myfile.py
However inside the file I have wrote some functions like
def myFunction(x,y):
return float(x)/y
with this method of running a python script I can not interact with my program and use myFunction to input x and y with different values every time and test myFunction properly.
Thank You,
Try passing -i before the script name
python -i myfile.py
You can learn more about what options are available by running man python.
To quote from the manual:
-i When a script is passed as first argument or the -c option
is used, enter interactive mode after executing the script
or the command. It does not read the $PYTHONSTARTUP file.
This can be useful to inspect global variables or a stack
trace when a script raises an exception.
You can use python -i script.py
This way, script.py is executed and then python enter interactive mode. In interactive mode you can use all functions, classes and variables that was defined in the script.
You can use raw_input() to do that.Your myfile.py code can look like this:
def myFunction(x,y):
return float(x)/y
x = raw_input("Please enter x value: ")
y = raw_input("Please enter y value: ")
print(myFunction(x,y))

Python script not able to read user input when run remotely

I am trying to remotely execute a simple python script userinfo.py present in remotehost.
Below is sourcecode of userinfo.py [ using Python 2.7.10 ]
#############
print "Userinfo :"
name=raw_input("Enter your name")
age=raw_input("Enter your age")
print "Name"+name+"\nAge"+age
#############
But script is working abnormally when run remotely.
[user#localhost]# ssh remotehost python /home/userinfo.py
Userinfo :
Enter your nameEnter your ageName
Age
[user#localhost]#
Execution summary ::
During execution, it doesn't print anything, it directly waits for user input and I just pressed Enter key it will display output as above.
Would like to know why it is not behaving as expected when raw_input is used.
When values are passed as arguments, it works fine.
[user#localhost]# ssh remotehost python userinfo.py xyz 20
Userinfo :
Name xyz
Age 20
[user#localhost]#
below is changed code.
###########
import sys
print "Userinfo :"
name=sys.argv[1]
age=sys.argv[2]
print "Name "+name+"\nAge "+age
############
Would like to know why interactive way is not working as expected and what may be fix.
In a regular terminal, the raw_input prompt is flushed immediately, meaning you will see the prompt "Enter Your Name".
If you run this script through ssh, it saves the output until the script it finished and only then prints everything in the buffer.
What you need is to run python unbuffered, which will force stdout to flush after every output, and thus display to your ssh session. This can be accomplished several ways.
ssh user#remotehost python -u script.py
or make the file executable and unbuffered by adding the following to top of your .py script. Be sure to use your actual python path here:
#! /usr/bin/python - u
and then in make it executable
sudo chmod +x script.py
then
ssh user#remotehost ./script.py

python cvs check out

I am writing an automation script in python and I need to cvs update from script.
In bash my commands look like this:
cvs login
CVS Password: <here i enter the password>
cvs update -P -d
I was using the sub-process module in python to do this, but it fails when it asks for the password.
Any ideas?
The pyCVS module can help you sovle the problem by using a binding.
In general, subprocesses have been, in my experience, much more trouble than just using a library that accomplishes the same thing.
Generally you can pass as arguments like this simplified code:
## program run.py
def print_args(name, passwd):
print name
print passwd
## calling program
import run
input_name = raw_input("Enter name ")
input_passwd = raw_input("Enter password ")
run.print_args(input_name, input_passwd)

Categories