Returning data to the original process that invoke a subprocess

不想你离开。 提交于 2019-12-11 04:20:03

问题


Someone told me to post this as a new question. This is a follow up to Instantiating a new WX Python GUI from spawn thread

I implemented the following code to a script that gets called from a spawned thread (Thread2)

# Function that gets invoked by Thread #2
def scriptFunction():
  # Code to instantiate GUI2; GUI2 contains wx.TextCtrl fields and a 'Done' button
  p = subprocess.Popen("python secondGui.py", bufsize=2048, shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE)

  # Wait for a response
  p.wait()

  # Read response
  response = p.stdout.read()

  # Process entered data
  processData()

On the new process running GUI2, I want the 'Done' button event handler to return 4 data sets to Thread2, and then destroy itself (GUI2)

def onDone(self,event):
  # This is the part I need help with; Trying to return data back to main process that instantiated this GUI (GUI2)
  process = subprocess.Popen(['python', 'MainGui.py'], shell=False, stdout=subprocess.PIPE)
  print process.communicate('input1', 'input2', 'input3', 'input4')

  # kill GUI
  self.Close()

Currently, this implementation spawns another Main GUI in a new process. What I want to do is return data back to the original process. Thanks.


回答1:


Do the two scripts have to be separate? I mean, you can have multiple frames running on one main loop and transfer information between the two using pubsub: http://www.blog.pythonlibrary.org/2010/06/27/wxpython-and-pubsub-a-simple-tutorial/

Theoretically, what you're doing should work too. Other methods I've heard of involve using Python's socket server library to create a really simple server that runs that the two programs can post to and read data from. Or a database or watching a directory for file updates.




回答2:


Function that gets invoked by Thread #2

def scriptFunction():
  # Code to instantiate GUI2; GUI2 contains wx.TextCtrl fields and a 'Done' button
  p = subprocess.Popen("python secondGui.py", bufsize=2048, shell=True,stdin=subprocess.PIPE, stdout=subprocess.PIPE)

  # Wait for a response
  p.wait()

  # Read response and split the return string that contains 4 word separated by a comma
  responseArray = string.split(p.stdout.read(), ",")

  # Process entered data
  processData(responseArray)

'Done' button event handler that gets invoked when the 'Done' button is clicked on GUI2

def onDone(self,event):
  # Package 4 word inputs into string to return back to main process (Thread2)
  sys.stdout.write("%s,%s,%s,%s" % (dataInput1, dataInput2, dataInput3, dataInput4))

  # kill GUI2
  self.Close()

Thanks for your help Mike!



来源:https://stackoverflow.com/questions/10689186/returning-data-to-the-original-process-that-invoke-a-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!