def load_string(file): """ Reads a string containing the contents of the given file. If this given file doesn't exist, or an error occurs, this method returns an empty string. """ retval = "" try: if File.Exists(file): with StreamReader(file, Encoding.UTF8, False) as sr: retval = sr.ReadToEnd() except: import log log.debug_exc("problem loading string from file " + sstr(file)) retval = "" return retval
def GetBatchRvtSettings(settingsFilePath, output): aborted = False batchRvtSettings = None if not File.Exists(settingsFilePath): output() output("ERROR: No settings file specified or settings file not found.") aborted = True else: batchRvtSettings = BatchRvtSettings() isSettingsLoaded = batchRvtSettings.LoadFromFile(settingsFilePath) if not isSettingsLoaded: output() output("ERROR: Could not load settings from the settings file!") aborted = True return batchRvtSettings if not aborted else None
def test(MemList): TotalRunTime = Stopwatch.StartNew() TotalSizeAnalyzed = 0 for MemoryDump in MemList: print " ++++++++++++++++++++++++++++++ ANALYZING INPUT [" + MemoryDump + "] ++++++++++++++++++++++++++++++ " if not File.Exists(MemoryDump): print "Can not find dump to analyze: " + MemoryDump continue copts.FileName = MemoryDump vtero = ScanDump(MemoryDump, copts) TotalSizeAnalyzed += vtero.FileSize print " ++++++++++++++++++++++++++++++ DONE WITH INPUT [" + MemoryDump + "] ++++++++++++++++++++++++++++++ " print " ++++++++++++++++++++++++++++++ ALL DONE... Please explore! ++++++++++++++++++++++++++++++" print "TOTAL RUNTIME: " + TotalRunTime.Elapsed.ToString() + " (seconds), TOTAL DATA ANALYZED: " + TotalSizeAnalyzed.ToString("N") + " bytes." print "SPEED: " + ((TotalSizeAnalyzed / 1024) / ((TotalRunTime.ElapsedMilliseconds / 1000)+1)).ToString("N0") + " KB / second (all phases aggregate time)" return vtero
def IsValidDraftTemplate(): # Check for a Draft template in the case of a Custom Draft if (scriptDialog.GetValue("DraftCustomRadio")): draftTemplate = scriptDialog.GetValue("DraftTemplateBox") if (not File.Exists(draftTemplate)): scriptDialog.ShowMessageBox( "Draft template file \"%s\" does not exist." % draftTemplate, "Error") return False elif (PathUtils.IsPathLocal(draftTemplate)): result = scriptDialog.ShowMessageBox( "The Draft template file \"%s\" is local, are you sure you want to continue?" % draftTemplate, "Warning", ("Yes", "No")) if (result == "No"): return False return True
def _check_magic_file(path_s): ''' ComicVine implementation of the identically named method in the db.py ''' series_key_s = None file_s = None try: # 1. get the directory to search for a cvinfo file in, or None dir_s = path_s if path_s and Directory.Exists(path_s) else \ Path.GetDirectoryName(path_s) if path_s else None dir_s = dir_s if dir_s and Directory.Exists(dir_s) else None if dir_s: # 2. search in that directory for a properly named cvinfo file # note that Windows filenames are not case sensitive. for f in [dir_s + "\\" + x for x in ["cvinfo.txt", "cvinfo"]]: if File.Exists(f): file_s = f # 3. if we found a file, read it's contents in, and parse the # comicvine series id out of it, if possible. if file_s: with StreamReader(file_s, Encoding.UTF8, False) as sr: line = sr.ReadToEnd() line = line.strip() if line else line match = re.match(r"^.*?\b(49|4050)-(\d{2,})\b.*$", line) line = match.group(2) if match else line if utils.is_number(line): series_key_s = utils.sstr(int(line)) except: log.debug_exc("bad cvinfo file: " + sstr(file_s)) # 4. did we find a series key? if so, query comicvine to build a proper # SeriesRef object for that series key. series_ref = None if series_key_s: try: dom = cvconnection._query_series_details_dom( __api_key, utils.sstr(series_key_s)) num_results_n = int(dom.number_of_total_results) series_ref =\ __volume_to_seriesref(dom.results) if num_results_n==1 else None except: log.debug_exc("error getting SeriesRef for: " + sstr(series_key_s)) if file_s and not series_ref: log.debug("ignoring bad cvinfo file: ", sstr(file_s)) return series_ref # may be None!
def ReadRevitFileListData(self, output): revitFileListData = None if self.RevitProcessingOption == BatchRvt.RevitProcessingOption.BatchRevitFileProcessing: if self.RevitFileList is not None: output() output("Reading Revit File list from object input.") self.RevitFileListData = revit_file_list.FromLines( self.RevitFileList) revitFileListData = self.RevitFileListData else: output() output("Reading Revit File list:") output() output("\t" + ( self.RevitFileListFilePath if not str.IsNullOrWhiteSpace( self.RevitFileListFilePath) else "Not specified!")) if not File.Exists(self.RevitFileListFilePath): output() output( "ERROR: No Revit file list specified or file not found." ) elif revit_file_list.HasExcelFileExtension( self.RevitFileListFilePath ) and not revit_file_list.IsExcelInstalled(): output() output( "ERROR: Could not read from the Excel Revit File list. An Excel installation was not detected!" ) else: revitFileListData = revit_file_list.FromFile( self.RevitFileListFilePath) revitFileList = ([ revitFilePathData.RevitFilePath for revitFilePathData in revitFileListData ] if revitFileListData is not None else None) self.RevitFileList = revitFileList self.RevitFileListData = revitFileListData if revitFileListData is None: output() output("ERROR: Could not read the Revit File list.") elif len(revitFileListData) == 0: output() output("ERROR: Revit File list is empty.") revitFileListData = None return revitFileListData
def __read(self): try: filestream = File.OpenRead(self.file_location) xml = XmlReader.Create(filestream) if self.progress: self.progress.filestream = filestream except IOError as e: raise e else: if xml.IsStartElement('osm'): self.__readOsmEntities(xml) else: print('Osm file is not valid. No <osm> element found.\n') finally: if File.Exists(self.file_location): xml.Close() filestream.Close()
def setUp(self): self.temp_directory = Env.GetEnvironmentVariable("TEMP") #check temp dir exists self.assertTrue(Directory.Exists(self.temp_directory)) #check temp file in temp dir does not exist if File.Exists(self.tempFileFullPath1 or self.tempFileFullPath2 or self.tempFileFullPath1): File.Delete(self.tempFileFullPath1) File.Delete(self.tempFileFullPath2) File.Delete(self.tempFileFullPath3) #create a file to check and delete fs1 = FileStream(self.tempFileFullPath1, FileMode.Create) fs2 = FileStream(self.tempFileFullPath2, FileMode.Create) fs3 = FileStream(self.tempFileFullPath3, FileMode.Create) fs1.Close() fs2.Close() fs3.Close()
def IsWordInstalled(): from Microsoft.Win32 import Registry from System.IO import File word = None #Office 11 or 12 are both OK for this test. Office 12 is preferred. word = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\12.0\\Word\\InstallRoot") if word==None: word= Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\11.0\\Word\\InstallRoot") #sanity check if word==None: return False #make sure it's really installed on disk word_path = word.GetValue("Path") + "winword.exe" return File.Exists(word_path)
def IsExcelInstalled(): from Microsoft.Win32 import Registry from System.IO import File excel = None #Office 11 or 12 are both OK for this test. Office 12 is preferred. excel = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\12.0\\Excel\\InstallRoot") if excel==None: excel = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Office\\11.0\\Excel\\InstallRoot") #sanity check if excel==None: return False #make sure it's really installed on disk excel_path = excel.GetValue("Path") + "excel.exe" return File.Exists(excel_path)
def process(context): filename = context.Request.Url.AbsolutePath if not filename: filename = "index.html" if filename[0] == '/': filename = filename[1:] print(filename) filename = Path.Combine(root, filename) print(filename) if not File.Exists(filename): context.Response.Abort() return input = FileStream(filename, FileMode.Open) bytes = Array.CreateInstance(Byte, 1024 * 16) nbytes = input.Read(bytes, 0, bytes.Length) while nbytes > 0: context.Response.OutputStream.Write(bytes, 0, nbytes) nbytes = input.Read(bytes, 0, bytes.Length) input.Close() context.Response.OutputStream.Close()
def SubmitButtonPressed(*args): global scriptDialog # Check if scene file exists. sceneFile = scriptDialog.GetValue( "SceneBox" ) #scriptDialog.ShowMessageBox(sceneFile, "") if( not File.Exists( sceneFile ) ): scriptDialog.ShowMessageBox( "The sceen {0} does not exist".format(sceneFile), "Error" ) return elif (PathUtils.IsPathLocal(sceneFile)): result = scriptDialog.ShowMessageBox( "The scene file {0} is local. Are you sure you want to continue?".format(sceneFile), "Warning", ("Yes","No") ) if(result=="No"): return # Create job info file. jobInfoFilename = Path.Combine( GetDeadlineTempPath(), "pdplayer_job_info.job" ) #scriptDialog.ShowMessageBox(str(jobInfoFilename), "") try: writer = StreamWriter( jobInfoFilename, False, Encoding.Unicode ) #<- this is the line messing up except Exception, e: scriptDialog.ShowMessageBox("error: " + str(e) , "")
def load_map(file): """ Reads a map out of the given file, which was created with the persist_map function. All keys in the returned map will be strings, but the values will be converted to integers, booleans and floats where possible. If this given file doesn't exist or an error occurs, this method returns an empty map. """ retval = {} try: if File.Exists(file): with StreamReader(file, Encoding.UTF8, False) as sr: line = sr.ReadLine() while line is not None: pair = line.strip().split(':') if len(pair) == 2: key = pair[0].strip() value = pair[1].strip() if value.lower() == "false": value = False elif value.lower() == "true": value = True else: try: if '.' in value: value = float(value) else: value = int(value) except: pass retval[key] = value line = sr.ReadLine() except: import log log.debug_exc("problem loading map from file " + sstr(file)) retval = {} return retval
def f3(arg0, arg1, arg2, *arg3): return "same## %s %s %s %s" % (arg0, arg1, arg2, arg3) if is_cli: from iptest.process_util import run_csc run_csc("/nologo /target:library /out:sbs_library.dll sbs_library.cs") import clr clr.AddReferenceToFile("sbs_library.dll") from SbsTest import C o = C() g1 = o.M1 g2 = o.M2 g3 = o.M3 #for peverify runs from System.IO import Path, File, Directory if File.Exists(Path.Combine(Path.GetTempPath(), "sbs_library.dll")): try: File.Delete(Path.Combine(Path.GetTempPath(), "sbs_library.dll")) except: pass if not File.Exists(Path.Combine(Path.GetTempPath(), "sbs_library.dll")): File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "sbs_library.dll"), Path.Combine(Path.GetTempPath(), "sbs_library.dll")) else: g1 = f1 g2 = f2 g3 = f3 # combinations choices = [(), (0,), (1,), (2,), (3,), (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3), (0, 1, 2, 3) ]
def isfile(self, filename): return File.Exists(filename)
def load_defaults(self): ''' Loads any settings that are saved in the user's settings files (if there are any) and stores them in this Configuration object. ''' # load the loaded dict out of the serialized file loaded = {} if File.Exists(Resources.SETTINGS_FILE): loaded = load_map(Resources.SETTINGS_FILE) # any settings that the serialized dict happens to contain if Configuration.__API_KEY in loaded: self.api_key_s = loaded[Configuration.__API_KEY] if Configuration.__UPDATE_SERIES in loaded: self.update_series_b = loaded[Configuration.__UPDATE_SERIES] if Configuration.__UPDATE_NUMBER in loaded: self.update_number_b = loaded[Configuration.__UPDATE_NUMBER] if Configuration.__UPDATE_PUBLISHED in loaded: self.update_published_b = loaded[Configuration.__UPDATE_PUBLISHED] if Configuration.__UPDATE_RELEASED in loaded: self.update_released_b = loaded[Configuration.__UPDATE_RELEASED] if Configuration.__UPDATE_TITLE in loaded: self.update_title_b = loaded[Configuration.__UPDATE_TITLE] if Configuration.__UPDATE_CROSSOVERS in loaded: self.update_crossovers_b = loaded[ Configuration.__UPDATE_CROSSOVERS] if Configuration.__UPDATE_WRITER in loaded: self.update_writer_b = loaded[Configuration.__UPDATE_WRITER] if Configuration.__UPDATE_PENCILLER in loaded: self.update_penciller_b = loaded[Configuration.__UPDATE_PENCILLER] if Configuration.__UPDATE_INKER in loaded: self.update_inker_b = loaded[Configuration.__UPDATE_INKER] if Configuration.__UPDATE_COVER_ARTIST in loaded: self.update_cover_artist_b = loaded[ Configuration.__UPDATE_COVER_ARTIST] if Configuration.__UPDATE_COLORIST in loaded: self.update_colorist_b = loaded[Configuration.__UPDATE_COLORIST] if Configuration.__UPDATE_LETTERER in loaded: self.update_letterer_b = loaded[Configuration.__UPDATE_LETTERER] if Configuration.__UPDATE_EDITOR in loaded: self.update_editor_b = loaded[Configuration.__UPDATE_EDITOR] if Configuration.__UPDATE_SUMMARY in loaded: self.update_summary_b = loaded[Configuration.__UPDATE_SUMMARY] if Configuration.__UPDATE_IMPRINT in loaded: self.update_imprint_b = loaded[Configuration.__UPDATE_IMPRINT] if Configuration.__UPDATE_PUBLISHER in loaded: self.update_publisher_b = loaded[Configuration.__UPDATE_PUBLISHER] if Configuration.__UPDATE_VOLUME in loaded: self.update_volume_b = loaded[Configuration.__UPDATE_VOLUME] if Configuration.__UPDATE_CHARACTERS in loaded: self.update_characters_b = loaded[ Configuration.__UPDATE_CHARACTERS] if Configuration.__UPDATE_TEAMS in loaded: self.update_teams_b = loaded[Configuration.__UPDATE_TEAMS] if Configuration.__UPDATE_LOCATIONS in loaded: self.update_locations_b = loaded[Configuration.__UPDATE_LOCATIONS] if Configuration.__UPDATE_WEBPAGE in loaded: self.update_webpage_b = loaded[Configuration.__UPDATE_WEBPAGE] if Configuration.__OVERWRITE_EXISTING in loaded: self.ow_existing_b = loaded[Configuration.__OVERWRITE_EXISTING] if Configuration.__IGNORE_BLANKS in loaded: self.ignore_blanks_b = loaded[Configuration.__IGNORE_BLANKS] if Configuration.__CONVERT_IMPRINTS in loaded: self.convert_imprints_b = loaded[Configuration.__CONVERT_IMPRINTS] if Configuration.__AUTOCHOOSE_SERIES in loaded: self.autochoose_series_b = loaded[ Configuration.__AUTOCHOOSE_SERIES] if Configuration.__CONFIRM_ISSUE in loaded: self.confirm_issue_b = loaded[Configuration.__CONFIRM_ISSUE] if Configuration.__DOWNLOAD_THUMBS in loaded: self.download_thumbs_b = loaded[Configuration.__DOWNLOAD_THUMBS] if Configuration.__PRESERVE_THUMBS in loaded: self.preserve_thumbs_b = loaded[Configuration.__PRESERVE_THUMBS] if Configuration.__FAST_RESCRAPE in loaded: self.fast_rescrape_b = loaded[Configuration.__FAST_RESCRAPE] if Configuration.__RESCRAPE_NOTES in loaded: self.rescrape_notes_b = loaded[Configuration.__RESCRAPE_NOTES] if Configuration.__RESCRAPE_TAGS in loaded: self.rescrape_tags_b = loaded[Configuration.__RESCRAPE_TAGS] if Configuration.__SUMMARY_DIALOG in loaded: self.summary_dialog_b = loaded[Configuration.__SUMMARY_DIALOG] # grab the contents of the advanced settings file, too if File.Exists(Resources.ADVANCED_FILE): self.advanced_settings_s = load_string(Resources.ADVANCED_FILE)
def run(self, Mml2vgmInfo, index): #設定値の読み込み Mml2vgmInfo.loadSetting() #ファイル選択 xgmFn = Mml2vgmInfo.fileSelect("xgmファイルの選択") if xgmFn is None: return None if not File.Exists(xgmFn): Mml2vgmInfo.msg("ファイルが見つかりません") return None if Path.GetExtension(xgmFn).ToLower() != ".xgm": Mml2vgmInfo.msg("拡張子が.xgmではありません") return None #ファイル読み込み xgmDat = File.ReadAllBytes(xgmFn) #FCCチェック if xgmDat[0]!=88 or xgmDat[1]!=71 or xgmDat[2]!=77: Mml2vgmInfo.msg("FCCがXGMではありません") return None sampleDataBlockSize = xgmDat[0x100] + xgmDat[0x101] * 0x100 #Mml2vgmInfo.msg(sampleDataBlockSize.ToString()) versionInformation = xgmDat[0x102]; #Mml2vgmInfo.msg(versionInformation.ToString()) dataInformation = xgmDat[0x103]; #Mml2vgmInfo.msg(dataInformation.ToString()) isNTSC = (dataInformation & 0x1) == 0; #Mml2vgmInfo.msg(isNTSC.ToString()) existGD3 = (dataInformation & 0x2) != 0; #Mml2vgmInfo.msg(existGD3.ToString()) multiTrackFile = (dataInformation & 0x4) != 0; #Mml2vgmInfo.msg(multiTrackFile.ToString()) sampleDataBlockAddr = 0x104; #Mml2vgmInfo.msg(sampleDataBlockAddr.ToString()) adr = sampleDataBlockAddr + sampleDataBlockSize * 256 musicDataBlockSize = xgmDat[adr] + xgmDat[adr+1]*0x100 + xgmDat[adr+2]*0x10000 + xgmDat[adr+3]*0x1000000 #Mml2vgmInfo.msg(musicDataBlockSize.ToString()) musicDataBlockAddr = sampleDataBlockAddr + sampleDataBlockSize * 256 + 4; #Mml2vgmInfo.msg(musicDataBlockAddr.ToString()) gd3InfoStartAddr = musicDataBlockAddr + musicDataBlockSize; #Mml2vgmInfo.msg(gd3InfoStartAddr.ToString()) #PCMテーブルを取得&出力 lst = List[Byte]() n = 0 while n < 63*4: ind=n+4 if ind == xgmDat.Length: break lst.Add(xgmDat[ind]) n+=1 File.WriteAllBytes( xgmFn + ".pcmTable.bin" , lst.ToArray() ) lst.Clear(); #PCMデータを取得&出力 if sampleDataBlockSize > 0: n=0 while n < sampleDataBlockSize * 256: ind=n + sampleDataBlockAddr if ind == xgmDat.Length: break lst.Add(xgmDat[ind]) n+=1 File.WriteAllBytes( xgmFn + ".pcmData.bin" , lst.ToArray() ) lst.Clear(); #SEQデータを取得&出力 if musicDataBlockSize > 0: n=0 while n<musicDataBlockSize: ind=n + musicDataBlockAddr if ind == xgmDat.Length: break lst.Add(xgmDat[ind]) n+=1 File.WriteAllBytes( xgmFn + ".seqData.bin" , lst.ToArray() ) lst.Clear(); #GD3データを取得&出力 if existGD3: n=0 while n < xgmDat.Length - gd3InfoStartAddr: ind=n + gd3InfoStartAddr lst.Add(xgmDat[ind]) n+=1 File.WriteAllBytes( xgmFn + ".gd3.bin" , lst.ToArray() ) lst.Clear(); Mml2vgmInfo.msg("xgmファイルを分割しました") #戻り値を生成(何もしないけど念のため) si = ScriptInfo() si.responseMessage = "" return si
# sort the table table = ZenTools.TableTools.SortColumn(table=table, columnname='Time' + tunit, option='asc') # show the soted table Zen.Application.Documents.Add(table) if savetable: # save the data to file tablefilename = img.FileName[:-4] + '_PlaneTable.csv' print 'Data will be saved to: ', tablefilename # check for exiting file if File.Exists(tablefilename): msg = ZenWindow() msg.Initialize('!!! Attention !!!') msg.AddLabel('File already exits. Allow to Overwrite?') result = msg.Show() # check, if Cancel button was clicked if result.HasCanceled: print('Canceled. Data will not be saved.') if not result.HasCanceled: print('File will be overwritten.') write_planetable(table, tablefilename, delimiter=',') if not File.Exists(tablefilename): write_planetable(table, tablefilename, delimiter=',')
#------------------------------------------------------------------------------ #--Globals #if this is a debug build and the assemblies are being saved...peverify is run. #for the test to pass, Maui assemblies must be in the AssembliesDir if is_peverify_run: AddReferenceToDlrCore() clr.AddReference("Microsoft.Scripting") from Microsoft.Scripting.Runtime import ScriptDomainManager from System.IO import Path tempMauiDir = Path.GetTempPath() print "Copying Maui.Core.dll to %s for peverify..." % (tempMauiDir) if not File.Exists(tempMauiDir + '\\Maui.Core.dll'): File.Copy( testpath.rowan_root + '\\Languages\\IronPython\\External\\Maui\\Maui.Core.dll', tempMauiDir + '\\Maui.Core.dll') #Cleanup the last run for t_name in ['ip_session.log', 'ip_session_stderr.log']: if File.Exists(t_name): File.Delete(t_name) Assert(not File.Exists(t_name)) #------------------------------------------------------------------------------ #--Helper functions def getTestOutput():
__import__(mod) except ImportError: pass else: print("""module %s has been implemented. It needs to be moved into the BUILTIN_MODULES list and a baseline should be generated using: ipy modulediff.py C:\\Python27\\python.exe %s""" % (mod, mod)) differs = 1 sys.exit(differs) if __name__ == '__main__': if len(sys.argv) < 2 or not File.Exists(sys.argv[1]): print('usage: ') print( ' ipy modulediff.py C:\\Python27\\python.exe module_name [module_name ...]' ) print( ' generates a report for an indivdual module into the baselines directory' ) print() print(' ipy modulediff.py C:\\Python27\\python.exe --') print( ' generates reports for all modules into the baselines directory' ) print() print(' ipy modulediff.py C:\\Python27\\python.exe') print(
def exists(filename): Directory.CreateDirectory(_basePath) return File.Exists(get_path(filename))
# Permission is granted to use, modify and distribute this code, # as long as this copyright notice remains part of the code. ################################################################# from System.Diagnostics import Process from System.IO import File, Path, Directory import time # clear output Zen.Application.MacroEditor.ClearMessages() # define the external plot script or tool pythonexe = r'C:\Anaconda3\python.exe' script = r'c:\External_Python_Scripts_for_OAD\test_wellplate_from_ZEN.py' if not File.Exists(pythonexe): message = 'Python Executable not found.' print(message) raise SystemExit if File.Exists(pythonexe): message = 'Python Executable found.' print(message) if not File.Exists(script): message = 'Plot Script not found.' print(message) raise SystemExit if File.Exists(script): message = 'Plot Script found.'
def monitoringAction(): pendingProcessOutputReadLineTask[0] = ShowRevitProcessOutput( hostRevitProcess.StandardOutput, output, pendingProcessOutputReadLineTask[0]) pendingProcessErrorReadLineTask[0] = ShowRevitProcessError( hostRevitProcess.StandardError, showRevitProcessErrorMessages, output, pendingProcessErrorReadLineTask[0]) pendingReadLineTask[0] = ShowRevitScriptOutput( scriptOutputStreamReader, output, pendingReadLineTask[0]) if time_util.GetSecondsElapsedSinceUtc( progressRecordCheckTimeUtc[0] ) > REVIT_PROGRESS_CHECK_INTERVAL_IN_SECONDS: progressRecordCheckTimeUtc[ 0] = time_util.GetDateTimeUtcNow() progressRecordNumber = ScriptDataUtil.GetProgressNumber( progressRecordFilePath) if progressRecordNumber is not None: if currentProgressRecordNumber[ 0] != progressRecordNumber: # Progress update detected. currentProgressRecordNumber[ 0] = progressRecordNumber progressRecordChangedTimeUtc[ 0] = time_util.GetDateTimeUtcNow() if processingTimeOutInMinutes > 0: if currentProgressRecordNumber[0] != 0: if time_util.GetSecondsElapsedSinceUtc( progressRecordChangedTimeUtc[0]) > ( processingTimeOutInMinutes * SECONDS_PER_MINUTE): output() output( "WARNING: Timed-out waiting for Revit task / file to be processed. Forcibly terminating the Revit process..." ) TerminateHostRevitProcess(hostRevitProcess, output) if currentProgressRecordNumber[0] == 0: if time_util.GetSecondsElapsedSinceUtc( progressRecordChangedTimeUtc[0] ) > REVIT_PROCESS_BEGIN_PROCESSING_TIMEOUT_IN_SECONDS: output() output( "WARNING: Timed-out waiting for Revit script host to begin task / file processing. Forcibly terminating the Revit process..." ) TerminateHostRevitProcess(hostRevitProcess, output) if snapshotDataFilesExistTimestamp[0] is not None: if time_util.GetSecondsElapsedSinceUtc( snapshotDataFilesExistTimestamp[0] ) > REVIT_PROCESS_EXIT_TIMEOUT_IN_SECONDS: output() output( "WARNING: Timed-out waiting for the Revit process to exit. Forcibly terminating the Revit process..." ) TerminateHostRevitProcess(hostRevitProcess, output) elif snapshotDataFilePaths.All( lambda snapshotDataFilePath: File.Exists( snapshotDataFilePath)): output() output( "Detected snapshot data files. Waiting for Revit process to exit..." ) snapshotDataFilesExistTimestamp[ 0] = time_util.GetDateTimeUtcNow() try: revit_dialog_detection.DismissCheekyRevitDialogBoxes( hostRevitProcessId, output) except Exception, e: output() output( "WARNING: an error occurred in the cheeky Revit dialog box dismisser!" ) exception_util.LogOutputErrorDetails(e, output)
def getDirectory(p): if File.Exists(p): return Path.GetDirectoryName(p) if Directory.Exists: return p return
# define the actual CZI file to be analyzed czifile = CZIdict[cziname] czifile_cmd = '"' + CZIdict[cziname] + '"' params = czifile_cmd + ' ' + writecsv + ' ' + separator + ' ' + save + ' ' + saveformat_result + ' ' + surface print 'CZI file to be used: ', czifile print 'Parameter : ', params # when option to save the figure was set if save_result: savename = Path.GetFileNameWithoutExtension( czifile) + '_planetable_XYZ-Pos.' + saveformat_result savename_full = Path.Combine(Path.GetDirectoryName(czifile), savename) print 'Savename: ', savename_full # delete older version of the figure if existing if File.Exists(savename_full): File.Delete(savename_full) print 'Deleted older figure: ', savename_full # start the data display script as an external application app = Process() app.StartInfo.FileName = SCRIPT app.StartInfo.Arguments = params app.Start() # waits until the python figure was closed app.WaitForExit() if show_fig_result: print 'Showing saved figure in ZEN.' if File.Exists(savename_full): plotfigure = Zen.Application.LoadImage(savename_full, False)
filePaths = IN[0] if not isinstance(filePaths, list): filePaths = [filePaths] run = IN[1] outList = [] openOptions = OpenOptions() # openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndPreserveWorksets openOptions.DetachFromCentralOption = DetachFromCentralOption.DetachAndDiscardWorksets openOptions.Audit = True saveAsOptions = SaveAsOptions() saveAsOptions.OverwriteExistingFile = True for f in filePaths: if File.Exists(f): try: modelPath = ModelPathUtils.ConvertUserVisiblePathToModelPath(f) if run: upgradeDoc = app.OpenDocumentFile(modelPath, openOptions) # upgradeDoc = DocumentManager.Instance.CurrentDBDocument title = upgradeDoc.Title p = upgradeDoc.PathName if p != f: upgradeDoc.SaveAs(f, saveAsOptions) p = upgradeDoc.PathName upgradeDoc.Close(False) else: upgradeDoc.Close() outList.append(p) else:
def SubmitButtonPressed(*args): global scriptDialog global integration_dialog try: submitScene = scriptDialog.GetValue("SubmitSceneBox") # Check if Integration options are valid if not integration_dialog.CheckIntegrationSanity(): return warnings = [] errors = [] # Check if max files exist. sceneFiles = StringUtils.FromSemicolonSeparatedString( scriptDialog.GetValue("SceneBox"), False) if not sceneFiles: errors.append("No 3dsmax file specified") for sceneFile in sceneFiles: if not File.Exists(sceneFile): errors.append("3dsmax file %s does not exist" % sceneFile) return elif not submitScene and PathUtils.IsPathLocal(sceneFile): warnings.append( "The scene file " + sceneFile + " is local and is not being submitted with the job, are you sure you want to continue?" ) # Check if path config file exists. pathConfigFile = scriptDialog.GetValue("PathConfigBox").strip() if pathConfigFile: if not File.Exists(pathConfigFile): errors.append("Path configuration file %s does not exist" % pathConfigFile) # Check if PreLoad script file exists. preLoadFile = scriptDialog.GetValue("PreLoadBox").strip() if preLoadFile: if not File.Exists(preLoadFile): errors.append("PreLoad MAXScript file %s does not exist" % preLoadFile) # Check if PostLoad script file exists. postLoadFile = scriptDialog.GetValue("PostLoadBox").strip() if postLoadFile: if not File.Exists(postLoadFile): errors.append("PostLoad MAXScript file %s does not exist" % postLoadFile) # Check if PreFrame script file exists. preFrameFile = scriptDialog.GetValue("PreFrameBox").strip() if preFrameFile: if not File.Exists(preFrameFile): errors.append("PreFrame MAXScript file %s does not exist" % preFrameFile) # Check if PostFrame script file exists. postFrameFile = scriptDialog.GetValue("PostFrameBox").strip() if postFrameFile: if not File.Exists(postFrameFile): errors.append("PostFrame MAXScript file %s does not exist" % postFrameFile) # Check if a valid frame range has been specified. frames = scriptDialog.GetValue("FramesBox") if scriptDialog.GetValue("DBRModeBox") != "Disabled": frameArray = FrameUtils.Parse(frames) if len(frameArray) != 1: errors.append( "Please specify a single frame for distributed rendering in the Frame List." ) elif not FrameUtils.FrameRangeValid(frames): errors.append( "Please specify a valid single frame for distributed rendering in the Frame List." ) frames = "0-" + str(scriptDialog.GetValue("DBRServersBox") - 1) else: if not FrameUtils.FrameRangeValid(frames): errors.append("Frame range %s is not valid" % frames) # If using 'select GPU device Ids' then check device Id syntax is valid if scriptDialog.GetValue( "GPUsPerTaskBox") == 0 and scriptDialog.GetValue( "GPUsSelectDevicesBox"): regex = re.compile("^(\d{1,2}(,\d{1,2})*)?$") validSyntax = regex.match( scriptDialog.GetValue("GPUsSelectDevicesBox")) if not validSyntax: errors.append( "'Select GPU Devices' syntax is invalid!\nTrailing 'commas' if present, should be removed.\nValid Examples: 0 or 2 or 0,1,2 or 0,3,4 etc" ) # Check if concurrent threads > 1 if scriptDialog.GetValue("ConcurrentTasksBox") > 1: errors.append( "If using 'Select GPU Devices', then 'Concurrent Tasks' must be set to 1" ) if errors: scriptDialog.ShowMessageBox( "The following errors were encountered:\n\n%s\n\nPlease resolve these issues and submit again.\n" % ("\n\n".join(errors)), "Errors") return if warnings: result = scriptDialog.ShowMessageBox( "Warnings:\n\n%s\n\nDo you still want to continue?" % ("\n\n".join(warnings)), "Warnings", ("Yes", "No")) if result == "No": return successes = 0 failures = 0 # Submit each scene file separately. for sceneFile in sceneFiles: jobName = scriptDialog.GetValue("NameBox") if len(sceneFiles) > 1: jobName = jobName + " [" + Path.GetFileName(sceneFile) + "]" # Create job info file. jobInfoFilename = Path.Combine(ClientUtils.GetDeadlineTempPath(), "max_job_info.job") writer = StreamWriter(jobInfoFilename, False, Encoding.Unicode) writer.WriteLine("Plugin=3dsmax") writer.WriteLine("Name=%s" % jobName) writer.WriteLine("Comment=%s" % scriptDialog.GetValue("CommentBox")) writer.WriteLine("Department=%s" % scriptDialog.GetValue("DepartmentBox")) writer.WriteLine("Pool=%s" % scriptDialog.GetValue("PoolBox")) writer.WriteLine("SecondaryPool=%s" % scriptDialog.GetValue("SecondaryPoolBox")) writer.WriteLine("Group=%s" % scriptDialog.GetValue("GroupBox")) writer.WriteLine("Priority=%s" % scriptDialog.GetValue("PriorityBox")) writer.WriteLine("TaskTimeoutMinutes=%s" % scriptDialog.GetValue("TaskTimeoutBox")) writer.WriteLine("EnableAutoTimeout=%s" % scriptDialog.GetValue("AutoTimeoutBox")) writer.WriteLine("ConcurrentTasks=%s" % scriptDialog.GetValue("ConcurrentTasksBox")) writer.WriteLine("LimitConcurrentTasksToNumberOfCpus=%s" % scriptDialog.GetValue("LimitConcurrentTasksBox")) writer.WriteLine("MachineLimit=%s" % scriptDialog.GetValue("MachineLimitBox")) if scriptDialog.GetValue("IsBlacklistBox"): writer.WriteLine("Blacklist=%s" % scriptDialog.GetValue("MachineListBox")) else: writer.WriteLine("Whitelist=%s" % scriptDialog.GetValue("MachineListBox")) writer.WriteLine("LimitGroups=%s" % scriptDialog.GetValue("LimitGroupBox")) writer.WriteLine("JobDependencies=%s" % scriptDialog.GetValue("DependencyBox")) writer.WriteLine("OnJobComplete=%s" % scriptDialog.GetValue("OnJobCompleteBox")) if scriptDialog.GetValue("SubmitSuspendedBox"): writer.WriteLine("InitialStatus=Suspended") writer.WriteLine("Frames=%s" % frames) if scriptDialog.GetValue("DBRModeBox") == "Disabled": writer.WriteLine("ChunkSize=%s" % scriptDialog.GetValue("ChunkSizeBox")) # Integration extraKVPIndex = 0 groupBatch = False if integration_dialog.IntegrationProcessingRequested(): extraKVPIndex = integration_dialog.WriteIntegrationInfo( writer, extraKVPIndex) groupBatch = groupBatch or integration_dialog.IntegrationGroupBatchRequested( ) if groupBatch: writer.WriteLine("BatchName=%s\n" % jobName) writer.Close() # Create plugin info file. pluginInfoFilename = Path.Combine( ClientUtils.GetDeadlineTempPath(), "max_plugin_info.job") writer = StreamWriter(pluginInfoFilename, False, Encoding.Unicode) writer.WriteLine("Version=%s" % scriptDialog.GetValue("VersionBox")) writer.WriteLine("IsMaxDesign=%s" % scriptDialog.GetValue("IsMaxDesignBox")) if int(scriptDialog.GetValue("VersionBox")) < 2014: writer.WriteLine("MaxVersionToForce=%s" % scriptDialog.GetValue("BuildBox")) writer.WriteLine("MaxVersionToForce0=None") writer.WriteLine("MaxVersionToForce1=32bit") writer.WriteLine("MaxVersionToForce2=64bit") writer.WriteLine("UseSlaveMode=%d" % (not scriptDialog.GetValue("WorkstationModeBox"))) if scriptDialog.GetValue("WorkstationModeBox"): writer.WriteLine("UseSilentMode=%s" % (scriptDialog.GetValue("SilentModeBox"))) else: writer.WriteLine("UseSilentMode=False") writer.WriteLine("ShowFrameBuffer=%s" % scriptDialog.GetValue("ShowVfbBox")) writer.WriteLine("RemovePadding=%s" % scriptDialog.GetValue("RemovePaddingBox")) writer.WriteLine("RestartRendererMode=%s" % scriptDialog.GetValue("RestartRendererBox")) writer.WriteLine( "IgnoreMissingExternalFiles=%s" % scriptDialog.GetValue("IgnoreMissingExternalFilesBox")) writer.WriteLine("IgnoreMissingUVWs=%s" % scriptDialog.GetValue("IgnoreMissingUVWsBox")) writer.WriteLine("IgnoreMissingXREFs=%s" % scriptDialog.GetValue("IgnoreMissingXREFsBox")) writer.WriteLine("IgnoreMissingDLLs=%s" % scriptDialog.GetValue("IgnoreMissingDLLsBox")) writer.WriteLine("LocalRendering=%s" % scriptDialog.GetValue("LocalRenderingBox")) writer.WriteLine("DisableMultipass=%s" % scriptDialog.GetValue("DisableMultipassBox")) writer.WriteLine("OneCpuPerTask=%s" % scriptDialog.GetValue("OneCpuPerTaskBox")) if pathConfigFile: writer.WriteLine("PathConfigFile=%s" % Path.GetFileName(pathConfigFile)) writer.WriteLine("MergePathConfigFile=%s" % scriptDialog.GetValue("MergePathConfigBox")) if preLoadFile: writer.WriteLine("PreLoadScript=%s" % Path.GetFileName(preLoadFile)) if postLoadFile: writer.WriteLine("PostLoadScript=%s" % Path.GetFileName(postLoadFile)) if preFrameFile: writer.WriteLine("PreFrameScript=%s" % Path.GetFileName(preFrameFile)) if postFrameFile: writer.WriteLine("PostFrameScript=%s" % Path.GetFileName(postFrameFile)) pluginIniOverride = scriptDialog.GetValue("PluginIniBox").strip() if pluginIniOverride: writer.WriteLine("OverridePluginIni=%s" % pluginIniOverride) writer.WriteLine("GammaCorrection=%s" % scriptDialog.GetValue("GammaCorrectionBox")) writer.WriteLine("GammaInput=%s" % scriptDialog.GetValue("GammaInputBox")) writer.WriteLine("GammaOutput=%s" % scriptDialog.GetValue("GammaOutputBox")) if int(scriptDialog.GetValue("VersionBox")) >= 2013: if scriptDialog.GetValue("OverrideLanguageBox"): writer.WriteLine("Language=%s" % scriptDialog.GetValue("LanguageBox")) else: writer.WriteLine("Language=Default") camera = scriptDialog.GetValue("CameraBox") if camera: writer.WriteLine("Camera=%s" % camera) writer.WriteLine("Camera0=") writer.WriteLine("Camera1=%s" % camera) if not submitScene: writer.WriteLine("SceneFile=%s" % sceneFile) if scriptDialog.GetValue("DBRModeBox") != "Disabled": if scriptDialog.GetValue("DBRModeBox") == "VRay DBR": writer.WriteLine("VRayDBRJob=True") elif scriptDialog.GetValue( "DBRModeBox") == "Mental Ray Satellite": writer.WriteLine("MentalRayDBRJob=True") elif scriptDialog.GetValue("DBRModeBox") == "VRay RT DBR": writer.WriteLine("VRayRtDBRJob=True") writer.WriteLine("DBRJobFrame=%s" % scriptDialog.GetValue("FramesBox")) if scriptDialog.GetValue("DBRModeBox") == "Disabled": writer.WriteLine("GPUsPerTask=%s" % scriptDialog.GetValue("GPUsPerTaskBox")) writer.WriteLine("GPUsSelectDevices=%s" % scriptDialog.GetValue("GPUsSelectDevicesBox")) writer.Close() # Setup the command line arguments. arguments = [jobInfoFilename, pluginInfoFilename] if scriptDialog.GetValue("SubmitSceneBox"): arguments.append(sceneFile) if pathConfigFile: arguments.append(pathConfigFile) if preLoadFile: arguments.append(preLoadFile) if postLoadFile: arguments.append(postLoadFile) if preFrameFile: arguments.append(preFrameFile) if postFrameFile: arguments.append(postFrameFile) if len(sceneFiles) == 1: results = ClientUtils.ExecuteCommandAndGetOutput(arguments) scriptDialog.ShowMessageBox(results, "Submission Results") else: # Now submit the job. exitCode = ClientUtils.ExecuteCommand(arguments) if exitCode == 0: successes += 1 else: failures += 1 if len(sceneFiles) > 1: scriptDialog.ShowMessageBox( "Jobs submitted successfully: %d\nJobs not submitted: %d" % (successes, failures), "Submission Results") except: scriptDialog.ShowMessageBox(traceback.format_exc(), "")
def f3(arg0, arg1, arg2, *arg3): return "same## %s %s %s %s" % (arg0, arg1, arg2, arg3) if is_cli: from iptest.process_util import run_csc run_csc("/nologo /target:library /out:sbs_library.dll sbs_library.cs") import clr clr.AddReference("sbs_library") from SbsTest import C o = C() g1 = o.M1 g2 = o.M2 g3 = o.M3 #for peverify runs from System.IO import Path, File, Directory if File.Exists(Path.GetTempPath() + r"\sbs_library.dll"): try: File.Delete(Path.GetTempPath() + r"\sbs_library.dll") except: pass if not File.Exists(Path.GetTempPath() + r"\sbs_library.dll"): File.Copy(Directory.GetCurrentDirectory() + r"\sbs_library.dll", Path.GetTempPath() + r"\sbs_library.dll") else: g1 = f1 g2 = f2 g3 = f3 # combinations choices = [(), (0,), (1,), (2,), (3,), (0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3), (0, 1, 2), (0, 1, 3), (0, 2, 3), (1, 2, 3), (0, 1, 2, 3) ]
def FileExists(filePath): return File.Exists(filePath)
# this depends on the actual CZIAS and the import of the CSV table in python parameter2display = 'ObjectNumber' params = ' -f ' + csvfile + ' -w 96' + ' -p ' + parameter2display + ' -sp False' # start the data display script as an external application app = Process() app.StartInfo.FileName = pythonexe app.StartInfo.Arguments = script + params app.Start() app.WaitForExit() savename_all = Path.Combine( outputpath, Path.GetFileNameWithoutExtension(savename) + '_Single_HM_all.png') savename_single = Path.Combine( outputpath, Path.GetFileNameWithoutExtension(savename) + '_Single_HM_' + parameter2display + '.png') print 'Showing saved figure in ZEN.' if File.Exists(savename_all): plotfigure1 = Zen.Application.LoadImage(savename_all, False) plotfigure2 = Zen.Application.LoadImage(savename_single, False) Zen.Application.Documents.Add(plotfigure1) Zen.Application.Documents.Add(plotfigure2) else: print 'Saved figure not found.' print 'Done.'