Get myself path with maya python

I want to know myself path with maya python like “file”.
Following code, getScriptPath() will do this.
This code saved to /document/maya/2020/script/working/ and called from shelf.

from PySide2 import QtCore
from PySide2 import QtWidgets
from shiboken2 import wrapInstance

import os
import sys

import maya.OpenMayaUI as omui

def maya_main_window():
Return the Maya main window widget as a Python object
main_window_ptr = omui.MQtUtil.mainWindow()
return wrapInstance(long(main_window_ptr), QtWidgets.QWidget)

class TestDialog(QtWidgets.QDialog):

def __init__(self, parent=maya_main_window()):
    super(TestDialog, self).__init__(parent)

    self.setWindowTitle("Test Dialog")

    # Remove the ? from the dialog on Windows
    self.setWindowFlags(self.windowFlags() ^ QtCore.Qt.WindowContextHelpButtonHint)
def create_testbtn(self):
    main_lo = QtWidgets.QVBoxLayout(self)
    test_button = QtWidgets.QPushButton("Test it")
def getScriptPath(self):
    print os.path.abspath(__file__)
if __name__ == "__main__":
    d = TestDialog()

I tried…

  • os.path.abspath(file)
  • os.path.dirname(sys.argv[0])
  • os.getcwd()

These seems to returned maya’s path.

This is my first post, so if there’s anything I’m missing, I’d appreciate it if you could let me know.
Thanks to your help.

Not sure exactly how you are running this script.

  • I saved this script to %HOME%/Documents/maya/2020/scripts as
  • I imported the module and TestDialog().getScriptPath() seems to work just fine.

Are you familiar with how Python modules and packages works? If not, check this link:
Python Modules and Packages – An Introduction – Real Python

It’s a good start.

If you are familiar with packages and modules and how they are imported. You might want to check how your PYTHONPATH and MAYA_SCRIPT_PATH are constructed.

For reference, __file__ is only created when the package/module is imported.

Thanks to your advice, my problem is solved!

1 Like

Just chiming in:

I’ve noticed sometimes when sending modules to Maya via a PyCharm setup with MayaCharm, things like __file__ return nulls.

Guessing here that MayaCharm is sending a block of text and executing it, not an import process.

Either way, Writing a little header file that imports what you are working on and pointing the project config at that is a good practice if using that sort of workflow.

__file__ is not guaranteed to exist and won’t point to anything in a variety of circumstances.

Much better to use the inspect module.


@ross-g if you’re not in the scope of an imported module, wont __file__ just return the same thing? If not, what does it return?

__file__ is an optional attribute set on a module, as part of the import process.
Not all modules come from files, and as such would struggle with using the __file__ attribute.

However, any .py file that you import, will generally speaking have a __file__ attribute. Unless you’ve done something clever to the import system.