Returning data to the original process that invoke

2019-08-11 11:31发布

问题:

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!