[Python][Maya] Open commandPort for Mayapy?

Hi everybody
I would love to keep mayapy running in background, and recieve data to execute code continuous. But look like we can’t use commandPort since the UI hadn’t load yet

Is there anything else i can do about it?
Thanks :):

Below is a very crude server you can run in maya.standalone that will accept commands over HTTP connections. You can run maya from the address bar of your browser if that floats your boat.

To send a command, send an HTTP get by typing into your browser bar:


#basic, no args command
http://<your-ip-here>:8000/?command=cmds.ls

# command with arguments (note: args are always in a list, even if you have only 1)
http://<your-ip-here>:8000/?command=cmds.select&args=["persp"] 

#command with keyword
 http://<your-ip-here>:8000/?command=cmds.ls&kwargs{"type":"transform"}

#command with arg and keywords
 http://<your-ip-here>:8000/?command=cmds.ls&args=["persp", "perspShape1"]&kwargs{"type":"transform"}

If you’re sending a command from script not the browser bar, you’ll need to encode the query string like this:


import json
import urrlib
def encode_command(cmd, *args, **kwargs):
    result = {'command': str(cmd)}
    if args:
        result['args'] = json.dumps(args)
    if kwargs:
        result['kwargs'] = json.dumps(kwargs)
    return urllib.urlencode(result)

You’d probably want to extend it by importing modules that exposed commands with nice clean interfaces for easy remote control; you can run maya.cmds remotely but it’s cumbersome.


'''
simple WSGI server to control Maya from an HTTP connection
'''

import sys
import json
import urlparse
import maya.standalone
maya.standalone.initialize()
import maya.cmds as cmds
import logging
import socket

import traceback
from wsgiref.simple_server import make_server


def handle_command  (environ, response):
        '''
        look for a query string with 'command' in it; eval the string and
        execute. Args and KWargs can be passed as json objects. The command will
        be evaluated in the global namespace.
        
        http://192.168.1.105:8000/?command=cmds.ls
        http://192.168.1.105:8000/?command=cmds.ls&kwargs{"type":"transform"}


        If the query string command is 'shutdown', quit maya.standalone
        '''
        


        if not environ.get('QUERY_STRING'):
            status = '404 Not Found'
            headers = [('Content-type', 'text/plain')]
            response(status, headers)
            return ["You must supply a command as a query string"]

        query = urlparse.parse_qs( environ['QUERY_STRING'] )
        status = '200 OK'
        headers = [('Content-type', 'text/plain')]
        response(status, headers)

        cmds_string = query.get('command')
        if not cmds_string:
            return ['No recognized command']
        
        cmd_name = "-"
        args = "-"
        kwargs = "-"
                        
        try:
            cmd_name = cmds_string[0]
            args = query.get('args') or []
            if args: 
                args = json.loads(args[0])

            kwargs = query.get('kwargs') or {}
            if kwargs: 
                # convert json dictionary to a string rather than unicode keyed dict
                unicode_kwargs = json.loads(kwargs[0])
                kwargs = dict( ( str(k), v) for k, v in unicode_kwargs.items())

            cmd_proc = eval(cmd_name)
            if cmd_name == 'shutdown':
                try:
                    return ['SERVER SHUTTING DOWN']
                finally:
                    cmd_proc()
            
            result = cmd_proc(*args, **kwargs)
            return [json.dumps(result)]
        
        except:
            return ["cmd_name:	", cmd_name, "
args:	", str(args) or "-", "
kwargs:	", str(kwargs)or "-", "
--------
", traceback.format_exc()]    
        
        

def create_server(port=None):
    '''
    create a server instance
    '''
    port = port or 8000
    address = socket.gethostbyname(socket.gethostname())
    server = make_server(address, port, handle_command)    
    return server, address, port

        
if __name__ == '__main__':
    server_instance, address, port = create_server()       

    # defined here so we don't need a global server reference...    
    def shutdown():
        print  "*" * 80
        print "shutting down"
        print "*" * 80
        cmds.quit(force=True)
        server_instance.shutdown()
        raise sys.exit(0)
        
    print "=" * 80
    print ("starting server on %s:%s" % (address,port)).center(80)
    print "=" * 80

    server_instance.serve_forever()
 

To Theodox : i love you man, i will test it and response ASAP :wow:

Hi Theodox
Everything works fine, but look like it can’t catch args and kwargs at all. I will do something about it
Thank a lots, you make my day :smiley:

check the formatting of the inputs - the ‘args’ should always be a JSON list and ‘kwargs’ a JSON dictionary

/?command=cmds.spaceLocator&kwargs={“name”:“test”}
This is work for me :smiley:

Cleaned up version with docs is up on github: