anti anti - 4 months ago 37x
Python Question

maya python call function from another py file

I have a python script saved to file.

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

from test1 import 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.

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

But you can have either way:

import test1 


from test1 import 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
>>> from test_imports.top_package import sub_module

assuming you have the following hierarchy:

J:\scripts\src\maya # <-- you are here
`-- test_imports
    |-- top_package
    |   |--
    |   |-- sub_package
    |   |   |--
    |   |   `--
    |   |--

Credits goes to Sam & Max blog (French)