简体   繁体   English

使用Python向正在运行的程序提供输入

[英]Give inputs to a running program using Python

I am running a python script via terminal. 我正在通过终端运行python脚本。 The script contains a main function. 该脚本包含一个主要功能。 It runs other programs in some directory and all those programs are in Python too. 它在某个目录中运行其他程序,所有这些程序也都在Python中。

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 MainProgram调用--dir1 / pg1.py

   ----inputs 10 20 30

Main program calls --dir1/pg2.py 主程序调用--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. 我需要一个程序(例如MainProgram.py),该程序在执行时会调用上述程序,并向其提供所需的输入,并获取输出并验证它是否正确。

Please help me with this. 请帮我解决一下这个。 Been searching for a solution for long. 一直在寻找解决方案。

Maybe you want the the input() function. 也许您需要input()函数。

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. 该程序将打印消息"Enter values"并等待用户输入内容,然后将每个值拆分为单独的列表元素,然后打印新列表。

Assuming you enter 10 20 30 the vals variable will be ["10", "20", "30"] . 假设您输入10 20 30vals变量将为["10", "20", "30"]

If you can, then it's better to call the function inside the pg1 and pg2 with the arguments. 如果可以的话,最好在pg1和pg2内部使用参数调用函数。 If you can't then: use os.system like this: 如果不能, 像下面这样使用os.system

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. 我认为您正在寻找stdin和stdout。

Check these two programs when one finish writing then another read it 当一个完成写入然后另一个读取它时,请检查这两个程序

sender.py 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 | 执行命令:./sender.py | ./reciever.py ./reciever.py

output by receiver.py: 通过receiver.py输出:

baby
baby
baby
baby
baby
baby
baby
baby
baby
baby

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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