maya python 从另一个 py 文件调用函数

maya python call function from another py file

我有一个 python 脚本保存到文件中。

test1.py

import maya.cmds as cmds
import sys

def process():
    print 'working'

我需要 运行 这个脚本中的函数在另一个 python 脚本中,在 Maya 中。我有:

import sys
sys.path.append('J:\scripts\src\maya')

from test1 import process

test1.process()

但它给了我:

from test1 import process
# Error: ImportError: file <maya console> line 4: cannot import name process # 

我做错了什么?

('import test1'没有错误,所以路径是正确的)。

解决方案:

重新加载您的 test1 模块,我的猜测是您在没有 process 方法的情况下创建并导入了 test1。要有效地重新加载模块,您不能只re-import它,您必须使用重新加载。

reload(test1)
from test1 import process

其他观察:

使用路径时使用原始字符串:

在您的路径字符串前添加 rsys.path.append(r'J:\scripts\src\maya')

Python Doc

The backslash () character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character. String literals may optionally be prefixed with a letter 'r' or 'R'; such strings are called raw strings and use different rules for interpreting backslash escape sequences.

检查导入模块的方式:

您写的是无效的:

from test1 import process
test1.process()

但你可以有两种选择:

import test1 
test1.process()

或:

from test1 import process
process()

对于sum-up,这些是导入模块或包的方法:

>>> import test_imports
>>> from test_imports import top_package
>>> from test_imports import top_module
test_imports.top_module
>>> from test_imports.top_package import sub_module
test_imports.top_package.sub_module

假设您具有以下层次结构:

J:\scripts\src\maya # <-- you are here
.
`-- test_imports
    |-- __init__.py
    |-- top_package
    |   |-- __init__.py
    |   |-- sub_package
    |   |   |-- __init__.py
    |   |   `-- other_module.py
    |   |-- sub_module.py
    `-- top_module.py

学分转到 Sam & Max blog(法语)

首先需要在系统路径中添加脚本所在路径

如果您将其作为 python 包制作,请不要忘记添加 包目录中的 __init__.py 文件。

你可以执行下面的代码。

import sys
path = r'J:\scripts\src\maya'
if path not in sys.path:
    sys.path.append(path)

import test1
test1.process()