[英]Python wrapper for Python program
I'm looking for a way to create a Python program that wraps another Python program. 我正在寻找一种方法来创建一个包装另一个Python程序的Python程序。 This is what I mean:
这就是我的意思:
while (otherProgram is waiting for raw_input):
send some text to the other program
It is essential that I can do this in two separate programs. 我必须在两个单独的程序中执行此操作。
Here is another example: 这是另一个例子:
program1.py program1.py
text = raw_input()
print("You entered " + text)
text2 = raw_input()
print("Your second input was " + text2)
text3 = raw_input()
print("Your third input was " + text3)
program2.py program2.py
# use program1.py somehow
while program1_is_waiting_for_input:
send_to_program1("prefix " + raw_input() + " suffix")
sample input into program2: 样本输入到program2:
asdf
ghjkl
1234
sample output out of program2: 程序2的样本输出:
You entered prefix asdf suffix
Your second input was prefix ghjkl suffix
Your third input was prefix 1234 suffix
Things I have considered using: 我考虑过的事情:
eval
or exec
or anything like that would work, since I don't know how much code to execute. eval
或exec
或类似的东西会起作用,因为我不知道要执行多少代码。
What I hope to end up with 我希望最终得到什么
I eventually want to end up with a Python program which, each time it is run, inserts another successive input into the wrapped program at the point it left off, and pipes the output into stdout. 我最终希望最终得到一个Python程序,每次运行时,在它停止的位置将另一个连续输入插入到包装程序中,并将输出传递给stdout。 If it is easier to do this, that would be great.
如果这样做更容易,那就太好了。
Here is an example of running the child process using subprocess. 以下是使用子进程运行子进程的示例。
import subprocess
program1 = subprocess.Popen("program1.py", stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while program1.poll() == None:
cmd_to_send = "prefix " + raw_input() + " suffix"
program1.stdin.write(cmd_to_send + "\n")
Your child process will wait for input because raw_input
is a blocking call until it receives a line of input. 您的子进程将等待输入,因为
raw_input
是一个阻塞调用,直到它收到一行输入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.