カスタム コマンドから Python タイプを返す

 
 
 

Python で作成したカスタム コマンドからの戻り値をセットアップする場合は、次に示すように、Python ネイティブ ディクショナリと Python カスタム クラスをそのまま渡すことはできないことに注意する必要があります。

戻り値として Python ディクショナリを使用する場合

Python ネイティブ ディクショナリの型は、Softimage がカスタム コマンドからの戻り値として許可するデータ型に適合していません。解決策として、次のコード(自己インストール カスタム コマンドからの抜粋)で示すように、ActiveX スクリプト ディクショナリを使用できます。

#---------
def testdictionary_Execute(  ):
	import win32com.client
	oDict = win32com.client.Dispatch( "Scripting.Dictionary" )

	oDict[ 'key1' ] = 123
	oDict[ 'key2' ] = 45
	oDict[ 'key3' ] = 6789
	
	return oDict
#---------

戻り値として Python カスタム クラスを使用する場合

Python カスタム コマンドは、関数と属性を VBScript と JScript がメソッドおよびプロパティとして使用できる Python オブジェクトを返すことができます。以下の手順に従います。

  1. Python クラスの次の属性を設定して、公開するメソッドと属性を定義します。
    • _public_methods_ : パブリック関数のリスト
    • _public_attrs_ : パブリック属性(読み取り専用と読み書き可の両方)のリスト
    • _readonly_attrs_ : 読み取り専用属性のリスト
  2. win32com.server.util.wrap( )関数を使用して、返されるクラスのインスタンスをラップします。

    カスタム コマンドは、オブジェクトを作成してこれを返します。

次の自己インストール プラグインは、VBScript と JScript で使用できる Python オブジェクトを返します。

 # This class will be exported to VBScript and JScript
class TestPython:
    # Declare list of exported functions
    _public_methods_ = ['GetAnswer']
    # Declare list of exported attributes
    _public_attrs_ = ['exclamation', 'answer']
    # Declare list of exported read-only attributes
    _readonly_attrs_ = ['answer']

    # Class init:
    def __init__(self):
    # Initialize exported attributes
	       self.exclamation = 1
	       self.answer = 42
		      # Perfectly valid to have other non exported attributes
    # Exported function
    def GetAnswer(self, question):
	       return "The answer to " + str(question) + " is " + str(self.answer) + "!"*self.exclamation
	       # Perfectly valid to have other non exported functions
		
true = 1

# Traditional Plugin installation
def XSILoadPlugin( in_reg ):
    in_reg.Author = "Command Wizard User"
    in_reg.Name = "TestPython Plug-in"
    in_reg.Major = 1
    in_reg.Minor = 0
    in_reg.RegisterCommand( "TestPython","TestPython" )
    return true

def TestPython_Init( io_Context ):
    oCmd = io_Context.Source
    oCmd.ReturnValue = true
    return true

def TestPython_Execute(  ):
    oClass = TestPython()
    import win32com.server
    # Class MUST be wrapped before being returned
    return win32com.server.util.wrap(oClass)

次の VBScript は Python オブジェクトを使用します。

set a = TestPython()
'INFO : TestPython_Execute called
LogMessage a.GetAnswer("life, the universe, everything")
'INFO : The answer to life, the universe, everything is 42!
a.exclamation = 10
LogMessage a.GetAnswer("life, the universe, everything")
'INFO : The answer to life, the universe, everything is 42!!!!!!!!!!

(例に示すように)毎回新しいオブジェクトを作成するか、オブジェクトの単一のインスタンスを共有するかを選択することができます。オブジェクトの単一のインスタンスはプラグインにグローバル変数として格納され、すべてのスクリプトがそのデータを共有できます。

詳細については、次の Python ソースを参照してください。