Python 脚本在与 execfile 一起发送时在 Autodesk Maya 中运行两次

Python script runs twice in Autodesk Maya when sent with execfile

我需要从用 Maya 编写的外部软件向 Maya 发送脚本。我试着用一个小例子来做到这一点:

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)

在 hello_world.py 我有:

print 'hello world'

但是,当我执行此操作时,'hello world' 在 Maya 中打印了两次。

我尝试的另一件事是:

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

但是它根本不执行。

最后,我也试过将打印放在一个方法中并像这样调用它:

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

但是我得到一个 name 'start' is not defined 错误

有人知道为什么会发生这种情况,或者至少知道如何避免这种情况吗?

在此先感谢您的帮助。

我找到了解决办法!

正如 this 回答中所建议的,我只需要将 import maya.cmds as mc\n 添加到要执行的命令中:

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

现在我很想知道为什么这段代码会阻止 Maya 执行脚本两次。

您可以通过几种更可预测的方式获得相同的结果。

Maya 已经提供了基于 TCP 的 [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]

您 运行 ( '127.0.0.1', 666 ) 的服务器是在您的 Maya 中 吗?这可以解释重复的打印输出。

相关内容:an example 如何在 Maya 中设置一个简单的服务器来响应来自 通过 HTTP 的命令。

您通常不想使用 execfile(),如果除了您自己以外的任何人都可以看到此代码:这是 最大的安全措施空洞可以想象!