First time here? Check out the FAQ!

Revision history  [back]

Here's a different approach that does hook up to presave to replace the contents of the editor at save time, just before saving, with the output from yapf:

import subprocess
import wingapi

def run_yapf(doc=wingapi.kArgDocument):

  # Set to non-None to use an uninstalled copy of yapf
  kYapfDir = None
  #kYapfDir = '/Users/jpe/Documents/tmp/yapf'

  proj = wingapi.gApplication.GetProject()
  pyexec = proj.GetPythonExecutable(doc.GetFilename())

  orig_text = doc.GetText()

  argv = [pyexec, '-m', 'yapf']
  process = subprocess.Popen(argv, cwd=kYapfDir, stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  from_yapf, error_output = process.communicate(orig_text)
  if from_yapf != orig_text:
    doc.SetText(from_yapf)

def _connect_to_document(doc):
  def _on_presave(filename, encoding):
    # Called for autosave w/ filename set to non-None
    if filename is not None:
      return

    if doc.GetMimeType() == 'text/x-python':
      run_yapf(doc)

  connect_id = doc.Connect('presave', _on_presave)

def _init():
  wingapi.gApplication.Connect('document-open', _connect_to_document)
  for doc in wingapi.gApplication.GetOpenDocuments():
    _connect_to_document(doc)

_init()

Here's a different approach that does hook up to presave to replace the contents of the editor at save time, just before saving, with the output from yapf:

yapf:
import subprocess
import wingapi

def run_yapf(doc=wingapi.kArgDocument):

  wingapi

def run_yapf(doc=wingapi.kArgDocument):

# Set to non-None to use an uninstalled copy of yapf kYapfDir = None #kYapfDir = '/Users/jpe/Documents/tmp/yapf' '/Users/jpe/Documents/tmp/yapf'

proj = wingapi.gApplication.GetProject() pyexec = proj.GetPythonExecutable(doc.GetFilename()) proj.GetPythonExecutable(doc.GetFilename())

orig_text = doc.GetText() doc.GetText()

argv = [pyexec, '-m', 'yapf'] process = subprocess.Popen(argv, cwd=kYapfDir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) from_yapf, error_output = process.communicate(orig_text) if from_yapf != orig_text: doc.SetText(from_yapf) doc.SetText(from_yapf)

def _connect_to_document(doc): def _on_presave(filename, encoding): # Called for autosave w/ filename set to non-None if filename is not None: return return

if doc.GetMimeType() == 'text/x-python':
   run_yapf(doc)
 

connect_id = doc.Connect('presave', _on_presave) _on_presave)

def _init(): wingapi.gApplication.Connect('document-open', _connect_to_document) for doc in wingapi.gApplication.GetOpenDocuments(): _connect_to_document(doc) _connect_to_document(doc)

_init()

​