0

I was working on my Auto-Rig script and noticed that the code was getting long making it hard to read and focus on one part. I was looking into importing a python file and call the functions inside the python file that was imported. Can't seem to find a way to import the file could someone help me with that.

  • 1
    write thefile.py and then in your script `import thefile`. Use functions calling `thefile.afunction()` – joaquin Mar 05 '13 at 07:52
  • the best way is invest some minutes for reading the python documentation about [inheritance, private variables and Class local-references][1], its fundamental to understand that a "object" in any oop language should have a data and behavior, [1]: https://docs.python.org/2/tutorial/classes.html – Ari Gold Sep 11 '16 at 21:08

2 Answers2

1

I recommend you create python module with your Python file and then do from MEL file:

python "import my_python_module";

string $pycommand = "my_python_module.my_function(param1, "+ $mel_string_param1 +",\"" + $mel_string_param2 + "\")";

string $result= `python $pycommand`;
emigue
  • 492
  • 3
  • 13
0

Write the functions you want to include in your module as a python file. (tip: do not start your python filename with digits).

In my example myModule.py contains:

def myFunc1():
    print 'myFunc1 is called'
    pass

def myFunc2():    
    print 'myFunc2 is called'
    return

Now save the file in a folder. My example Python file path is:

d:\projects\python\myModule.py

Now in your Maya session script editor, enter:

import sys
import os

modulePath = os.path.realpath(r'd:\projects\python\myModule.py')
moduleName = 'myModule'

if modulePath not in sys.path:
    sys.path.append(modulePath)

try:
    reload(moduleName)
except:
    exec('import %s' % moduleName)

Your module should be imported.

Now call myFunc1() from myModule:

myModule.myFunc1()

This will give the output:

myFunc1 is called

Now we call myFunc2() from myModule:

myModule.myFunc2()

This will give the output:

myFunc2 is called

If we now update our myModule.py with a new function:

def myFunc3():    
        print 'myFunc3 is called'
        return

We only need to run that same code above to reload the updated module.

Now we can try the statement:

myModule.myFunc3()

... and get this output:

myFunc3 is called

Patrick Woo
  • 61
  • 3
  • 5