简体   繁体   English

Python程序的Python包装器

[英]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: 我考虑过的事情:

  • I don't think eval or exec or anything like that would work, since I don't know how much code to execute. 我不认为evalexec或类似的东西会起作用,因为我不知道要执行多少代码。
  • The subprocess module might work if I pipe the outputs correctly, but can I "pause" the second program when waiting for input? 如果我正确地管道输出,子进程模块可能会工作,但是在等待输入时我可以“暂停”第二个程序吗?
  • Maybe I should try to multithread the non-wrapper program, but I don't know how I would go about doing that 也许我应该尝试多线程非包装程序,但我不知道我会怎么做
  • Download an open-source python interpreter and try to work off that (seems overly difficult for a relatively simple problem) 下载一个开源的python解释器并尝试解决这个问题(对于一个相对简单的问题来说似乎过于困难)



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. 如果这样做更容易,那就太好了。

看看子流程模块或https://pypi.python.org/pypi/pexpect-u/

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.

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