Maya <=> pycharm IDE (support to get maya track back and error line)






















































































































send selected lines to maya

save following script as “send_to_maya.py”
pycharm external parameters setting >

[your path\send_to_maya.py] $FilePath$ $SelectionStartLine$ $SelectionEndLine$


#PyCharm python script by Yann Schmidt, https://github.com/justinfx/MayaSublime; Edited by Dontnoun(for trace back, error line number)
#Version: 1.0       Send whole file to Maya via commandPort and get trackback to pycharm (track back does not work for multi-process-thread function)
#copy below 5 lines to your ..\Users\[user name]\Documents\maya\[maya_version]\scripts\userSetup.py(remove first '#' symbol for each line)
#import maya.cmds as cmds
#try : cmds.commandPort(n='127.0.0.1:7001' , bs=128000, stp = 'mel')
#except : pass
#try : cmds.commandPort(n='127.0.0.1:7002' , bs=128000, stp = 'python')
#except : pass

import sys, os, textwrap, time
from telnetlib import Telnet

class SendToMaya(object):
    PY_CMD_TEMPLATE = textwrap.dedent('''
        import traceback
        import __main__
        namespace = __main__.__dict__.get('_pycharm_SendToMaya_command')
        if not namespace:
            namespace = __main__.__dict__.copy()
            __main__.__dict__['_pycharm_SendToMaya_command'] = namespace
        namespace['__file__'] = {2!r}
        try : {0}({1!r}, namespace, namespace)
        except : traceback.print_exc()    ''')

    def __init__(self):
        self.maya_log_pth = os.path.dirname(os.path.abspath(__file__)).replace('\\','/') + '/'
        self.execType = 'execfile'
        self.fileType = 'python'
        #---------------------------------------------------
        slins_buf_py_pth = self.maya_log_pth + 'slins_buff.py'
        
        with open(str(sys.argv[1]), 'r') as slin_id : 
            slines = slin_id.readlines()[ int(sys.argv[2])-1: int(sys.argv[3]) ]

        with open(slins_buf_py_pth, 'w+') as wslns_id :
            for ww in slines : wslns_id.write(ww)

        self.file = slins_buf_py_pth        #str(sys.argv[1])
        #----------------------------------------------------
        self.sep = None
        self.is_python()
        self._settings = dict()
        self.init_settings()

    def init_settings(self):
        maya_hostname = "127.0.0.1"     #-------------!!!
        python_command_port = 7002      #-------------!!!
        mel_command_port = 7001         #-------------!!!
        self._settings['host'] = maya_hostname

        if self.fileType == 'python':
            self._settings['port'] = python_command_port
            self.sep = '
