2014-02-10 143 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是一個阻塞調用,直到它收到一個線路輸入的。