def dropdata_handler(mime_type, data, hook): """Handling dropdata.""" if mime_type != 'text/plain': return None data = u(data) if hook.is_ignore_data(data=data): return None LOGGER.debug('Handling dropdata: %s %s', mime_type, data) urls = chain([data], *hook.get_url(data=data)) filenames = chain(*(chain([i], *hook.get_filenames(url=i)) for i in urls)) try: ret = None for filename in progress(tuple(filenames)): if hook.is_ignore_filename(filename=filename): LOGGER.debug('Ignore filename: %s', filename) ret = True continue LOGGER.debug('Handling filename: %s', filename) context = {'is_created': False} nodes = tuple( chain(*hook.create_node(filename=filename, context=context))) if any(nodes): ret = True LOGGER.debug('Created nodes: %s', nodes) hook.after_created(nodes=nodes) return ret except CancelledError: return True
def execute(self): for n in progress(self.nodes, '设置节点'): set_knobs(n, **self._values) new_name = self._rename_knob.evaluate() if new_name: try: n.setName(new_name) except ValueError: nuke.message(b'非法名称, 已忽略')
def compare_with(self, local_dir): """Check if file already downloaded to @local_dir. """ _local_dir = Path(local_dir) is_dir_exists = _local_dir.exists() existed = [get_weak_filehash(i) for i in _local_dir.iterdir()] for i in progress(list(self), '比较文件修改日期'): assert isinstance(i, RemoteFile) i.is_updated = is_dir_exists and get_weak_filehash(i) in existed
def execute(self): """Start task. """ files = self._files for f in progress(files, '分离exr'): cmd = u'"{nuke}" -t "{script}" "{file_path}" "{output_dir}" -f "{file_type}"'.format( nuke=nuke.EXE_PATH, script=__file__, file_path=os.path.join(self.input_dir, f), file_type=self.output_ext, output_dir=self.output_dir) proc = Popen(e(cmd)) proc.wait() webbrowser.open(self.output_dir)
def dialog_create_dirs(): """A dialog for create dirs from cgtwq. """ folder_input_name = b'输出文件夹' database_input_name = b'数据库' prefix_input_name = b'镜头名前缀限制' panel = nuke.Panel(b'为项目创建文件夹') panel.addSingleLineInput(database_input_name, 'proj_qqfc_2017') panel.addSingleLineInput(prefix_input_name, '') panel.addFilenameSearch(folder_input_name, 'E:/temp') confirm = panel.show() if not confirm: return try: database = panel.value(database_input_name) save_path = panel.value(folder_input_name) prefix = panel.value(prefix_input_name) for _ in progress(['连接CGTeamWork...', ], '创建文件夹'): try: select = cgtwq.Database(database)['shot_task'].filter( cgtwq.Field('pipeline') == '合成') except cgtwq.IDError as ex: nuke.message(utf8('找不到对应条目\n{}'.format(ex))) return for name in progress(select['shot.shot'], '创建文件夹'): if not name or not name.startswith(prefix): continue _path = os.path.join(save_path, name) if not os.path.exists(_path): os.makedirs(_path) webbrowser.open(save_path) except CancelledError: LOGGER.debug('用户取消创建文件夹')
def parse_sheet(sheet): """Parse datasheet""" assert isinstance(sheet, openpyxl.worksheet.worksheet.Worksheet) first_row = find_first_row(sheet) data_start_row = first_row[0].row + 1 data_columns = find_data_columns(first_row) ret = [] for row in progress( sheet.iter_rows(min_row=data_start_row), total=sheet.max_row - data_start_row + 1): data = parse_row(row, data_columns) if data: ret.append(data) return ret
def download(self): """Download Files. """ if self.is_downloading: return self.is_downloading = True self.buttonBox.setEnabled(False) try: is_skip_same = self.checkBoxSkipSame.isChecked() pool = Pool() for i in progress(self.files, '下载文件', parent=self): result = pool.apply_async(i.download, (Path(self.dir) / Path(i).name, ), dict(is_skip_same=is_skip_same)) while not result.ready(): QCoreApplication.processEvents() if not result.successful(): raise RuntimeError('Download failed', i) finally: self.is_downloading = False self.buttonBox.setEnabled(True)
def __init__(self, target=SUBMIT_FILE): select = cgtwq.DesktopClient().selection() files = set() if target == SUBMIT_FILE: # Get from submit files. files.update(select.flow.list_submit_file()) else: # Get from filebox. checked = set() for entry in progress(select.to_entries(), '获取文件框内容'): assert isinstance(entry, cgtwq.Entry) filebox = entry.filebox.from_id(target.id) path = Path(filebox.path) for rule in filebox.rule: key = (path, rule) if key in checked: continue files.update(i for i in path.glob(rule) if i.is_file()) checked.add(key) files = (RemoteFile(i) if not isinstance(i, RemoteFile) else i for i in list(files)) super(RemoteFiles, self).__init__(files)
def run(self): """Start process all shots with a processbar.""" shots = self.get_shot_list() shots_info = dict.fromkeys(self._all_shots, '本次未处理') is_multi_threading = self.flags & MULTI_THREADING thread_count = cpu_count() if is_multi_threading else 1 pool = Pool(thread_count) proc_queue = Queue() cancel_event = Event() def _run(shot): if cancel_event.is_set(): return '取消: {}'.format(shot) output = os.path.join( CONFIG['output_dir'], '{}_v0.nk'.format(shot)) input_dir = shot if os.path.isdir( shot) else os.path.join(CONFIG['input_dir'], shot) cmd = u'"{nuke}" -t -priority low "{script}" "{input_dir}" "{output}"'.format( nuke=nuke.EXE_PATH, script=__path__, input_dir=input_dir, output=output ) try: LOGGER.info('%s:开始', shot) proc = Popen(cmd, # shell=True, stdout=PIPE, stderr=PIPE) proc_queue.put(proc) stderr = u(proc.communicate()[1]) if START_MESSAGE in stderr: stderr = stderr.partition( START_MESSAGE)[2].strip() if stderr: shots_info[shot] = stderr elif proc.returncode: if cancel_event.is_set(): shots_info[shot] = '用户取消' else: shots_info[shot] = 'Nuke非正常退出: {}'.format( proc.returncode) else: shots_info[shot] = '正常完成' LOGGER.info('%s:结束', shot) except: shots_info[shot] = traceback.format_exc() LOGGER.error('Unexpected exception during comp', exc_info=True) raise RuntimeError return '完成: {}'.format(shot) if is_multi_threading: _run = run_with_memory_require(8)(_run) def _oncancel(): cancel_event.set() while not proc_queue.empty(): proc = proc_queue.get() if proc.poll() is None: try: proc.terminate() except OSError: pass try: for _ in progress(pool.imap_unordered(_run, shots), name='批量合成', total=len(shots), start_message=( '正在使用 {} 线程进行……'.format(thread_count)), oncancel=_oncancel): pass except (CancelledError, RuntimeError): pass webbrowser.open(self.generate_report(shots_info)) webbrowser.open(CONFIG['output_dir'])
def test_qt_handler(): from wlf.progress.handlers import QtProgressHandler with qt_app(): for _ in progress(range(200), 'qt测试', handler=QtProgressHandler()): time.sleep(0.01)
def test_cli_handler(): from wlf.progress.handlers import CLIProgressHandler for _ in progress(range(200), 'cli测试', handler=CLIProgressHandler()): time.sleep(0.01)
def test_base_handler(): from wlf.progress.handlers import BaseProgressHandler for _ in progress(range(200), 'base测试', handler=BaseProgressHandler()): time.sleep(0.01)