简体   繁体   中英

Give inputs to a running program using Python

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.

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"] .

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')
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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM