anti anti - 6 months ago 51
Python Question

maya python call function from another py file

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).

Answer

Solution:

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

Other observations:

Use raw string when using paths:

Add r before your path string: sys.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.

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)