1
votes

i want to pass multiline python command as a string variable to maya commandPort in following format. But looks like it errors out , when executed in maya through port. It erros as Unterminated string. //

In maya , i have opened a command port as

import maya.cmds as cmds cmds.commandPort(name=":6001")

Here is the command i execute in nuke to pass to maya command port , when supplied multiline command in form code1 variable it doesnt work, but when we supply command in code2 , it works. Is there a way to pass long multiline command string without using \n or ; in the same line ?

### multiline string like below doesn't work, errors as unterminated sring

code1="""
cmds.polySphere()
"""

### if supplied in below format ,it works
code2="cmds.polySphere()" 

import socket
host = 'localhost'
port = 6001

try:
   # Connect to Maya Command Port
   maya = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   maya.connect( (host,port) )
   # Send Command Through Socket --> Can Only Send MEL Commands
   message = 'python("{}")'.format(code1)
   print message
   maya.send(message)

except:
   raise Exception, 'Connection Failed To : %s:%s' % (host, port)

finally:
   # Close Socket Connection
   maya.close()
2

2 Answers

0
votes

It executes properly if code1 is formatted in a single line:

code1 = """cmds.polySphere()"""

And you can use a ; (semi-colon) to run multiple commands:

code1 = """cmds.polySphere();cmds.polyCube()"""

I personally find it more readable to format it like this using \n (new line):

code1 = ("cmds.polySphere()\\n"
         "if 2 > 1:\\n"
         "    cmds.polyCube()")

The \n needs to be escaped with an extra \ because it's being placed in another string in your message variable.

You can also use replace() to avoid escaping altogether:

code1 = ("cmds.polySphere()\n"
         "if 2 > 1:\n"
         "    cmds.polyCube()").replace("\n", "\\n")
0
votes

Thanks for the reply :)

I also found a way to write multiline the normal way without having to add \n or ; , and automate it in the next step

code1_multiLine="""
                 for i in range(5):
                     print i
                """
code1_singleLine=code1_multiLine.replace("\n",r"\n")   

##then pass , this to the command port , in the top most example.

message = 'python("{}")'.format(code1_singleLine)

Thanks,