def openScriptFolder(): #GETTING SCRIPT PATH AND ADDING '/' AT THE END file = nuke.script_directory() splitList = file.split('/') path = "" for i in range(0, (len(splitList))): path += splitList[i] + '/' #WORK AROUND FOR WHITE SPACES IN STRING IF ANY spacespath = '' spaceList = path.split(' ') for i in range(0, (len(spaceList))): spacespath += spaceList[i] + '\ ' FinalPath = '' spaceList2 = spacespath.split('/') spaceList2.pop(-1) FinalPath = '/'.join(spaceList2) + '/' print FinalPath #DOING THE WORK def open(path): if os.path.exists(file): if (sys.platform == 'win32'): os.system('start ' + FinalPath) elif (sys.platform == 'darwin'): os.system('open ' + FinalPath) else: subprocess.Popen(['xdg-open', FinalPath]) else: nuke.message('Path is empty:\n' + file) open(FinalPath)
def loadFeedback(): scriptDirectory = nuke.script_directory() cutDirectory = scriptDirectory.split('/') eliminateVariable = [] readList = [] allread = nuke.allNodes('Read') #---------------------------getting the filepath--------------------------- for x in cutDirectory: if x == '03 NK': del x else: eliminateVariable.append(x) feedbackDirectory = '/'.join( eliminateVariable) + "/05 Other files/feedback/" #---------------------------watch your reads my friend--------------------------- for f in allread: readList.append(f.knob('label').getValue()) #---------------------------creating or not the read--------------------------- for x in os.listdir(feedbackDirectory): if x in readList: print "allready exist here" else: feedback = nuke.createNode('Read', inpanel=False) feedback['file'].setValue(feedbackDirectory + x) feedback['label'].setValue(x)
def addRelPathCommandMenu(): # import re projectPath = nuke.menu('Nodes').findItem( 'jj_tools/Set Project Directory').addMenu('Project Path') projectPath.clearMenu() for i in range(5)[::-1]: projectPath.addCommand( re.escape(nuke.script_directory().rsplit('/', i)[0]), 'setProjDir.setProjDir(%s)' % str(i + 1))
def get_project_directory(): """ project directory に設定されているパスを文字列で返す。 :return: string """ temp_dir = nuke.Root()["project_directory"].getValue() if temp_dir == "[python {nuke.script_directory()}]": temp_dir = nuke.script_directory() return temp_dir
def __init__(self, parent): super(gui_pathConverter, self).__init__(parent) self.setWindowFlags(QtCore.Qt.Tool) #initializes some default font attributes that will be used to distinguish the difference between selected and deselected items within the tool try: self.italicFont = QtGui.QApplication.font() except: self.italicFont = QtGui.QGuiApplication.font() self.italicFont.setWeight(50) self.italicFont.setItalic(1) try: self.boldFont = QtGui.QApplication.font() except: self.boldFont = QtGui.QGuiApplication.font() self.boldFont.setBold(1) self.boldFont.setItalic(0) #stores the absolute pathname for the current working script into a variable as an instance within the 'gui_pathConverter()' class self.SCRIPT_DIR = nuke.script_directory() nuke.root()['project_directory'].setValue(self.SCRIPT_DIR) #sets the 'objectName()' and 'windowTitle()' arguments of the 'QtWidgets.QMainWindow' object self.setObjectName('gui_pathConverterObj') self.setWindowTitle('Path Converter') #initializes size of the 'myGUI' window to be 800 x 600px self.resize(800, 600) #creates a 'menuBar' widget and parents it to the 'QtWidgets.QMainWindow' object self.myMenuBarWidget = QtWidgets.QMainWindow.menuBar(self) #creates a 'QMenu' widget named "Help," and adds it to the 'menuBar' object self.menuHelp = QtWidgets.QMenu('Help') self.myMenuBarWidget.addMenu(self.menuHelp) #creates a 'QAction' widget named "Help," connects it to the 'self.showHelpDialog()' function, and adds it to the 'menuHelp' object #self.actionHelp = QtWidgets.QAction('Help', self.menuHelp) #self.connect(self.actionHelp, QtCore.SIGNAL('triggered()'), self.showHelpDialog) #self.menuHelp.addAction(self.actionHelp) #creates a 'QAction' widget named "About," connects it to the 'self.showAboutDialog()' function, and adds it to the 'menuHelp' object self.actionAbout = QtWidgets.QAction('About', self.menuHelp) self.connect(self.actionAbout, QtCore.SIGNAL('triggered()'), self.showAboutDialog) self.menuHelp.addAction(self.actionAbout) #initializes 'myMainWidget' as a parenting object for all other 'QWidget()' objects within the 'myGUI()' class self.primary_widget = QtWidgets.QWidget() self.setCentralWidget(self.primary_widget) #initializes 'layout' as a variable that will serve to organize the 'QWidget()' objects contained within 'myMainWidget' self.primary_layout = QtWidgets.QVBoxLayout(self.primary_widget) #calls 'self.coreFunction()' which creates the core for this tool self.coreFunction()
def KuWrite(): '''Adding inputs for auto generate output path''' RENDER_TYPE = ['comp', 'precomp', 'lookdev'] node = nuke.createNode('Write') node.setName('KuWrite') node.knob('file').setEnabled(False) k_pipeline = nuke.Text_Knob('kupipeline', 'kuWrite', 'kuWrite') # Ku Pipeline Identifier k_tab = nuke.Tab_Knob('tb_KuWrite', 'KuWrite') k_projDir = nuke.File_Knob('fp_proj', 'proj dir') k_scene = nuke.String_Knob( 'tx_scene', 'scene', os.path.basename(nuke.scriptName()).split('_v')[0]) k_type = nuke.Enumeration_Knob('mu_type', 'type', RENDER_TYPE) k_precomp = nuke.String_Knob('tx_precomp', '_', 'NewPass') k_ver = nuke.Int_Knob('nm_ver', 'version', 1) k_div = nuke.Text_Knob('divider', '') k_set = nuke.PyScript_Knob('bt_set', '<b>Set Write</b>', 'mod_KuWrite.set_settings(nuke.thisNode())') k_render = nuke.PyScript_Knob('bt_render', '<b>Render</b>', 'mod_KuWrite.render_node(nuke.thisNode())') path_proj = os.path.dirname(os.path.dirname(nuke.script_directory())) k_projDir.setValue(path_proj) k_precomp.clearFlag(nuke.STARTLINE) k_precomp.setVisible(False) k_ver.setValue(1) k_render.clearFlag(nuke.STARTLINE) k_pipeline.setVisible(False) for k in [ k_tab, k_pipeline, k_projDir, k_scene, k_type, k_precomp, k_ver, k_div, k_set, k_render ]: node.addKnob(k) set_settings(node)
def resolve_knob_path(knob): ''' Resolve the knob value of any TCL expression and/or relative path Note that this does *not* resolve any frame number expressions. args: knob: any File_Knob object return: str. the resolved path value example paths: '[python {nuke.script_directory()}]/../images/sequences/02/image.%04d.jpg' '../images/sequences/[value this.name]/image.%04d.jpg' '../images/sequences/03/image.%04d.jpg' '../images/sequences/../sequences/03/image.%04d.jpg' '' ''' raw_value = knob.value() logger.debug("Resolving tcl expressions (if any) on %s value: %r", knob.fullyQualifiedName(), raw_value) path = nuke.runIn(knob.node().fullName(), "nuke.tcl('return %s')" % raw_value.replace("'", "\\'")) # If the path is empty/none, simply return. no further processing necessary if not path: return path or "" # ensure we return str if not os.path.isabs(path): logger.debug("Resolving relative path: %s", path) # Join the relative path with the nuke script directory path = os.path.join(nuke.script_directory(), path) # Resolve any ellipses in the path (e.g. ../../ ). Unfortunately this also normpaths it, which may lead to some fallout/bugs path = os.path.abspath(path) logger.debug("Resolved to: %s", path) return path
def resolve_knob_path(knob): ''' Resolve the knob value of any TCL expression and/or relative path Note that this does *not* resolve any frame number expressions. args: knob: any File_Knob object return: str. the resolved path value example paths: '[python {nuke.script_directory()}]/../images/sequences/02/image.%04d.jpg' '../images/sequences/[value this.name]/image.%04d.jpg' '../images/sequences/03/image.%04d.jpg' '../images/sequences/../sequences/03/image.%04d.jpg' '' ''' raw_value = knob.value() logger.debug("Resolving tcl expressions (if any) on %s value: %r", knob.fullyQualifiedName(), raw_value) path = nuke.runIn(knob.node().fullName(), "nuke.tcl('return %s')" % raw_value) # If the path is empty/none, simply return. no further processing necessary if not path: return path or "" # ensure we return str if not os.path.isabs(path): logger.debug("Resolving relative path: %s", path) # Join the relative path with the nuke script directory path = os.path.join(nuke.script_directory(), path) # Resolve any ellipses in the path (e.g. ../../ ). Unfortunately this also normpaths it, which may lead to some fallout/bugs path = os.path.abspath(path) logger.debug("Resolved to: %s", path) return path
class ssPanel(nukescripts.PythonPanel): DEV = 0 rootDir = nuke.script_directory() snapsDir = rootDir + "/snaps" def __init__(self): nukescripts.PythonPanel.__init__(self, 'Snapshotr', 'uk.co.thefoundry.ssPanel') if self.DEV > 0: print "\n* Debug mode ON" print "* rootDir inside ssPanel __init__ = " + self.rootDir print "* snapsDir inside ssPanel __init__ = " + self.snapsDir self.btn_snap_fullres = nuke.PyScript_Knob('Full') self.btn_snap_instant = nuke.PyScript_Knob('Instant') self.btn_open_webview = nuke.PyScript_Knob('Open') self.commentField = nuke.String_Knob('Comment:') self.divider = nuke.Text_Knob('') self.markNode = nuke.Boolean_Knob('Mark node ') self.timerValue = nuke.Int_Knob('Autosnap: ') self.addKnob(self.commentField) self.addKnob(self.btn_snap_instant) self.addKnob(self.btn_snap_fullres) self.addKnob(self.btn_open_webview) self.addKnob(self.timerValue) self.addKnob(self.divider) self.addKnob(self.markNode) self.timerValue.setValue(60) # 60 minutes by default scriptPath = nuke.toNode('root').knob('name').value() scriptName = scriptPath.split("/")[-1] if cmn.check_script(name=scriptName) is None: nuke.message( "Please save your script in the following format:\nshot.task.artist.v00.00.nk" ) raise BaseException def snapAutosave(): """ Create auto snapshot, start timer to trigger this (every 60min by default) """ try: c_var = cmn.init_common_vars(snapsDir=self.snapsDir) print "\n~ autosaving snapshot..." cmn.create_snapshot_dirs(rootDir=self.rootDir, snapsDir=self.snapsDir, snapPath=c_var["snapPath"], markNode=self.markNode) cmn.create_snapshot_script( scriptPath=c_var["scriptPath"], snapScriptName=c_var["snapScriptName"], upversion=False) cmn.create_snapshot_comment( snapCommentFile=c_var["snapCommentFile"], commentText="#autosnap") cmn.create_snapshot_screenshot( DEV=self.DEV, snapImageFile=c_var["snapImageFile"]) finally: timer = int(self.timerValue.value()) * 60000 QtCore.QTimer.singleShot(timer, snapAutosave) snapAutosave() def snap_instant(self): """ Create instant snapshot of current active viewer """ c_var = cmn.init_common_vars(snapsDir=self.snapsDir) cmn.create_snapshot_dirs(rootDir=self.rootDir, snapsDir=self.snapsDir, snapPath=c_var["snapPath"], markNode=self.markNode) cmn.create_snapshot_script(scriptPath=c_var["scriptPath"], snapScriptName=c_var["snapScriptName"], upversion=True) cmn.label_node(markNode=self.markNode, nodeLabel=c_var["nodeLabel"]) cmn.create_snapshot_comment(snapCommentFile=c_var["snapCommentFile"], commentText=self.commentField.getText()) cmn.create_snapshot_screenshot(DEV=self.DEV, snapImageFile=c_var["snapImageFile"]) def snap_fullres(self): """ Create full-res snapshot via BG render """ c_var = cmn.init_common_vars(snapsDir=self.snapsDir) cmn.create_snapshot_dirs(rootDir=self.rootDir, snapsDir=self.snapsDir, snapPath=c_var["snapPath"], markNode=self.markNode) cmn.create_snapshot_script(scriptPath=c_var["scriptPath"], snapScriptName=c_var["snapScriptName"], upversion=True) cmn.label_node(markNode=self.markNode, nodeLabel=c_var["nodeLabel"]) cmn.create_snapshot_fullres(snapImageFile=c_var["snapImageFile"], writeUniqueName=c_var["writeUniqueName"], fakeFrameRange=c_var["fakeFrameRange"]) cmn.create_snapshot_comment(snapCommentFile=c_var["snapCommentFile"], commentText=self.commentField.getText()) def prevent_doubleclick(self, time=None): self.commentField.setValue("") self.commentField.setEnabled(False) self.btn_open_webview.setEnabled(False) self.btn_snap_instant.setEnabled(False) self.btn_snap_fullres.setEnabled(False) def unlock(): self.commentField.setEnabled(True) self.btn_open_webview.setEnabled(True) self.btn_snap_instant.setEnabled(True) self.btn_snap_fullres.setEnabled(True) QtCore.QTimer.singleShot(time, unlock) def knobChanged(self, knob): """ :param knob: certain knob within panel """ scriptPath = nuke.toNode('root').knob('name').value() scriptName = scriptPath.split("/")[-1] pFile = str(scriptName).split(".") pFile = "_".join(pFile[0:2]) pFile = self.snapsDir + "/" + pFile + ".html" if knob is self.btn_snap_fullres: self.snap_fullres() webview_html = snapshotr_webView.updateWebView( debug=self.DEV, s_dirs=self.snapsDir) cmn.write_html(pFile=pFile, html=webview_html) self.prevent_doubleclick(time=2000) elif knob is self.btn_snap_instant: self.snap_instant() webview_html = snapshotr_webView.updateWebView( debug=self.DEV, s_dirs=self.snapsDir) cmn.write_html(pFile=pFile, html=webview_html) self.prevent_doubleclick(time=2000) elif knob is self.btn_open_webview: webbrowser.open('file://' + os.path.realpath(pFile), new=2, autoraise=True) elif knob is self.timerValue: if self.timerValue.value() < 10: self.timerValue.setValue(10) elif self.timerValue.value() > 60: self.timerValue.setValue(60) else: pass
def HubCamera(): ###################CREATING DIRECTORY############################ #-----defining first part of the dinamic directory(based in nukeproject)-------- scriptDirectory = nuke.script_directory() cutDirectory = scriptDirectory.split('/') eliminateVariable = [] if os.path.isdir(scriptDirectory) == False: nuke.message("The nuke project it's not define" +" \n "+ "please save file") else: for x in cutDirectory: if x == 'Script': del x else: eliminateVariable.append(x) camDirectory = '/'.join(eliminateVariable) + "/Camera/" #--------File search .abc or .fbx and store in camsAvailable---------- if os.path.isdir(camDirectory) == False: nuke.message("out of the pipeline:" + "\n" + "expecting X:/Movie/Scene/Shot/Script/ - for the scripts files" + "\n" + "expecting X:/Movie/Scene/Shot/Camera/ - for the Camera files") return else: camsAvailable = [] ###all cameras availables### for filename in os.listdir(camDirectory): if filename.endswith(".abc") or filename.endswith(".fbx"): camsAvailable.append(filename) else: print "this is not a cam file {}".format(filename) #--------------Appendin last camara file (by version)--------------- lastCameraFile = [] if len(camsAvailable) > 0: lastCameraFile.append(camsAvailable.pop())#ultima camara por version. pero puede fallar lastCameraFile = "".join(lastCameraFile) nuke.message(str(camsAvailable)) else: nuke.message("there are no camera in: " + "\n" + "{}".format(camDirectory)) return #---------------Camara creation and path confirm--------------------- finallyThePath = camDirectory + lastCameraFile ###################CREATING CAMERA############################ hubCamera = nuke.createNode('camera_project_1.0.0.nk', inpanel=False) #Custom Camera project hubCamera['read_from_file'].setValue(True) hubCamera['file'].setValue(finallyThePath) hubCamera.forceValidate() #######NO HAY CAMARAS EN DIRECTORIO### ok #######NO SE ENCUENTRA DIRECTORIO#####ok (eliminar doble mensaje) #######NO ESTA DEFINIDO LA RUTA DEL NUKE##### ok #######guardalo y reemplazar como archivo.### ####usar ultimo modificado ####
def make_collect_folder(): split = os.path.splitext(nuke.scriptName()) dst_path = os.path.join(nuke.script_directory(), split[0] + "_Collected") return make_folder(dst_path)
def nuke_get_path_from_write_node(inputH, knob="file"): """ Gets a file path from a specified node/input This function normalizes and attempts to make absolute all paths, whether the input is originally absolute or relative .. Considerations:: This method was originally written simply for Nuke objects and getting their knobs but it was eventually adopted to take strings with parseable text (such as %04d, $F4, ####) and an integer as knob in order to return a specific frame number in a sequence. Sorry this method got shoe-horned in so poorly Exmaple Use #1: >>> nukeObject = nuke.toNode("Write1") >>> fileKnobName = "file" >>> nuke_get_path_from_write_node(nukeObject, fileKnobName) "/whatever/is/nuke/node/file/knob/filename_####.tiff" Example Use #2: >>> filename = r"/some/path/filename_####.tiff" >>> indexNumber = 8 >>> nuke_get_path_from_write_node(filename, indexNumber) "/some/path/filename_0008.tiff" Args: inputH (Nuke object or str): The input node or string to get the full path from knob (str or int): A string to a Nuke object knob or an integer for parsed text Returns: str: The actual filename to save """ # LOGGER.info('string inputH:' + str(inputH)) # LOGGER.info('string knob:' + str(knob)) # LOGGER.info('string inputH:' + str(type(inputH))) # LOGGER.info('string knob:' + str(type(knob))) LOGGER.info('INPUT fileToSave:' + str(inputH)) # replace anjy parseable text with a number sequence with padding if isinstance(knob, int) and paths.is_parseable(inputH) \ and isinstance(inputH, six.string_types): fileToSave = paths.get_expanded_str_from_index(inputH, knob) fileToSave = os.path.join(os.path.dirname(inputH), fileToSave) elif isinstance(knob, int) and isinstance(inputH, six.string_types): fileToSave = inputH else: fileToSave = inputH[knob].value() # get absolute path of file if os.path.isabs(fileToSave): fileToSave = os.path.normpath(fileToSave) # redundant but just in case else: baseDir = nuke.Root()['project_directory'].value() if baseDir == '[python {nuke.script_directory()}]': # :::TO DO::: potentially vulnerable. # perhaps process with regex or as TCL and get/run the result? # baseDir = nuke.script_directory() fileToSave = os.path.join(baseDir, fileToSave) fileToSave = os.path.normpath(fileToSave) # LOGGER.info('string inputH:' + str(inputH)) # LOGGER.info('string knob:' + str(knob)) LOGGER.info('string fileToSave:' + fileToSave) return fileToSave