如何确保用户可以输入任何数据类型(str、float、int、boolean...)?

How to ensure that user can input any datatype (str, float, int, boolean...)?

所以这是我在论坛上的第一个问题,我希望我做对了。 一般问题:在编写允许用户根据上下文输入不同数据类型的值的脚本时,如何确保python不会return任何错误或者他们想改变的参数? 更具体:我是 python 的新手,想编写一个脚本,允许 The Foundry 的 Nuke 用户更改同一 class 的多个节点上的值一次。根据要更改的所需参数是否是复选框('bool')和 RGBA 输入(“4 个浮点数”)...输入必须是不同的类型。搜索论坛我发现可以通过 type() 函数检查类型,并在 if 语句中与 isinstance() 函数进行比较。我想我可以使用它,但是例如一个 Gradenode 的乘法旋钮 returns 类型 'AColor_Knob'。我期待像浮动的东西。无论我比较的数据类型如何,在 isinstance() 中进行比较都不会给我匹配项。

到目前为止的主要脚本:

nukescripts.clear_selection_recursive()

userInput = nuke.getInput('Which type of nodes would you like to select? (!!!first char has to be capitalized!!!)',
                          'Shuffle')

matchingNodes = []

for each in nuke.allNodes():
    if each.Class() == userInput:
        matchingNodes.append(each)
    else:
        pass

for i in matchingNodes:
    i.setSelected(True)

nuke.message(str(len(
    matchingNodes)) + ' matching Nodes have been found and are now selected! (if 0 there either is no node of this type or misspelling caused an error!)')

userInput_2 = nuke.getInput('Which parameter of these nodes would you like to change? \n' +
                            '(!!!correct spelling can be found out by hovering over parameter in Properties Pane!!!)',
                            'postage_stamp')
userInput_3 = nuke.getInput('To what do you want to change the specified parameter? \n' +
                            '(allowed input depends on parameter type (e.g. string, int, boolean(True/False)))', 'True')

for item in matchingNodes:
    item.knob(userInput_2).setValue(userInput_3)

到目前为止我是如何检查数据类型的:

selected = nuke.selectedNode()
knobsel = selected.knob('multiply')
print(type(knobsel))
#if type(knobsel) == bool:
if isinstance(knobsel, (str,bool,int,float,list)):
    print('match')
else:
    print('no match')

您可以使用 nuke.tcl() 调用 TCL 命令。在 TCL 中,一切都是字符串,因此类型无关紧要(在某些命令中)。

p = nuke.Panel('Property Changer')
p.addSingleLineInput('class', '')
p.addSingleLineInput('knob', '')
p.addSingleLineInput('value', '')
p.show()

node_class = p.value('class')
knob_name = p.value('knob')
knob_value = p.value('value')

for node in nuke.allNodes(node_class):
    tcl_exp = 'knob root.{0}.{1} "{2}"'.format(node.fullName(),knob_name,knob_value)
    print tcl_exp
    nuke.tcl(tcl_exp)

这应该可以回答您的问题。有很多方法可以实现您想要做的事情 - 如果您想将其全部保留在 python 中,您可以对旋钮的值进行类型检查。例如:

b = nuke.nodes.Blur()
print type(b.knob('size').value()).__name__

这将创建一个模糊节点并打印该类型的字符串值。虽然我不推荐这条路线,但你可以用它来转换价值:

example = '1.5'
print type(example)
exec('new = {}(example)'.format('float'))
print type(new) 

另一种下降途径可能是为自己构建自定义查找 table 旋钮类型和预期值。

编辑:

TCL Nuke 命令: http://www.nukepedia.com/reference/Tcl/group__tcl__builtin.html#gaa15297a217f60952810c34b494bdf83d

如果您在 nuke 节点图中按 X 或转到文件 > Comp 脚本命令,您可以 select TCL 和 运行:

knob root.node_name.knob_name knob_value

示例:

knob root.Grade1.white "0 3.5 2.1 1"

这将为命名旋钮设置值。