I have a python script saved to file.
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. 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).
Reload your test1
module, my guess is that you created and imported test1
without the process
method inside. 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')
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.
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)
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.
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.