2012-06-15 9 views

Respuesta

14

Puede activar el código de PyDev-formateador con Ctrl +Shift +F (preferencias en: Ventana> Preferencias> PyDev> Editor> Estilo de Código> Código formateador - incluso se puede permitir que se para trabajar de forma automática).

Aún así, el formateador de código PyDev interno es bastante conservador y no realizará todas las transformaciones necesarias para un código PEP8 100% compatible (aunque maneja los casos más comunes), por lo tanto, si no es suficiente para sus necesidades, tiene algunas opciones:

  1. puede utilizar autopep8.py que también está integrado en PyDev por defecto en la versión más reciente (habilitado mediante ventana> Preferencias> PyDev> Editor> Estilo de Código> Código formateador> uso autopep8. py para formatear el código?)

  2. Puede echar un vistazo a PythonTidy (herramienta externa) ... es posible utilizarlo como se define en: http://bear330.wordpress.com/2007/10/30/using-pythontidy-in-pydev-as-code-formatter/

4

he hecho un script hacen posible el uso de autopep8 en pydev como formateador de código, y puede personalizarse para satisfacer el estándar de codificación en su equipo.

Si desea usarlo, guarde este código en alguna parte ya que pyedit_autopep8.py (pyedit_XXXX.py es obligatorio). También debe instalar los paquetes python pep8 y autopep8.

A continuación, vaya a eclipsar página de preferencias PyDev (en: Ventana> Preferencias> pydev> pydev scripting) para especificar la ubicación del script:

Ahora, con el fin de invocar autopep8 sólo tiene que pulsar Ctrl + Shift + F mientras edita el código python en eclipse. ¡Formatear el texto seleccionado también es compatible!

""" 
By Per A. Brodtkorb 
based on pyedit_pythontidy.py by Bear Huang (http://bear330.wordpress.com/). 

This code is public domain. 
""" 

import tempfile 
import os 

if False: 
    from org.python.pydev.editor import PyEdit # @UnresolvedImport 
    cmd = 'command string' 
    editor = PyEdit 

assert cmd is not None 
assert editor is not None 

if cmd == 'onCreateActions': 
    from org.python.pydev.editor.actions import PyAction 
    from org.python.pydev.core.docutils import PySelection 
    from java.lang import Runnable 
    from org.eclipse.swt.widgets import Display 
    from java.io import FileWriter 
    import java.lang.Exception 

    FORMAT_ACTION_DEFINITION_ID = "org.python.pydev.editor.actions.pyFormatStd" 
    FORMAT_ACTION_ID = "org.python.pydev.editor.actions.navigation.pyFormatStd" 

    class Autopep8Action(PyAction): 
     def _autopep8(self, text): 
      tmp_full_file_name = tempfile.mktemp() 
      f1 = FileWriter(tmp_full_file_name) 
      f1.write(text) 
      f1.close() 
      os.system('autopep8-script.py -i "%s"' % (tmp_full_file_name)) 
      f2 = open(tmp_full_file_name, "r") 
      tidy_text = f2.read() 
      f2.close() 
      os.remove(tmp_full_file_name) 
      return tidy_text 

     def _get_text(self, selection): 
      text = selection.getSelectedText() 
      format_all = len(text) == 0 
      if format_all: 
       print "Autopep8: format all." 
       text = selection.getDoc().get() 
       text_offset = 0 
      else: 
       print "Autopep8: Format selected." 
       text_offset = selection.getAbsoluteCursorOffset() 
      return text, text_offset 

     def run(self): 
      try: 
       selection = PySelection(editor) 

       text, text_offset = self._get_text(selection) 
       tidy_text = self._autopep8(text) 

       if len(text)==len(tidy_text): 
        print "Autopep8: Nothing todo!" 
       else: 
        doc = selection.getDoc() 
        doc.replace(text_offset, len(text), tidy_text) 

      except java.lang.Exception, e: 
       self.beep(e) 

    def bindInInterface(): 
     act = Autopep8Action() 
     act.setActionDefinitionId(FORMAT_ACTION_DEFINITION_ID) 
     act.setId(FORMAT_ACTION_ID) 
     try: 
      editor.setAction(FORMAT_ACTION_ID, act) 
     except: 
      pass 

    class RunInUi(Runnable): 

     '''Helper class that implements a Runnable (just so that we 
     can pass it to the Java side). It simply calls some callable. 
     ''' 

     def __init__(self, c): 
      self.callable = c 

     def run(self): 
      self.callable() 

    def runInUi(callable): 
     ''' 
     @param callable: the callable that will be run in the UI 
     ''' 
     Display.getDefault().asyncExec(RunInUi(callable)) 

    runInUi(bindInInterface) 
+2

Como nota, autopep8.py está actualmente integrado en PyDev por defecto (solo tiene que estar habilitado en las preferencias). –

Cuestiones relacionadas