Difference between revisions of "Pml2py"

From PyMOLWiki
Jump to navigation Jump to search
(created)
 
(parse list arguments)
Line 19: Line 19:
 
TODO
 
TODO
  
     comments, aliases, list arguments
+
     comments, aliases
 
     '''
 
     '''
 
     def quote(args):
 
     def quote(args):
 +
        args = iter(args)
 
         for arg in args:
 
         for arg in args:
 
             if '=' not in arg:
 
             if '=' not in arg:
                 yield repr(arg)
+
                 prefix = ''
 
             else:
 
             else:
                 a = arg.split('=', 1)
+
                 prefix, arg = arg.split('=', 1)
                 yield a[0] + '=' + repr(a[1])
+
                 prefix += '='
 +
                arg = arg.lstrip()
 +
            if arg.startswith('['):
 +
                while not arg.endswith(']'):
 +
                    arg += ',' + args.next()
 +
            elif arg.startswith('('):
 +
                while not arg.endswith(')'):
 +
                    arg += ',' + args.next()
 +
            yield prefix + repr(arg)
 +
 
 
     if isinstance(out, basestring):
 
     if isinstance(out, basestring):
 
         out = open(out, 'w')
 
         out = open(out, 'w')
 +
 
     print >> out, '''
 
     print >> out, '''
 
# automatically converted from "%s"
 
# automatically converted from "%s"
Line 35: Line 46:
 
from pymol import *
 
from pymol import *
 
''' % (filename)
 
''' % (filename)
 +
 
     handle = iter(open(filename))
 
     handle = iter(open(filename))
 
     for line in handle:
 
     for line in handle:
Line 48: Line 60:
 
             name = cmd.kwhash.shortcut.get(name, name)
 
             name = cmd.kwhash.shortcut.get(name, name)
 
             func = cmd.keyword[name][0]
 
             func = cmd.keyword[name][0]
             assert func.func_name != 'python_help'
+
             assert func.__name__ != 'python_help'
 
         except:
 
         except:
 
             out.write(line)
 
             out.write(line)
 
             continue
 
             continue
  
         if func.func_name == '<lambda>':
+
         if func.__name__ == '<lambda>':
 
             print >> out, 'cmd.do(%s)' % (repr(line.strip()))
 
             print >> out, 'cmd.do(%s)' % (repr(line.strip()))
            continue
 
 
        # FIXME hack for set_view list argument
 
        if name == 'set_view':
 
            print >> out, 'cmd.set_view(' + a[1] + ')'
 
 
             continue
 
             continue
  
Line 66: Line 73:
 
         else:
 
         else:
 
             args = []
 
             args = []
 +
 +
        # old syntax: set property=value
 +
        if name in ['set', 'set_color'] and '=' in args[0]:
 +
            args = [i.strip() for i in args[0].split('=', 1)] + args[1:]
  
 
         if name == 'python':
 
         if name == 'python':
Line 74: Line 85:
 
             continue
 
             continue
  
         print >> out, '%s.%s(%s)' % (func.__module__, func.func_name, ', '.join(quote(args)))
+
        # use 'cmd' module if possible
 +
        try:
 +
            test = getattr(cmd, func.__name__)
 +
            assert func == test
 +
            module = 'cmd'
 +
        except:
 +
            module = func.__module__
 +
 
 +
         print >> out, '%s.%s(%s)' % (module, func.__name__, ', '.join(quote(args)))
  
 
cmd.extend('pml2py', pml2py)
 
cmd.extend('pml2py', pml2py)
  
 
# vi:expandtab:smarttab
 
# vi:expandtab:smarttab
 +
 
</source>
 
</source>
 +
 +
[[Category:Script_Library]]
 +
[[Category:System_Scripts]]

Revision as of 14:22, 9 April 2011

This script converts a pml script to a python script.

See pymol-users mailing list (Subject: Convert pml script to Pymol Python script, Fri, 8 Apr 2011).

import sys
from pymol import cmd

def pml2py(filename, out=sys.stdout):
    '''
DESCRIPTION

    Convert a pml script to python syntax.

USAGE

    pml2py infile [, outfile]

TODO

    comments, aliases
    '''
    def quote(args):
        args = iter(args)
        for arg in args:
            if '=' not in arg:
                prefix = ''
            else:
                prefix, arg = arg.split('=', 1)
                prefix += '='
                arg = arg.lstrip()
            if arg.startswith('['):
                while not arg.endswith(']'):
                    arg += ',' + args.next()
            elif arg.startswith('('):
                while not arg.endswith(')'):
                    arg += ',' + args.next()
            yield prefix + repr(arg)

    if isinstance(out, basestring):
        out = open(out, 'w')

    print >> out, '''
# automatically converted from "%s"
import pymol
from pymol import *
''' % (filename)

    handle = iter(open(filename))
    for line in handle:
        while line.endswith('\\\n'):
            line = line[:-2] + handle.next()

        a = line.split(None, 1)
        try:
            name = a[0]
            if name.startswith('/'):
                line = line.lstrip()[1:]
                raise
            name = cmd.kwhash.shortcut.get(name, name)
            func = cmd.keyword[name][0]
            assert func.__name__ != 'python_help'
        except:
            out.write(line)
            continue

        if func.__name__ == '<lambda>':
            print >> out, 'cmd.do(%s)' % (repr(line.strip()))
            continue

        if len(a) > 1:
            args = [i.strip() for i in a[1].split(',')]
        else:
            args = []

        # old syntax: set property=value
        if name in ['set', 'set_color'] and '=' in args[0]:
            args = [i.strip() for i in args[0].split('=', 1)] + args[1:]

        if name == 'python':
            for line in handle:
                if line.split() == ['python', 'end']:
                    break
                out.write(line)
            continue

        # use 'cmd' module if possible
        try:
            test = getattr(cmd, func.__name__)
            assert func == test
            module = 'cmd'
        except:
            module = func.__module__

        print >> out, '%s.%s(%s)' % (module, func.__name__, ', '.join(quote(args)))

cmd.extend('pml2py', pml2py)

# vi:expandtab:smarttab