How to execute a command & respond to multiple inputs using python subprocess? - python

I am trying to understand how to execute a command/program using python subprocess module & respond to the prompt by giving input.
Sample Program Program1.py which can take multiple input's:
arr1=[]
username = input("Enter your username1 : ")
password = input("Enter your password1 : ")
arr1.append((username,password))
username = input("Enter your username2 : ")
password = input("Enter your password2 : ")
arr1.append((username,password))
username = input("Enter your username3 : ")
password = input("Enter your password3 : ")
arr1.append((username,password))
username = input("Enter your username4 : ")
password = input("Enter your password4 : ")
arr1.append((username,password))
for item in arr1:
print("username:",item[0],"Password:",item[1])
I have written another program called Execute_Program1.py
import subprocess
proc = subprocess.Popen('python Program1.py',stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE,shell=True,universal_newlines=True)
print(proc.poll())
while proc.poll() is None:
print(proc.stdout)
proc.stdin.write('inputdata\n')
But this program is not able to execute the Program1.py. I have read many posts related to this. As per the information I have got proc.poll() return's None then the command executed by Popen is still active.
But my program is giving the following output:
None
<_io.TextIOWrapper name=4 encoding='cp1252'>
I am using Python version 3.7.4. Could anyone please help me with some inputs where I am doing mistake?
Thanks in advance.

I could not get it to work with subprocess at this time but I wanted you to have an ASAP working solution using the os module in case you need this quickly and are not absolutely required to use the subprocess module...
First add this line to the end of Program1.py, with no indentation, to prevent the command window from exiting before you have a chance to see the output:
input("Press <enter> to continue")
Next, replace your entire code in Execute_Program1.py with the following:
import os
os.system("python Program1.py 1")
This worked beautifully in Python 3.8.1 on win10pro.

Related

using subprocess.run to automate a command line application (windows 10)

trying to use python to automate a usage of a command line application called slsk-cli
manually, the procedure is straight-forward - i open a command prompt window and type 'soulseek login', then a prompt requests username, after i type in and press enter i'm requested a password.
so far, i manage to get the prompt of the username but not getting passed that.
subprocess.run('soulseek login',shell=True)
this results in the ?Login output in the python console but also the process is stuck, when i run in debug or also in run
is there a better way to go about this?
Interacting continuously with a system via subprocess can be tricky. However, it seems that your interface prompts are one after the other, which can therefore be chained together, via newline characters which act as Return key strokes.
For example, the program shown below simply prompts a user for their username and a password, to which the 'user' (your script) provides the input via the proc.communicate() method. Once these are provided, the user is asked if they'd like to continue (and do the same thing again). The following subprocess call feeds the following input into the prompter.py script:
username
password
continue reply (y or n)
Example code:
import subprocess
uid = 'Bob'
pwd = 'MyPa$$w0rd'
reply = 'n'
with subprocess.Popen('./prompter.py',
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
text=True) as proc:
stdout, stderr = proc.communicate(input='\n'.join([uid, pwd, reply]))
Output:
# Check output.
>>> print(stdout)
Please enter a username: Password: uid='Bob'
pwd='MyPa$$w0rd'
Have another go? [y|n]:
# Sanity check for errors.
>>> print(stderr)
''
Script:
For completeness, I've included the contents of the prompter.py script below.
#!/usr/bin/env python
from time import sleep
def prompter():
while True:
uid = input('\nPlease enter a username: ')
pwd = input('Password: ')
print(f'{uid=}\n{pwd=}')
sleep(2)
x = input('Have another go? [y|n]: ')
if x.lower() == 'n':
break
if __name__ == '__main__':
prompter()

How to execute a Python program without any interruption when we change the shell or switch the Linux users inside the program?

Scenario: I made one program where I am taking the input file and execute the shell commands inside the file line by line using Python. But I noticed when we change the shell or switch the user, the execution stops on the go.
Input File:
# cat commands.txt
free -m
touch hi
ls -lrt
su - user
Code:
# cat mylinux.py
# This program is to interact with Linux
try:
import os
import subprocess
import shlex
print("This is an interactive linux session using Python! \nHere if you want to exit the session, type exit as the input command")
print("Your RHEL OS version is "+subprocess.run(shlex.split("cat /etc/redhat-release"),stdout=subprocess.PIPE).stdout.decode())
i = input("Enter the file name: ")
inputfile = open(i,"r")
for line in inputfile:
o=subprocess.run(shlex.split(line), stdout=subprocess.PIPE).stdout.decode()
print(o)
except FileNotFoundError:
if i != "exit":
print("Please re-run the script and make sure to give some valid commands.")
print("Thank you for using your PyShell!")
except IndexError:
print("Bye! Next time, type some valid commands")
How would I make sure this works even when the shell or user changes?

Why is subprocess.run entering a newline for input?

This is a sample code snippet which reproduces the issue I'm facing:
import subprocess
ctb_path = "\"C:\\Program Files\\Cold Turkey\\Cold Turkey Blocker.exe\""
exception = input("Enter the exception phrase: ")
subprocess.run(f'{ctb_path} -add Distractions -exception \"*{exception}*\"', check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
choice = input("Enter your choice between 1 & 2: ")
Here, I'm not asked for an input because a newline has been accepted instead and successfully exited the program. What are the possible reasons this may occur? How can it be fixed?
Refer this for Cold Turkey Blocker's User Guide.

Python 3.4 How do you limit user input

I have made a program which requires the user to go and come back after completing the command, I would like the user to press ENTER to then continue the programme, to do this I used a normal Input command that does not record the answer. However I would like it if the user cannot enter any text, the only thing they can do is press ENTER to proceed.
input("Please charge your device, when you are finished, press ENTER on the keyboard")
You can try to write an if loop that checks whatever the input is enter: For example:
import tty
import sys
import termios
orig_settings = termios.tcgetattr(sys.stdin)
tty.setraw(sys.stdin)
x = input("Text")
while x != chr(13): # Enter
x=sys.stdin.read(1)[0]
print("ERROR PLEASE TRY AGAIN")
x = input("Text")
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)
You might like to check this answer by #Turn at the question here: https://stackoverflow.com/a/34497639/2080764

python subprocess: check to see if the executed script is asking for user input

import subprocess
child = subprocess.Popen(['python', 'simple.py'], stdin=subprocess.PIPE)
child.communicate('Alice')
I know you can communicate with executed script via communicate
How do you check for whether a script 'simple.py' is asking for user input?
simple.py could ask for 5-10 user inputs so simply hardcoding communicate wouldnt be enough.
[EDIT]: want to parse the stdout as the script is running and communicate back to the script
while True:
if child.get_stdout() == '?':
# send user input
A simple example:
simple.py:
i = raw_input("what is your name\n")
print(i)
j = raw_input("What is your age\n")
print(j)
Read and write:
import subprocess
child = subprocess.Popen(['python2', 'simple.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in iter(child.stdout.readline, ""):
print(line)
if "name" in line:
child.stdin.write("foo\n")
elif "age" in line:
child.stdin.write("100\n")
Output:
what is your name
foo
What is your age
100

Categories

Resources