当前位置: 动力学知识库 > 问答 > 编程问答 >

Python wrapper for Python program

问题描述:

I'm looking for a way to create a Python program that wraps another Python program. 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

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

# use program1.py somehow

while program1_is_waiting_for_input:

send_to_program1("prefix " + raw_input() + " suffix")

sample input into program2:

asdf

ghjkl

1234

sample output out of program2:

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



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

网友答案:

take a look at subprocess module or https://pypi.python.org/pypi/pexpect-u/

分享给朋友:
您可能感兴趣的文章:
随机阅读: