【发布时间】:2017-03-24 17:50:59
【问题描述】:
我在返回函数时遇到了一些麻烦。我想创建一个 Nuke 脚本,询问用户一个目录,并在写入节点中自动设置该目录的路径,其中包含当前日期、时间等。这部分非常简单(这是提供的 DateWrite() 函数代码)
现在,我想在渲染完成后打开这个目录。所以我必须使用回调并调用一个打开给定目录的函数。
这是我遇到麻烦的地方:由于目录是在第一个函数中设置的,我尝试使用 return 获取此函数的值。
它有效,但它迫使我使用第一个函数两次(这部分是openDirectoryAfterRender() 函数)
#Modules import
import nuke
import subprocess
# Create DateWrite function
def DateWrite():
# Create Variables
selectedNodes = nuke.selectedNodes() # Get Selection of all selected nodes
if len(selectedNodes) == 1:
filePath = nuke.getFilename('Set Output Directory') # Asks the user to set an OutPut directory for the Write Node
writeNode = nuke.createNode("Write") # Create a Write Node
writeNode['file'].setValue(filePath + "[file rootname [file tail [value root.name]]]_[date %y][date %m][date %d]_[date %H][date %M].png") # Set the Write Node with TCL
writeNode['afterRender'].setValue('openDirectoryAfterRender()') # Add a callback which will call the function openDirectoryAfterRender()
else:
nuke.message("No node selected or more than one node are selected.\nPlease select only one node.")
return filePath
# Create openDirectoryAfterRender
def openDirectoryAfterRender():
directoryToOpen = DateWrite() # Get the returned directory from DateWrite() -but also execute DateWrite another time-
directoryToOpen = directoryToOpen.replace('/','\\') # Replace the slashes with backslashes
subprocess.Popen('explorer %s' % directoryToOpen) # Open the chosen directory
我对 Python 和一般代码都很陌生,所以这可能是一个菜鸟问题。 我尝试了很多不同的解决方案,这是我能得到的最接近我想要的解决方案。
非常感谢!
【问题讨论】:
-
“它迫使我使用第一个函数两次”。请注意,
def DateWrite():行是定义函数,而不是调用它。正如您现在的代码一样,您只需执行一次DateWrite。还是您的意思是“它迫使我分配给directoryToOpen两次”?您可以使用directoryToOpen = DateWrite().replace('/', '\\')一行完成。 -
@Kevin 建议的唯一缺点是,如果 DateWrite retuns
None,您将收到属性错误。如果len(selectedNodes) != 1DateWrite()返回None。 -
我认为现在如果
len(selectedNodes) != 1,那么它会在return上以UnboundLocalError崩溃,因为根本没有分配给filePath。 -
os.path有一个名为normpath的方法,根据您使用的平台,您可能会发现它比.replace( '/', '\\' )更有用。 -
“就像你现在的代码一样,你只执行一次 DateWrite。”实际上,
DateWrite执行了两次,即使我只执行了openDirectoryAfterRender:执行函数时,以及渲染完成时。即使我尝试directoryToOpen = DateWrite().reaplce('/', '\\'),它也会再次执行DateWrite函数(因为变量DateWrite()中有directoryToOpen)。我的主要问题是我不想在声明openDirectoryToOpen变量时执行DateWrite。不知道说的清楚不明白,我的思路可能有误:)
标签: python function return nuke