2014-02-10 50 views
0

我正在寻找一种方法来创建一个包装另一个Python程序的Python程序。这就是我的意思:Python程序的Python包装

while (otherProgram is waiting for raw_input): 
    send some text to the other program 

重要的是,我可以在两个单独的程序中做到这一点。


下面是另一个例子:

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") 

样品输入到程序2:

asdf 
ghjkl 
1234 

样本输出了程序2的:

You entered prefix asdf suffix 
Your second input was prefix ghjkl suffix 
Your third input was prefix 1234 suffix 



事情我必须使用考虑:

  • 我不认为evalexec或类似的东西,将工作,因为我不知道要执行多少代码。
  • 如果我正确输出输出,子过程模块可能会工作,但在等待输入时可以“暂停”第二个程序吗?
  • 也许我应该尝试多线程的非包装程序,但我不知道我会怎么做这样做
  • 下载一个开放源代码的python解释器,并试图解决这个问题(似乎太困难了比较简单的问题)



我希望与

结束了,我最终想在每次运行时一个Python程序,该程序结束后,插入另一连续输入到包装程序在它停止的地方,并将输出传送到标准输出。如果这样做更容易,那就太好了。

+1

我不是很确定,但你可能想看'gevent'模块。 – thefourtheye

+1

为什么不能从其他脚本中导入组件? – Blender

+0

“暂停”第二个程序是什么意思? –

回答

1

下面是运行使用子子进程的一个例子。

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") 

你的孩子进程将等待输入,因为raw_input是一个阻塞调用,直到它收到一个线路输入的。