Skip to content

Instantly share code, notes, and snippets.

@utatsuya
Last active October 9, 2016 20:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utatsuya/e4d60228b2372662b2fc to your computer and use it in GitHub Desktop.
Save utatsuya/e4d60228b2372662b2fc to your computer and use it in GitHub Desktop.
"---------------------------------------------------------------------------
" SendToMayaについて
"
" vim から maya にスクリプトを投げることができます。ユーザー定義の _vimrc
" などにコピペしてご使用ください。
"
" できること
" ビジュアルモードで選択した行だけ実行する。
" エラーを受け取って vim で表示する。(日本語対応)
"
" vim から python を実行し、maya へのソケット通信を行っています。
" 実行前に Maya 側で commandPort コマンドによって接続可能な状態になっている
" 必要があります。
"
" TODO:
" ・選択行の実行はできるが、選択文字列の実行はできていない。
" ・エラーメッセージは受け取れるが、通常のprintなどのログは受け取れていな
" い。
"---------------------------------------------------------------------------
" 設定
let g:SendToMaya_Host = "localhost"
let g:SendToMaya_Port = 8888
"---------------------------------------------------------------------------
:function! SendToMaya(start_line, end_line)
let g:SendToMaya_startLine = a:start_line
let g:SendToMaya_endLine = a:end_line
:python << EOP
import os
import codecs
import socket
import tempfile
import vim
host = vim.eval ('g:SendToMaya_Host' )
port = int(vim.eval ('g:SendToMaya_Port' ))
# TODO: 行番号だけではなく何文字目かも指定できるようにする
vStart = (int(vim.eval ('g:SendToMaya_startLine' )), 0)
vEnd = (int(vim.eval ('g:SendToMaya_endLine' )), 0)
# 一時ファイル生成
scriptfile = tempfile.mkstemp()
errorfile = tempfile.mkstemp()
scriptcode = ["# -*- coding:utf-8 -*-"]
for line in vim.current.buffer [vStart [0] - 1 : vEnd [0]]:
scriptcode.append(line)
scriptcode = "\n".join(scriptcode)
scriptcode = scriptcode.decode('cp932').encode('utf-8')
f = os.fdopen(scriptfile[0], "w")
f.write(scriptcode)
f.close()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
# maya に送る(Mayaで実行される)スクリプト
code = """
import traceback
try:
print "// vim", "-"*40
execfile(r"SCRIPTFILE")
except:
f = open(r"ERRORFILE","w")
traceback.print_exc(file=f)
f.close()
raise
finally:
os.remove(r"SCRIPTFILE")
"""
code = code.replace("SCRIPTFILE", scriptfile[1])
code = code.replace("ERRORFILE", errorfile[1])
sock.send(code)
# エラーメッセージの処理
try:
s = sock.recv(4096)
if not s.startswith("None"):
print s.decode("utf-8")
if os.path.exists(errorfile[1]):
f = os.fdopen(errorfile[0], "r")
data = f.read()
f.close()
os.remove(errorfile[1])
print data
# Mayaからエラーメッセージを奪ってしまったので送り返す
# Error message
msg = [repr(w) for w in s.decode("utf-8").split("\n") if len(w) > 3]
msg = "\n".join(msg)
sock.send("print " + msg)
s = sock.recv(4096)
# traceback
msg = [w for w in data.split("\n") if len(w) > 3]
msg = "\n".join(msg)
sock.send("print '''" + msg + "'''")
s = sock.recv(4096)
finally:
sock.close()
EOP
:endfunction
:command! -range=% Toma :call SendToMaya(<line1>,<line2>)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment