Lala_Ghost
Lala_Ghost

Reputation: 211

__file__ in Maya not defined(#NameError)

This seems like a questions that get asked a lot but so far I did not have found a working answer.

I am working in Maya 2020 and try to make a script that need to work with some relative and absolute paths.

This is my script:

import os

print os.path.dirname(os.path.realpath(__file__)) + os.sep

this is the path to my script: Y:\New folder\my_script.py

When I run:

execfile("Y:\New folder\my_script.py")

I always get the error:

# NameError: name '__file__' is not defined #

Why does it happen?

Upvotes: 1

Views: 2680

Answers (1)

ababak
ababak

Reputation: 1793

First of all, execfile is a deprecated function in Python 3 and it is better to avoid using it. They suggest to use exec(open(fn).read()) instead (in fact, that's how it works under the hood). If you look at the suggested replacement, you'll see why the __file__ is not defined (it is not a file but a text that is interpreted as a Python code).

The usual way to import files in Maya is to place them in a directory that is added to a PYTHONPATH. There is a default Maya script directory in your user's Documents. Depending on your platform and Maya version this could be: C:\Users\<your_user>\Documents\maya\2020\scripts Another option is to add your directory to PATH. Usually this looks like this:

import sys
MY_SCRIPT_PATH = "/Some/path/with/my/scripts"
if MY_SCRIPT_PATH not in sys.path:
    sys.path.append(MY_SCRIPT_PATH

Then if your script file is named my_script.py you can import it:

import my_script

And now your __file__ variable will work as expected.

P.S. If you change your file and want to reload:

reload(my_script)

Upvotes: 2

Related Questions