- Pythonのバージョンを表示
>>> import sys
>>> print sys.version
2.6.7 (r267:88850, Jan 13 2012, 17:06:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)]
- デフォールトエンコーディングを調べる
>>> import sys
>>> sys.getfilesystemencoding()
'utf-8'
- OS のコマンドを実行
Linux 上で date コマンドを実行。
>>> import os
>>> os.system('date')
2008年 9月 30日 火曜日 18:40:20 JST
- Photoshopを起動
>>> import os
>>> os.system('"C:\\Program Files\\Adobe\\Adobe Photoshop CC 2015\\Photoshop.exe"')
- 環境変数の値を得る
>>> import os
>>> os.environ.get('MAYA_APP_DIR')
- 現在のディレクトリを調べる
現在、作業中のディレクトリ(フォルダ)を調べる。
>>> import os
>>> os.getcwd()
'/home/abe/maya/projects/default/'
- 現在のディレクトリを変更
/home/someone ディレクトリ(フォルダ)に移動する。
>>> import os
>>> os.chdir('/home/someone/')
- パス名の操作
>>> import os
>>> path = '/aaa/bbb/ccc.ddd'
拡張子の取り出し
>>> os.path.splitext(path)
('/aaa/bbb/ccc', '.ddd')
ファイル名の取り出し
>>> os.path.basename(path)
'ccc.ddd'
ディレクトリ名の取り出し
>>> os.path.dirname(path)
'/aaa/bbb'
ディレクトリ名とファイル名を分ける
>>> os.path.split(path)
('/aaa/bbb', 'ccc.ddd')
- ファイルのコピー
ファイル tmp1 を tmp2 にコピー。
>>> import shutil
>>> shutil.copyfile('tmp', 'tmp2')
- ファイルの移動
ファイル名 tmp1 を tmp2 に変更。
tmp2 がディレクトリなら tmp1 は tmp2 の中に移動。
>>> import shutil
>>> shutil.move('tmp', 'tmp2')
- ファイルからの読み込み
一行ずつ読み込み。
f = open('test.txt', 'r')
for line in f:
print line
f.close()
または
with open('test.txt', 'r') as f:
for line in f:
print line
- ファイルへの書き込み
str に入っている文字列を、ファイルtest1.txtに書き込み。
str = 'test'
f = open('test1.txt', 'w')
f.write(str)
f.close()
または
str = 'test'
with open('test1.txt', 'w') as f:
f.write(str)
str2 に入っている文字列を、ファイルtest1.txtに追加して書き込み。
str2 = 'test2'
f = open('test1.txt', 'a')
f.write(str2)
f.close()
または
str2 = 'test2'
with open('test1.txt', 'a') as f:
f.write(str2)
リストstrsに入っている文字列を、ファイルtest2.txtに書き込み。
strs = ['test1\n', 'test2\n']
f = open('test2.txt', 'w')
f.writelines(''.join(strs))
f.close()
または
strs = ['test1\n', 'test2\n']
with open('test2.txt', 'w') as f:
f.writelines(''.join(strs))
- 画像ファイルの名前(シーケンス番号)変更
たとえば、 X:/maya/projects/default/images にある bomb2.iff.(番号)の画像ファイル全部を bomb2.iff.(番号+30) に番号を付け換えたければ以下のように実行。
bomb2.iff.1 〜 bomb2.iff.100 が bomb2.iff.31 〜 bomb2.iff.130 になる。
import os
import glob
add = 30
imgs = glob.glob('X:/maya/projects/default/images/bomb2.iff.*')
imgs = [i.split('.') for i in imgs]
imgs.sort(key=lambda x: int(x[2]))
if add > 0:
imgs.reverse()
imgs = [(i[0], i[1], i[2], str(int(i[2])+add)) for i in imgs]
imgs = [('.'.join(i[0:3]), '.'.join((i[0], i[1], i[3]))) for i in imgs]
print imgs
for ii in imgs:
os.rename(ii[0], ii[1])
- ディレクトリのファイル名を調べる
ディレクトリにあるファイル名のリストを得る。
>>> import glob
>>> glob.glob('tmp*')
['tmp1', 'tmp2', 'tmp3']
- コマンドライン引数を得る
コマンドラインの引数は sys.argv にリストで入っている。
>>> import sys
>>> sys.argv
['-r', '123', 'filename']
- オブジェクトが文字列かどうか調べる
文字列は Unicode の場合もあるので、isinstance() 関数によって、
basestring で調べる。
>>> s1 = 'test'
>>> s2 = u'unicode'
>>> isinstance(s1, basestring)
True
>>> isinstance(s2, basestring)
True
>>> isinstance(s2, str)
False
- リストの中からランダムに選ぶ
与えられたリストの中から、いくつかの要素をランダムに選ぶ。
>>> import random
>>> random.sample(range(10), 5)
[2, 4, 6, 3, 8]
>>> list1 = ['aaa', 'bbb', 'ccc', 5, 10, 20]
>>> random.sample(list1, 3)
['aaa', 5, 20]
- 実行時間の計測
計算・関数の実行時間を調べる。
>>> import timeit
>>> timeit.Timer('range(10)').timeit()
1.0400159358978271
>>> timeit.Timer('range(100)').timeit()
3.8700580596923828
>>> timeit.Timer('xrange(10)').timeit()
0.56000900268554688
>>> timeit.Timer('xrange(100)').timeit()
0.55000901222229004
- オブジェクトの型を調べる
>>> n = 3
>>> type(n)
<type 'int'>
>>> s = 'test'
>>> type(s)
<type 'str'>
- 文字を表す数値に変換
>>> ord('x')
120
- 文字列を整数に変換
>>> int('123')
123
- 文字列を実数に変換
>>> float('3.14')
3.14
- 数値を文字列に変換
>>> str(3.14)
'3.14'
- 2進数の文字列を10進数の数値に変換
>>> int('1010', 2)
10
- 8進数の文字列を10進数の数値に変換
>>> format('12', 8)
10
- 16進数の文字列を10進数の数値に変換
>>> format('a', 16)
10
- 数値を2進数の文字列に変換
>>> format(10, 'b')
'1010'
- 数値を8進数の文字列に変換
>>> format(10, 'o')
'12'
- 数値を16進数の文字列に変換
>>> format(10, 'x')
'a'
- if文を使わずにある範囲以外を切り捨て
ある変数xに入っている数値を0から3以外の部分を切り捨て。
>>> x = max(x, 0)
>>> x = min(x, 3)
- タプルをリストに変換
組み込み関数 list() を使用する。
>>> list((1, 2, 3))
[1, 2, 3]
- リストをタプルに変換
組み込み関数 tuple() を使用する。
>>> tuple([1, 2, 3])
(1, 2, 3)
- リストから同じ要素を削除
>>> list1 = [1, 2, 3, 4, 5, 3, 2]
>>> list2 = list(set(list1))
>>> list2
[1, 2, 3, 4, 5]
または
>>>list2 = sorted(set(list1), key=list1.index)
この場合は順番が保存される。
- ループカウンタと共にリストを処理
list1=['a', 'b', 'c']
for i, s in enumerate(list1):
print i,s
出力は以下の通り。
0 a
1 b
2 c
- 2つのリストを組み合わせて処理
list1=[1, 2, 3]
list2=['a', 'b', 'c']
for n, s in zip(list1, list2):
print n,s
出力は以下の通り。
1 a
2 b
3 c
- ネストしたリストを連結
2重のリストの場合。
>>> m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> sum(m, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> reduce(lambda x, y: x + y, m, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
任意のリストの場合。
def flatten(l):
if isinstance(l, list):
return reduce(lambda x, y: x + flatten(y), l, [])
else:
return [l]
>>> flatten([[1, 2], [3, [4, 5]], [6, [[7, 8], 9]]])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- 数値を丸める
>>> round(1.5)
2.0
>>> round(0.3)
0.0
- 平均値を求める
>>> a = [1, 2, 3, 4, 5]
>>> sum(a)
15
>>> sum(a)/len(a)
3
- シェルコマンドの出力を取り込む (Linux)
>>> import commands
>>> commands.getoutput('date')
2008年 1月 10日 木曜日 23:09:08 JST
>>> import os
>>> os.system('date')
2008年 1月 10日 木曜日 23:09:08 JST
- python スクリプトを読み込んで実行
execfile を使用する。
>>> execfile("./test.py")
- python スクリプト内で MEL コマンドを実行
Python コマンド eval を使用する。
maya.mel.eval("ls")
- MEL スクリプト内で python コマンドを実行
MEL コマンド python を使用する。
python("maya.cmds.sphere()")
- python コマンドを使用しないでスクリプトを実行 (Linux)
#!/usr/bin/env maya
をスクリプトの1行目に記述しておく。
- 空行を削除
以下のスクリプトは、標準入力から読み込んだデータから、
空行を削除するものである。
import re
import sys
list = []
for line in sys.stdin:
list.append(line)
pat = re.compile("^$")
for n in list:
if pat.match(n):
list.remove(n)
print "".join(list)
または、以下のようにしてもよい。
import sys
import re
re.sub(r"\n+", "\n", sys.stdin.read())
- インデックス可能コレクションを空にしてコピー
>>> data = [1, 2, 3]
>>> empty = data[:0]
>>> print empty
[]
>>> data = (1, 2, 3)
>>> empty = data[:0]
>>> print empty
()
>>> data = 'abcde'
>>> empty = data[:0]
>>> print empty
>>>
- 文字列が数字だけかどうか調べる
>>> str1 = '123'
>>> str1.isdigit()
True
>>> str2 = '-123'
>>> str2.isdigit()
False
- 文字列を2文字ずつ分解
>>> str = 'abcdefgh'
として、
['ab', 'cd', 'ef', 'gh']
のように分解する。
- イテレータを使用する方法
>>> import operator
>>> iter = iter(str)
>>> map(operator.add, iter, iter)
- mapのみで実行する方法
>>> import operator
>>> map(operator.add, str[::2], str[1::2])
- 正規表現を使用する方法
>>> import re
>>> re.findall('..', str)
- 内包表現を使用する方法 1
>>> [str[n:n+2] for n in xrange(0, len(str), 2)]
- 内包表現を使用する方法 2
>>> [t + u for t, u in zip(str[::2], str[1::2])]
- 文字列の長さ(日本語)
% cat printlen.py
# -*- coding: utf-8 -*-
data = u'あいうえお'
print len(data)
% python printlen.py
5
- WindowsでLinux用のテキストをファイルに出力
Windows上で、以下のようにテキストをファイルに出力すると
自動的に改行コード(\n)がCRLFになります。
fp = open('filename','w').write('output text\n')
これを、LinuxなどUNIX系のOS用に改行コードをLFのまま出力するには、
以下のように出力ファイルをバイナリモードでopenします。
fp = open('filename','wb').write('output text\n')
- ファイルから読み込んだ文字列の長さ(日本語)
ファイル内の文字が UTF-8 の場合
>>> data = open('filename').read()
>>> print len(data.decode('utf-8'))
- 文字がひらがな・カタカナかどうか(日本語)
re モジュールを使用する方法。
>>> import re
>>> if 'あ' in [c for c in u'ぁ-んァ-ン']:
>>> print True
unicodedata モジュールを使用する方法。
>>> import unicodedata
>>> if unicodedata.name(u'あ').split()[0] == 'HIRAGANA':
>>> print True
- HTTPサーバー起動
>>> import SimpleHTTPServer
>>> SimpleHTTPServer.test()
- HTTPサーバー起動(CGI付き)
>>> import CGIHTTPServer
>>> CGIHTTPServer.test()
- itertools を使用した 2 次元のループ
>>> import itertools
>>> for i,j in itertools.product(range(3), range(2)):
... print i,j
...
0 0
0 1
1 0
1 1
2 0
2 1
同じ回数のループは以下のようにも実行できる。
>>> import itertools
>>> for i,j in itertools.product(range(3), repeat=2):
... print i,j
...
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
- itertools を使用した 3 次元のループ
>>> import itertools
>>> for i,j,k in itertools.product(range(4), range(3), range(2)):
... print i,j,k
...
0 0 0
0 0 1
0 1 0
0 1 1
0 2 0
0 2 1
1 0 0
1 0 1
1 1 0
1 1 1
1 2 0
1 2 1
2 0 0
2 0 1
2 1 0
2 1 1
2 2 0
2 2 1
3 0 0
3 0 1
3 1 0
3 1 1
3 2 0
3 2 1
同じ回数のループは以下のようにも実行できる。
>>> for i,j,k in itertools.product(range(3), repeat=3):
... print i,j,k
...
0 0 0
0 0 1
0 0 2
0 1 0
0 1 1
0 1 2
0 2 0
0 2 1
0 2 2
1 0 0
1 0 1
1 0 2
1 1 0
1 1 1
1 1 2
1 2 0
1 2 1
1 2 2
2 0 0
2 0 1
2 0 2
2 1 0
2 1 1
2 1 2
2 2 0
2 2 1
2 2 2
- yield を使用した 2 次元のループ
def range2d(xres = 320, yres = 240):
x = 0
y = 0
for n in range(xres*yres):
if x >= xres:
x = 0
y += 1
if y >= yres:
return
yield x,y
x += 1
for x,y in range2d(30, 20):
print x,y
- yield を使用した 3 次元のループ
def range3d(xres = 100, yres = 100, zres = 100):
x = 0
y = 0
z = 0
for n in range(xres*yres*zres):
if x >= xres:
x = 0
y += 1
if y >= yres:
y = 0
z += 1
if z >= zres:
return
yield x,y,z
x += 1
for x,y,z in range3d(30, 20, 10):
print x,y,z
- 変数•関数が存在するかどうか調べる
testという名前の変数または関数が存在するかどうか。
例外を使う方法。
try:
test
except NameError:
print 'not exist'
globals()を使う方法。
if 'test' in globals():
print 'exist'
- 関数が実行された回数を数えるデコレータ
def count(func):
def infunc(*args, **kwargs):
ret = func(*args, **kwargs)
infunc.n += 1
print func.__name__, infunc.n
return ret
infunc.n = 0
return infunc
@count
def test1():
pass
@count
def test2(n):
return 2 * n
上の関数を実行すると以下のように出力されます。
>>> test1()
test1 1
>>> v = test2(5)
test1 2
>>> test1()
test1 2
>>> v = test2(v)
test2 2
>>> v = test2(v)
test2 3
- 辞書によってif文を置き換える方法
以下のようなコードがあったとすると辞書によってif文を置き換えることができます。
if x == 'aaa':
test1()
elif x == 'bbb':
test2()
elif x == 'ccc':
test3()
以下のように辞書の値に関数を与えます。
d = {'aaa':test1, 'bbb':test2, 'ccc':test3}
x = 'aaa'
d[x]()
d[x]がtest1に置き換わり test1() が実行されます。
ただし、xの値が辞書のキーに無い場合にはエラーになるので、
その場合には以下のように何もしない関数do_nothing()を利用してget()メソッドを使用します。
def do_nothing(*arg):
pass
x = 'ddd'
d.get(x, do_nothing)()
d['ddd']が存在しないので do_nothing() が実行されます。
- 現在、アクティブなプロジェクト名を調べる
maya.cmds.workspace(q=True,active=True)
- 現在、アクティブなプロジェクトのパスを調べる
maya.cmds.workspace(q=True,directory=True)
- プロジェクト名のリストを得る
maya.cmds.workspace(listWorkspaces=True)
# Result: [u'default', u'test'] #
プロジェクト名のディレクトリのパスも同時に得たい場合のコマンド
maya.cmds.workspace(listFullWorkspaces=True)
# Result: [u'/home/abe/maya/projects/default', u'/home/abe/maya/projects/test'] #
- プロジェクトを変更する
たとえば、現在のプロジェクトを test という名前のプロジェクトに変更するには、
以下のコマンドを使用する。
maya.cmds.workspace('test',openWorkspace=True)
- Maya 起動直後にオブジェクトを作成
Maya が起動された直後に、
シーン中にオブジェクトを作成するには、
~/maya/scripts/userSetup.py
または
~/maya/8.5/scripts/userSetup.py
に以下のようなコマンドを記述しておく。
import maya
maya.utils.executeDeferred(maya.cmds.sphere)
引数を渡す場合には以下のように実行する。
maya.utils.executeDeferred(maya.cmds.sphere, r=3)
または
maya.utils.executeDeferred("maya.cmds.sphere(r=3)")
- スタンドアローン スクリプトを実行する方法
まず、スタンドアローン スクリプトの先頭には、
以下のようなコマンドを記述しておく。
import maya.standalone
maya.standalone.initialize( name='python' )
これらのコマンド以下は、通常の Python スクリプトを記述する。
スクリプトの記述が終了したら、
スタンドアローン スクリプトは mayapy コマンドによって実行する。
たとえば、test.py という スタンドアローン スクリプトを実行する場合は、
コマンドラインから以下のように実行する。
% mayapy test.py
実行できない場合は、mayapy コマンドの存在するホルダ(ディレクトリ)にパスを通しておく。
(Windows の場合)
C:\\Program Files\\Autodesk\\Maya8.5\\bin
(Linux の場合)
/usr/autodesk/maya8.5/bin
- mayaBinary を mayaAscii に変換するスタンドアローン スクリプト
test.mb (mayaBinary) を test.ma (mayaAscii) に変換する
スタンドアローン型のスクリプトは以下のようになる。
import maya.standalone
maya.standalone.initialize( name='python' )
import maya
maya.cmds.file('test.mb',o=True)
maya.cmds.file(rename='test.ma')
maya.cmds.file(save=True, type='mayaAscii')
このスクリプトを mbtoma.py というファイル名で保存したら、
以下のように実行する。
% mayapy mbtoma.py
- バッチレンダリング を実行するスタンドアローン スクリプト (mayaSoftware)
test.mb を mayaSoftware によってレンダリングするスタンドアローン スクリプトは、
以下のようになる。
import maya.standalone
maya.standalone.initialize( name='python' )
import maya
maya.cmds.file('test.mb',open=True)
maya.cmds.render(batch=True)
test.mb は現在のプロジェクトの scenes フォルダから探される。
- mentalray でバッチレンダリング
mental ray でバッチレンダリングを実行するためには、Mayatomr() を使用する。
maya.cmds.Mayatomr(render=True)
- レンダラーの種類を調べる
defaultRenderGlobalsノードのcurrentRendererアトリビュートによって、
Render Settings で設定されたレンダラーの種類を調べることができる。
renderer = maya.cmds.getAttr("defaultRenderGlobals.currentRenderer")
if renderer == "mentalRay":
maya.cmds.Mayatomr(render=True)
elif renderer == "mayaSoftware":
maya.cmds.render(b=True)
elif renderer == "mayaHardware":
maya.cmds.hwRender()
elif renderer == "mayaVector":
maya.cmds.vectorize()
- 画像フォーマットを変更してバッチレンダリング を実行
画像フォーマットを TGA に変更するには、以下のコマンドを実行する。
maya.cmds.setAttr("defaultRenderGlobals.imageFormat",19)
TGA をあらわす 19 を他の番号に変更すると他の画像フォーマットになる。
画像フォーマット |
番号 |
TIF |
3 |
SGI |
5 |
IFF |
7 |
JPG |
8 |
TGA |
19 |
BMP |
20 |
PNG |
32 |
- アニメーションの設定に変更してバッチレンダリング を実行
たとえば、name.####.ext というファイル名形式で、
1 フレーム目から 60 フレーム目までをレンダリングするコマンドは以下のようになる。
maya.cmds.setAttr("defaultRenderGlobals.animation",1)
maya.cmds.setAttr("defaultRenderGlobals.putFrameBeforeExt",1)
maya.cmds.setAttr("defaultRenderGlobals.periodInExt",1)
val = maya.cmds.getAttr("defaultRenderGlobals.outFormatControl")
if val is 1:
maya.cmds.setAttr("defaultRenderGlobals.outFormatControl",0)
maya.cmds.setAttr("defaultRenderGlobals.extensionPadding",4)
maya.cmds.setAttr("defaultRenderGlobals.startFrame",1)
maya.cmds.setAttr("defaultRenderGlobals.endFrame",60)
- MEL から Python への引数の変換方法
- フラグではない引数は左
- 単独のフラグには =True をつける
- フラグに 2 つ以上の数値・文字列がつく場合はリスト・タプルにする
- 2つ以上同じ名前のフラグはダメ
- 引数の中では改行 OK
- プラグインのロード
Python で記述されたプラグインがロードされているかどうかチェックして、
ロードされていなければロードするには以下のように実行する。
try:
maya.cmds.pluginInfo('myPlugin', q=True, n=True)
except:
maya.cmds.loadPlugin('c:/home/abe/python/Plugin.py')
- リモートからの MEL コマンド実行
Maya の外部から MEL のコマンド、または MEL スクリプトを実行する方法。
- 以下の Python スクリプトを rmc.py という名前で作成
import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 8888))
com = sys.stdin.read()
com = com.replace('\n', '')
sock.send(com)
- Maya で以下の MEL コマンドを実行
commandPort -n ":8888";
- コマンドラインから以下のコマンドを実行
# echo sphere | python rmc.py
Python がインストールされていない場合は、mayapyを実行。
- Maya のシーン内に NURBS 球体が作成される
- MEL スクリプトを実行する場合
Linux のシェルの場合
# cat test.mel | python rmc.py
Windows のコマンドプロンプトの場合
# type test.mel | python rmc.py
pythonコマンドが存在しない場合は、
mayapyコマンドなどを使用します。
rmc.py 内の localhost の部分を他のマシンのアドレスに変更することもできます。