Search code examples
pythonmayaexecfile

Python script runs twice in Autodesk Maya when sent with execfile


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.


Solution

  • 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!