Updated 2017-03-20 22:10:18 by Molecool

p-Shell - A Tcl Interface to Creo Parametric edit

Scripting in Creo

p-Shell is a Creo Application which runs synchronous or a-synchronous with Creo, enables access to Creo Files via functions within a running Tcl/Tk environment.

Show some of many p-Shell built-In commands. This allows scripting in Creo for administrative or automation jobs and application development.

More info: Tcl4Creo (at) gmail (dot) com


This section shows how to work with parameter/attributes in Creo using the p-Shell command 'ps_param'

Sample: Create new parameter (or modify if exists) and change/set the value
# Create a parameter
set paramObj [ps_param set MY_Param String {Hallo World}  ]

# Configure the value

$paramObj configure -value "Hallo Wiki Tcl"

#Create two string parameter at the first feature with the ID 1 

ps_modelitem miObj -model box.prt -type Feature -id 1

set paramObjs [ps_param set -at_item miObj -- [list MY_Param1 MY_Param2] String {Unknown} ]

Sample: Simple output of all parameter within the current Creo CAD model.
# write all parameter from the current model into a csv file with the name param.txt
proc GetParamToCSV {} {
# csv delimeter ',' or ';' ?
  set del ";"

# create the file

  set fp [open param.csv w]

# write the header
  puts $fp [join [list Name Type Value] $del]

# sorted param names output

  foreach paramObj [lsort -dictionary [ps_param  list] ] {

    set nam [$paramObj cget -name]
    set val [$paramObj cget -value]
    set typ [$paramObj cget -type]

    puts $fp [join [list $nam $typ $val] $del]


# close and done

  close $fp


Creo Callback Menu

Provide a Callback menu in Creo.

Based on the installation, there is a 'program' folder, each folder may provide a Tcl Callback program if you place a 'pshell_init.tcl' file within this folder.

Sample 'pshell_init.tcl' file, argv0 is the path to the init file. The 'program' folder are parsed once, recursively on Creo Start. The command may supply additional arguments.
proc PShell_Init {dir} {
  ps_auto_menu add -root     {My Attributes}                 \
                   -text     {Model Attributes}              \
                   -command  [list $dir/MyAttributes.tcl]


PShell_Init [file dirname $argv0]

If the user select now the menu "Tools->My Attributes->Model Attributes" in Creo the file '$dir/MyAttributes.tcl' in the same dir of the 'pshell_init.tcl' file gets sourced an executed. All required files for Creo (menu files) will be created automatically on run time. To end the Tcl program call 'exit', which will only end the running Tcl program.

Another Parameter Sample

Show some commands and usage. Assume the parameter name is 'IDENT' and the final value should be "A-123-K-009", enable export to Windchill
# Set a parameter by name, type and value
# Make sure we have a parameter which is a STRING
# Check if exists

if ![ps_param  exists IDENT] {

# Okay create it
   set paramCmd [ps_param  set IDENT String "This is a Identnumber, please change me." ]

  } else {

# Paramter exists. Is parameter a STRING type ?
#  If locked create an error

    set paramCmd [ps_param  list IDENT]

    if  [$paramCmd islocked]  {

      error "Error: Parameter IDENT is locked"


    if ![string equal [$paramCmd cget -type]  STRING ] {
# Wrong type
# Get val and create a string type
    set val [$paramCmd cget -value]

# Delete the param
    $paramCmd delete

# Create as a STRING type with old value

    set paramCmd [ps_param  set  IDENT String $val ]



# Change to the final value and enable with designate the export to Windchill

$paramCmd configure -value "A-123-K-009" -designate Yes -description "This Parameter will hold the Article Number"

Note: Working with dimensions is similar, a dimObj will contain more info (Tolerance, Tolerance Label, owning FeatId, the value,...) which can be extracted with the 'cget' option.

Asynchronous Sample

In Asynchronous mode you start Creo or connect to an existing session. After this you can drive Creo without having a callback in a Creo Menu.
# Simple asynchrounes Creo Session
# to load a Creo Drawing and export an DXF file
# Execute in Tcl as a callback or just in plain Tcl

# Setup to callback functions
# Invoked after connection is establish
proc pShell_Init {} {puts "Connected"}
# Invoked after connection is closed
proc pShell_Exit {} { puts "Session closed"}

# In Tcl get the DLL
package req pshell_asyn 

# Configure and Start the Creo Session
ps_session ::PS::SessionCmd                               \
        -exit                pShell_Exit                  \
        -init                pShell_Init                  \
        -timeout             20                           \
        -text                C:/p-Shell/programs/text     \
        -pro_comm_msg        [file native "C:/Creo 2/Common Files/M200/x86e_win64/ob/pro_comm_msg.exe"] 

# Start Creo 
# after connect 'pShell_Init' is called
::PS:SessionCmd start [file native "C:/Creo 2/Parametric/bin/creo2.bat"]

# Make sure that all Datums are not displayed
# Load a config file wich will turn on/off what we want

ps_import config c:/Release/release.pro

# Open the Drawing in the current Working Dir
ps_file open box.drw

# Get the referenced model
# No error check here (None or more than one)
set refMdl [ps_draw list -drawing box.drw]

# Make sure not to display a certain layer, turn off a layer where we have only curves
# No error check here (Layer exists, current status)

ps_layer set -model $refMdl -- ALL_CURVES Blank

# Update the title block to display the current day (This is Based on the used Format)
# assume parameter DRW_RELASE_DATE is new or exists as a string 
ps_param  set DRW_RELEASE_DATE String [clock format [clock seconds] -format "%m/%d/%y"]

# Display the Drawing in a Window
ps_wind set box.drw

# Create the DXF file
ps_export dxf -model box.drw -- box.dxf

# Save the drawing with the updated parameter
ps_file save box.drw

# Stop the session
# This will eval 'pShell_Exit' and delete all p-Shell commands
::PS:SessionCmd stop


Command options for ps_assy are:
     component_name       FeatID
     is_bulk_item         FeatID
     type                 FeatID
     matrix_get           comppathObj Matrix
     matrix_set           comppathObj Matrix
     explode              ?NewState?
     interchange          IDs ReplaceModel
     create               NAME.EXT Unplaced ?Template?
     dynamic_position     ?NewState?
     assemble             Component Matrix modelItemObjReturn
     setconstraints       CompPath ModelItem Constraints
     getconstraints       ModelItem Constraints
     numofconstraints     ModelItem

Assume you have have an active assembly test.asm where feature ID 43 is the subassembly sub.asm and contains a component with the name bolt.prt at feature id 30
# Assembly test.asm is active
# '0' the path is invalid or
# '1' the path is valid.
set member1 [ps_assy component_name    43 ] 
set member2 [ps_assy component_name  -model sub.asm  -- 30 ] 

member1 will be set to SUB.ASM

member2 will be set to BOLT.PRT

Component Path

Create a component path object. A component path object identifies a unique component in one assembly.
# Note: creation or configuration return 0 or 1. 
# '0' the path is invalid or
# '1' the path is valid.
ps_comppath    myPath  -model test.asm -path {43 30} -component bolt.prt

Export to file

Options for ps_export are:
     relation             Filename
     model_info           Filename
     program              Filename
     iges_2d              Filename
     dxf                  Filename
     render               Filename
     sla_binary           Filename
     sla_ascii            Filename
     catiafacets          Filename
     bom                  Filename
     dwg_setup            Filename
     feature_info         Filename
     mfg_oper_cl          Filename
     mfg_feat_cl          Filename
     material             Filename
     iges_3d              Filename
     step                 Filename
     vda                  Filename
     set                  Filename
     cgm                  Filename
     inventor             Filename
     fiat                 Filename
     connector_params     Filename
     catia                Filename
     cable_params         Filename
     optegra_vis          Filename
     dwg                  Filename

Geometric Data

Options for ps_data are:
     axis               Geom_ID lineObj
     edge               Geom_ID lineObj
     arc                Geom_ID arcObj
     csys               Geom_ID csysObj
     surface            Geom_ID csysObj
     point              Geom_ID pointObj
     outline            lineObj
     eval_surface       Geom_ID UVpointObj lineObj
     extremes           Geom_ID pointObj lineObj
     edge_eval_xyz      IDs Params
     curve_eval_xyz     IDs Params
     edge_dir           SurfID EdgeID
     curve              Geom_ID lineObj
     tessellation       Geom_ID Tolerance


ps_matrix matrixObj

This command will create a 4x4 identity matrixObj

Options for matrixObj are:
     cget                   Option
     configure              Option ?Value?
     rot2d                  angle
     normalize              ?matrixOut?
     copy                   matrixOut
     product                matrixObj ?matrixOut?
     x_to_vector            pointObj
     y_to_vector            pointObj
     z_to_vector            pointObj
     origin_to_vector       pointObj
     x_from_vector          pointObj
     y_from_vector          pointObj
     z_from_vector          pointObj
     origin_from_vector     pointObj
     shift_to_vector        pointObj
     shift_from_vector      pointObj
     scale_xyz              ScaleValue

Sample command
# copy the matrix
matrixObj copy bckMatrix

Similar commands available for points, arcs, coordinate systems, and single line (2 Points)

Options for pointObj are:
     cget              Option
     configure         ?Option?
     transform         matrixObj pointObj
     rotate            matrixObj pointObj
     copy              pointObj
     product           pointObj
     angle             pointObj
     cross_product     point2Obj resultPointObj
     add               point2Obj resultPointObj
     move              point2Obj resultPointObj
     diff              point2Obj resultPointObj
     2d_values         XY_List
     3d_values         XYZ_List
     multiply          matrixObj pointObj
     draw              ?Color?


Command options for ps_feat are:
     name                     FeatIDs
     type                     FeatIDs
     exists                   FeatIDs
     children                 FeatID
     parents                  FeatID
     status                   FeatIDs
     visible                  FeatIDs
     active                   FeatIDs
     number                   FeatIDs
     has_geom_checks          FeatIDs
     suppress                 FeatIDs
     delete                   FeatIDs
     resume                   FeatIDs
     protype                  FeatIDs
     subtype                  FeatIDs
     show_param               selObj ParamType
     set_name                 FeatID NewName
     is_read_only             FeatIDs
     set_read_only            FeatID
     ungroup                  GroupIDs
     groupstatus              FeatIDs
     isgroup                  FeatIDs
     num_section              FeatID
     section_copy             FeatID secNumber sectionObjName
     cancel_insert_mode       ?BoolResume?
     insert_mode_activate     FeatID
# Children of a feature in the active model
ps_feat child 23

# Parents from FeatID 45 in model box.prt
ps_feat parents -model box.prt -- 45

# get the status for all features in the active model
set stat  [ps_feat stat [ps_feat list]]


Options for ps_file are:
     open        Filename
     erase       Filename
     exists      Filename
     save        Filename
     delete      Filename
     display     Filename
     copy        Source Target
     rename      Source Target
     backup      Filename NewDir
     create      Filename
     get         ?Filter? ?InitPath? ?Label? ?PreSelect?

Note: Get working directory with 'ps_pwd' and change with 'ps_cd TargetDir'
# open file from disc into memory
ps_file open c:/workdir/box.prt


Invoke a user selection
# create the selection object
ps_sel selObj

# The usr should select an edge
# Wirite something into the Creo message area

ps_mess "Please select an edge"

# Control goes to Creo
selObj select edge

# Back in p-Shell:
# Get the model item from the selection object
# Note: You can also get the status if a user abort.
selObj modelitem miObj

# It's an edge - get the edge data into an lineObj
# Note: the line object will contains more info, calculate length is only one option

ps_data edge -model [miObj get -model] --  [miObj get -id ]  lineObj

# get the vector length
set len  [lineObj len]

CAD[Category 3D][Category Creo][Category Creo Scripting]