# -----------------------------------------------------------------------------
# Example program that sends commands to Chimera.
#
class Chimera_IO:

    def __init__(self):

        args = ['chimera', '--start', 'ReadStdin']
        self.prog = run_program(args)
        
    def send_command(self, command):

        p = self.prog
        p.stdin.write(command + '\n')
        p.stdin.flush()

        # Collect output.
        lines = []
        while True:
            line = p.stdout.readline()
            if line == '' or line == 'END\n':
                break
            lines.append(line)
        output = ''.join(lines)

        return output
    
# -----------------------------------------------------------------------------
#
def run_program(args):

    # Hide console window on Windows.
    import sys
    if sys.platform == 'win32':
        from subprocess import STARTUPINFO, STARTF_USESHOWWINDOW
        spinfo = STARTUPINFO()
        spinfo.dwFlags |= STARTF_USESHOWWINDOW
    else:
        spinfo = None

    from subprocess import Popen, PIPE
    try:
        p = Popen(args, stdin = PIPE, stdout = PIPE, startupinfo = spinfo)
    except:
        print 'Starting "%s" failed.\n' % ' '.join(args)
        return None

    return p

# -----------------------------------------------------------------------------
#
c = Chimera_IO()
print c.send_command('open 0 /tmp/sfv.mrc')
print c.send_command('volume #0 level 2500 color tan')
