1. Shawn Lipowski
  2. SL Maya Utilities

Commits

loo...@render04  committed 8c8fdb9

Starting with sendPythonToMaya which expecutes python scripts through the
command port.

  • Participants
  • Branches default

Comments (0)

Files changed (1)

File sendPythonToMaya.py

View file
  • Ignore whitespace
+#
+# sendPythonToMaya.py
+#
+# Shawn Lipowski
+# 18 May 2012
+#
+#
+# Build script for Sublime Text 2 (sendPythonToMaya.py's path is the 
+# important variable here):
+# {
+#   "cmd": ["python", "-u", "X:/path/to/sendPythonToMaya.py", "$file"]
+# }
+#
+#
+# In Maya, open a python command port with
+# mel to local host (port 2222 is typical) as follows:
+#
+#   commandPort -n "localhost:2222" -sourceType "python";
+#
+#
+# To use Python, the same host/port setup would be:
+#
+#   import maya.cmds as cmds
+#   cmds.commandPort( n='localhost:2223', sourceType='python' )
+#
+#
+# Close the port via mel:
+#
+#   commandPort -n "localhost:2222" -cl;
+#
+#
+# Close the port via python:
+#
+#   import maya.cmds as cmds
+#   cmds.commandPort( n='localhost:2223', cl=True )
+#
+
+import os
+import sys
+import socket
+
+debug = True
+
+
+def sendPythonToMaya( command, host='localhost', port=2222 ):
+
+    # connect
+    print( 'Opening socket to Maya at %s:%s' % (host, port) )
+    client = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
+    client.connect( (host, port) )
+
+    # send
+    if debug:
+        print( 'Sending command:\n\n%s' % command )
+    client.send( command )
+
+    # receive
+    data = client.recv( 1024 )
+    print( data )
+    # done
+    client.close()
+
+
+def main():
+
+    (directory, filename) = os.path.split( sys.argv[1] )
+    (basename, ext) = os.path.splitext( filename )
+
+
+    command  = 'import os\n'
+    command += 'import sys\n'
+
+    command += 'path = r"%s"\n' % directory
+
+    command += 'if not os.path.exists( path ):\n'
+    command += '    raise Exception( "Bad path: %s" % path )\n'
+
+    command += 'if path not in sys.path:\n'
+    command += '    sys.path.append( path )\n'
+
+    command += 'needsReload = False\n'
+    command += 'for n in sys.modules:\n'
+    command += '    if n == "%s":\n' % basename
+    command += '        needsReload = True\n'
+    command += '        break\n'
+
+    command += 'if needsReload:\n'
+    command += '    print( "Reloading %s." )\n' % basename
+    command += '    import %s\n' % basename
+    command += '    reload( %s )\n' % basename
+    command += 'else:\n'
+    command += '    print( "Importing %s." )\n' % basename
+    command += '    import %s\n' % basename
+
+
+    print( 'Sending load command for script: %s' % filename )
+    sendPythonToMaya( command )
+
+
+if __name__ == '__main__':
+    main()