1

I need to send a script to Maya from an external software written in Maya. I tried to do this with a small example:

import socket
import time
from os.path import abspath

ADDR=('127.0.0.1',666)


def execute_file(fileFullPath):
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(ADDR)
    command = "execfile('%s')" % (fileFullPath)
    client.send(command)
    data = client.recv(1024)
    print data
    client.close()
    time.sleep(.1)
    return data

if __name__ == '__main__':
    py_file = 'hello_world.py'
    py_file = abspath(py_file)
    execute_file(py_file)

In hello_world.py I have:

print 'hello world'

Hovewer, when I execute this, 'hello world' is printed twice in Maya.

Another thing I tried is:

if __name__ == '__main__':
    print 'hello world'

But then it doesn't execute at all.

Finally, I have also tried with putting the print in a method and the calling it like this:

command = "execfile('%s')" % (fileFullPath)
client.send(command)
data = client.recv(1024)
client.send("exec('start()')")

But then I get an name 'start' is not defined error

Does someone know why this happens, or has at least an idea on how I could avoid this?

Thanks in advance for your help.

Purrrple
  • 133
  • 6

2 Answers2

1

You can get the same results in a couple of more predictable ways.

Maya already provides a TCP-based [command port], which will execute commands coming in over the network; you don't need to write your own server. You could also use a more robust remote solution like [RPYC] or [ZeroMQ].

Were you running the server at ( '127.0.0.1', 666 ) inside your Maya? That would explain the duplicate printouts.

Related: is an example of how to set up a simple server inside of Maya to respond to commands coming over HTTP.

You generally don't want to use execfile(), if this code will be visible to anybody other than yourself: it's the biggest security hole imaginable!

user3666197
  • 1
  • 6
  • 50
  • 92
theodox
  • 12,028
  • 3
  • 23
  • 36
  • Thanks for your answer. It looks great. Now I am home with a flu, but as soon I can I will have a closer look and see if what you propose works for me. Anyway, i will let you (+the community) know. – Purrrple Dec 08 '16 at 11:15
0

I found a solution!

As suggested in this answer, I just had to add import maya.cmds as mc\n to the command to execute:

command = "import maya.cmds as mc\n import maya.cmds as mc\nexecfile('%s')" % (fileFullPath)

Now I would love to know why this piece of code prevents Maya of executing the script twice.

Community
  • 1
  • 1
Purrrple
  • 133
  • 6