'
        else:
            self._settings['port'] = mel_command_port
            self.sep = '\r'

    def is_python(self):
        if sys.argv[1].endswith('.py'):     self.fileType = 'python'
        elif sys.argv[1].endswith('.mel'):  self.fileType = 'mel'
        else:                               self.fileType = None

    def run(self):
        maya_log_pth = self.maya_log_pth + 'pycharmya.log'
        with open(maya_log_pth, 'w+') as empty_id : empty_id.write('')
        buff_pym_pth = self.maya_log_pth + 'maya_2pycharm_buf.fer'

        if self.fileType is None:
            print("No Maya-Recognized language found.")
            return
        #----------------------#----------------------VVV   to get maya track back and debug line
        crnt_py_line_lst = []
        with open(self.file, 'r')  as crnt_fid :
            for cc in  crnt_fid.readlines() :
                crnt_py_line_lst.append(cc.strip('
'))

        if self.fileType == 'python' :
            pre_cmd = "import maya.cmds as cmds; mlg = '" + self.maya_log_pth + "pycharmya.log'; cmds.scriptEditorInfo(hfn = mlg, wh=1);print 'MaYa Track Back :\
---------------'"
            pst_cmd = "import maya.cmds as cmds; cmds.scriptEditorInfo(hfn = mlg, wh=0)"
            mrk_cmd = "with open('" + self.maya_log_pth + "maya_2pycharm_buf.fer', 'w+')  as bfd : bfd.write('xxx')"
            with open(buff_pym_pth, 'w+')  as buff_fid :
                buff_fid.write(pre_cmd + '
')
                buff_fid.write('import sys, traceback
try :
')
                for bb in crnt_py_line_lst :   buff_fid.write('    ' + bb + '
')
                buff_fid.write('except Exception as eRr : 
    for x in traceback.extract_tb(sys.exc_info()[2]):print type(eRr), eRr.args[0], "\
", "Error on line:", x[1]-3, "--> ", x[3], "\
"
')
                buff_fid.write(pst_cmd + '
' + mrk_cmd + '
')

        else : buff_pym_pth = self.file     #-----for mel
        #----------------------#----------------------AAA   to get maya track back and debug line
        snips = []
        if self.fileType == 'python':       snips.append(buff_pym_pth)
        else:                               snips.append('rehash; source "{0}";'.format(buff_pym_pth))

        mCmd = str(self.sep.join(snips))
        if not mCmd :                       return
        if self.fileType == 'python':       mCmd = self.PY_CMD_TEMPLATE.format(self.execType, mCmd, buff_pym_pth)
        if self.fileType == 'mel':          mCmd = mCmd.replace('\\', '/')

        tnt = None
        try:
            tnt = Telnet(   self._settings.get('host'),    int(self._settings.get('port')),     timeout=3   )
            tnt.write(mCmd.encode(encoding='UTF-8'))
            #----------------------#----------------------#
            if self.fileType == 'python' :  self.get_maya_trackback()      #-------------!!! track back only for python not mel
            #----------------------#----------------------#
        except Exception:
            err = str( sys.exc_info()[1] )
            print("Failed to communicate with Maya (%(host)s:%(port)s)):
%(err)s" % locals())
            raise
        else: time.sleep(.1)
        finally:
            if tnt is not None: tnt.close()

    def get_maya_trackback(self):
        maya_log_pth = self.maya_log_pth + 'pycharmya.log'
        buff_pym_pth = self.maya_log_pth + 'maya_2pycharm_buf.fer'
        while 1 :
            time.sleep(0.3)             #-------------!!!
            #-------------------
            with open(buff_pym_pth, 'r') as buf_id :
                mrk_str = buf_id.readline().strip('
')
            #-------------------
            with open(maya_log_pth, 'r') as crash_id :
                crash_str = crash_id.readline().strip('
')
            if crash_str is not None and crash_str != 'MaYa Track Back :' :
                print 'Fatal SyntaxError: Can not run in MaYa!'
                break
            #-------------------
            if mrk_str == 'xxx':        #-------------!!!
                with open(maya_log_pth,'r') as mlog_id :
                    for ii in mlog_id.readlines():
                        print ii.strip('
')
                break


snd = SendToMaya()
snd.run()

#-----------------------------------------------old version
when I move maya python IDE to Pycharm, got a problem, pycharm can not get track back and error info from maya,
searched in google ,found something :
http://tech-artists.org/forum/showth...5280-MayaCharm
unfortunately it does not work for my computer…
maybe difference maya, pycharm version or os platform caused problem

then found a script from this page,
http://www.yannschmidt.com/blog/crea...mmand-pycharm/
its pretty good, I edited the script to get maya track back and error line info
it is a simple python script, should work in many versions of maya and pycharm and os
edited script is here:
Code:
#PyCharm python script by Yann Schmidt, https://github.com/justinfx/MayaSublime; Edited by Dontnoun(for track back, error line number)
#Version: 1.0 Send whole file to Maya via commandPort and get trackback to pycharm (track back does not work for multi-process-thread function)
#copy below 5 lines to your …\Users[user name]\Documents\maya[maya_version]\scripts\userSetup.py(remove first ‘#’ symbol for each line)
#import maya.cmds as cmds
#try : cmds.commandPort(n=‘127.0.0.1:7001’ , bs=128000, stp = ‘mel’)
#except : pass
#try : cmds.commandPort(n=‘127.0.0.1:7002’ , bs=128000, stp = ‘python’)
#except : pass

import sys, os, textwrap, time
from telnetlib import Telnet

class SendToMaya(object):
PY_CMD_TEMPLATE = textwrap.dedent(’’’
import traceback
import main
namespace = main.dict.get(’_pycharm_SendToMaya_command’)
if not namespace:
namespace = main.dict.copy()
main.dict[’_pycharm_SendToMaya_command’] = namespace
namespace[‘file’] = {2!r}
try : {0}({1!r}, namespace, namespace)
except : traceback.print_exc() ‘’’)

def __init__(self):
    self.maya_log_pth = os.path.dirname(os.path.abspath(__file__)).replace('\\','/') + '/'
    self.execType = 'execfile'
    self.fileType = 'python'
    self.file = str(sys.argv[1])
    self.sep = None

    self.is_python()
    self._settings = dict()
    self.init_settings()

def init_settings(self):
    maya_hostname = "127.0.0.1"     #-------------!!!
    python_command_port = 7002      #-------------!!!
    mel_command_port = 7001         #-------------!!!
    self._settings['host'] = maya_hostname

    if self.fileType == 'python':
        self._settings['port'] = python_command_port
        self.sep = '


else:
self._settings[‘port’] = mel_command_port
self.sep = ‘\r’

def is_python(self):
    if sys.argv[1].endswith('.py'):     self.fileType = 'python'
    elif sys.argv[1].endswith('.mel'):  self.fileType = 'mel'
    else:                               self.fileType = None

def run(self):
    maya_log_pth = self.maya_log_pth + 'pycharmya.log'
    with open(maya_log_pth, 'w+') as empty_id : empty_id.write('')
    buff_pym_pth = self.maya_log_pth + 'maya_2pycharm_buf.fer'

    if self.fileType is None:
        print("No Maya-Recognized language found.")
        return
    #----------------------#----------------------VVV   to get maya track back and debug line
    crnt_py_line_lst = []
    with open(self.file, 'r')  as crnt_fid :
        for cc in  crnt_fid.readlines() :
            crnt_py_line_lst.append(cc.strip('

'))

    if self.fileType == 'python' :
        pre_cmd = "import maya.cmds as cmds; mlg = '" + self.maya_log_pth + "pycharmya.log'; cmds.scriptEditorInfo(hfn = mlg, wh=1);print 'MaYa Track Back :\

---------------’"
pst_cmd = “import maya.cmds as cmds; cmds.scriptEditorInfo(hfn = mlg, wh=0)”
mrk_cmd = “with open(’” + self.maya_log_pth + “maya_2pycharm_buf.fer’, ‘w+’) as bfd : bfd.write(‘xxx’)”
with open(buff_pym_pth, ‘w+’) as buff_fid :
buff_fid.write(pre_cmd + ’
')
buff_fid.write('import sys, traceback
try :
‘)
for bb in crnt_py_line_lst : buff_fid.write(’ ’ + bb + ’
')
buff_fid.write('except Exception as eRr :
for x in traceback.extract_tb(sys.exc_info()[2]):print type(eRr), eRr.args[0], "
", “Error on line:”, x[1]-3, "–> ", x[3], "
"
')
buff_fid.write(pst_cmd + ’
’ + mrk_cmd + ’
')

    else : buff_pym_pth = self.file     #-----for mel
    #----------------------#----------------------AAA   to get maya track back and debug line
    snips = []
    if self.fileType == 'python':       snips.append(buff_pym_pth)
    else:                               snips.append('rehash; source "{0}";'.format(buff_pym_pth))

    mCmd = str(self.sep.join(snips))
    if not mCmd :                       return
    if self.fileType == 'python':       mCmd = self.PY_CMD_TEMPLATE.format(self.execType, mCmd, buff_pym_pth)
    if self.fileType == 'mel':          mCmd = mCmd.replace('\\', '/')

    tnt = None
    try:
        tnt = Telnet(   self._settings.get('host'),    int(self._settings.get('port')),     timeout=3   )
        tnt.write(mCmd.encode(encoding='UTF-8'))
        #----------------------#----------------------#
        if self.fileType == 'python' :  self.get_maya_trackback()      #-------------!!! track back only for python not mel
        #----------------------#----------------------#
    except Exception:
        err = str( sys.exc_info()[1] )
        print("Failed to communicate with Maya (%(host)s:%(port)s)):

%(err)s" % locals())
raise
else: time.sleep(.1)
finally:
if tnt is not None:
tnt.close()

def get_maya_trackback(self):
    maya_log_pth = self.maya_log_pth + 'pycharmya.log'
    buff_pym_pth = self.maya_log_pth + 'maya_2pycharm_buf.fer'
    while 1 :
        time.sleep(0.2)             #-------------!!!
        #-------------------
        with open(buff_pym_pth, 'r') as buf_id :
            mrk_str = buf_id.readline().strip('

‘)
#-------------------
with open(maya_log_pth, ‘r’) as crash_id :
crash_str = crash_id.readline().strip(’
‘)
if crash_str is not None and crash_str != ‘MaYa Track Back :’ :
print ‘Fatal SyntaxError: Can not run in MaYa!’
break
#-------------------
if mrk_str == ‘xxx’: #-------------!!!
with open(maya_log_pth,‘r’) as mlog_id :
for ii in mlog_id.readlines():
print ii.strip(’
')
break

snd = SendToMaya()
snd.run()