分岐での If-Then-Else 論理の使用

if-then-else 論理は、条件に基づいて異なる処理を実行するための単純で強力な概念です。if-then-else 論理は、「条件が true の場合はある処理を実行し、同じ条件が false の場合は別の処理を実行する」のように説明できます。

ModelBuilder での if-then-else 論理の使用

ModelBuilder で if-then-else 論理を実装するには、条件をテストして true と false の状態を表す 2 つの Boolean 変数を出力するスクリプト ツールを作成し、このスクリプト ツールをモデルに組み込みます。スクリプト ツールを作成する代わりに、[値の計算(Calculate Value)] ツールを使用して、条件のテストと Boolean 値の出力を行うこともできます。

次のモデルは、[座標系の確認(Check Coordinate System)] というスクリプト ツールを組み込んで、分岐の論理を使用しています。このスクリプト ツールは入力データセットを評価して、そのデータセットの座標系が投影された State Plane 座標系であるか、不明の座標系であるかを通知します。このモデルでは、入力データセットの座標系が投影された State Plane 座標系であると判断された場合、何も処理は実行されません。一方、入力データの座標系が不明の座標系であると判断された場合、モデルは投影システムを定義して、入力データを投影変換します。ModelBuilder で分岐論理を使用する際の主な手順の 1 つは、条件出力の 1 つを後の処理に対する前提条件として設定することです。

If-Then-Else の例

if-then-else 論理の例

次のサンプル コードは、上で説明した [座標系の確認(Check Coordinate System)] スクリプト ツールで、if-then-else による分岐がどのように実装されるかを示しています。スクリプトは 2 つの変数を出力し、1 つは if(true)条件を表し、もう 1 つは else(false)条件を表しています。

座標系の確認の例

この例は、入力データが StatePlane であるか、PRJ がないか、StatePlane 以外であるかをチェックします。

# Import modules
import arcpy
import sys
import traceback


# Set local variables
prj = "" 
indata = "C:/ToolData/well.shp" 
dsc = arcpy.Describe(indata) 
sr = dsc.spatialReference 
prj = sr.name.lower()

try:
 
   # check if indata is in StatePlane, has no PRJ, or one other than StatePlane
   if prj.find("_stateplane_") > -1:
       # Set the Is Unknown parameter to FALSE, and the Is StatePlane parameter to TRUE
       arcpy.SetParameterAsText(1,"false") #The first parameter refers to the "Is Unknown" variable
       arcpy.SetParameterAsText(2,"true") #The second parameter refers to the "Is StatePlane" variable
       arcpy.AddMessage("Coordinate system is StatePlane") 

   elif prj == "unknown": 
       # Set the Is Unknown parameter to TRUE, and the Is StatePlane parameter to FALSE
       arcpy.SetParameterAsText(1,"true") 
       arcpy.SetParameterAsText(2,"false") 
       arcpy.AddMessage("To continue, first define a coordinate system!") 

   else:
       # Set the Is Unknown parameter to FALSE, and the Is StatePlane parameter to FALSE
       arcpy.SetParameterAsText(1,"false") 
       arcpy.SetParameterAsText(2,"false") 
       arcpy.AddMessage("Coordinate system is not StatePlane or Unknown") 

except: 
   tb = sys.exc_info()[2]
   tbinfo = traceback.format_tb(tb)[0] 
   pymsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value) 
   arcpy.AddError("Python Messages: " + pymsg + " GP Messages: " + arcpy.GetMessages(2)) 




7/10/2012