[英]maya python call function from another py file
I have a python script saved to file. 我有一个python脚本保存到文件。
test1.py test1.py
import maya.cmds as cmds
import sys
def process():
print 'working'
I need to run the function from this script inside another python script, inside maya. 我需要在Maya内的另一个python脚本中从此脚本运行该函数。 I have: 我有:
import sys
sys.path.append('J:\scripts\src\maya')
from test1 import process
test1.process()
but it gives me: 但这给了我:
from test1 import process
# Error: ImportError: file <maya console> line 4: cannot import name process #
What am I doing wrong here? 我在这里做错了什么?
('import test1' gives no error, so the path is correct). (“ import test1”没有错误,因此路径正确)。
Reload your test1
module, my guess is that you created and imported test1
without the process
method inside. 重新加载您的test1
模块,我猜是您创建并导入了test1
但内部没有process
方法。 To effectively reload a module, you can't just re-import it, you have to use the reload. 为了有效地重新加载模块,您不能只重新导入它,而必须使用重新加载。
reload(test1)
from test1 import process
Use raw string when using paths: 使用路径时使用原始字符串:
Add r
before your path string: sys.path.append(r'J:\\scripts\\src\\maya')
在路径字符串前添加r
: sys.path.append(r'J:\\scripts\\src\\maya')
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'; 字符串文字可以选择以字母“ r”或“ R”为前缀; such strings are called raw strings and use different rules for interpreting backslash escape sequences. 这样的字符串称为原始字符串,并使用不同的规则来解释反斜杠转义序列。
Check the way you import your modules: 检查导入模块的方式:
You wrote, which is not valid: 您写的,这是无效的:
from test1 import process
test1.process()
But you can have either way: 但是您可以选择以下两种方式之一:
import test1
test1.process()
or: 要么:
from test1 import process
process()
To sum-up these are the ways to import a module or package: 总结一下,这些是导入模块或包的方法:
>>> 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
assuming you have the following hierarchy: 假设您具有以下层次结构:
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
Credits goes to Sam & Max blog (French) 致谢Sam&Max博客 (法语)
First you need to add the script location path in system path. 首先,您需要在系统路径中添加脚本位置路径。
and if you are making this as a python package than do not forget to add a __init__.py
file in the package directory. 并且如果您将其作为python软件包制作,请不要忘记在软件包目录中添加__init__.py
文件。
Than you can execute following code. 比您可以执行以下代码。
import sys
path = r'J:\scripts\src\maya'
if path not in sys.path:
sys.path.append(path)
import test1
test1.process()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.