1

I am running a python script via terminal. The script contains a main function. It runs other programs in some directory and all those programs are in Python too.

While running these sub programs, I need to enter their required input values in the terminal using this main program(not command line arguments).

Ex:

MainProgram calls --dir1/pg1.py

   ----inputs 10 20 30

Main program calls --dir1/pg2.py

   ----inputs 100 20 30  like wise the inputs to the subprograms are to be given by the main program.

I am trying to automate the process of giving input to a program and I need to do it with the help of a program. Ex: the given below is a simple program for finding factorial

i=1
fact=1
num=input("Enter the num : ")
while i<=num:
    fact*=i
    i+=1
print fact

I need a program(say MainProgram.py) that on execution calls the above program and give the required input to it and gets the output and validates if it is right or not.

Please help me with this. Been searching for a solution for long.

openacc
  • 11
  • 1
  • 4
  • 2
    Possible duplicate of [Getting user input](https://stackoverflow.com/questions/3345202/getting-user-input) – SCB Dec 27 '17 at 05:37
  • Are you refering to the input() function documented here; https://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html – Yohst Dec 27 '17 at 05:41

4 Answers4

2

I think you are looking for the stdin and stdout.

Check these two programs when one finish writing then another read it

sender.py

#!/usr/bin/python
import sys
for i in range(0,10):
    sys.stdout.write('baby\n')

reciever.py

#!/usr/bin/python
import sys
data = sys.stdin.read()
print data

Command to execute : ./sender.py | ./reciever.py

output by receiver.py:

baby
baby
baby
baby
baby
baby
baby
baby
baby
baby
babygame0ver
  • 447
  • 4
  • 16
0

If you can, then it's better to call the function inside the pg1 and pg2 with the arguments. If you can't then: use os.system like this:

from os import system

system('python pg1.py 10 20 30')
abybaddi009
  • 1,014
  • 9
  • 22
0
p = Popen(["python",programURL], stdin=PIPE, stdout=PIPE)
out = p.communicate(input=f.read())[0]

Got something like this. But this is not effective when user inputs values in a loop.

openacc
  • 11
  • 1
  • 4
-1

Maybe you want the the input() function.

vals = input("Enter values").split(" ")
print(vals)

The program will print the message "Enter values" and wait for the user to enter something, then split each value into a separate list element and print the new list.

Assuming you enter 10 20 30 the vals variable will be ["10", "20", "30"].

SCB
  • 5,821
  • 1
  • 34
  • 43