def run(self, Mml2vgmInfo, index): #設定値の読み込み Mml2vgmInfo.loadSetting() #初回のみ(設定値が無いときのみ)mucom88.exeの場所をユーザーに問い合わせ、設定値として保存する mc = Mml2vgmInfo.getSettingValue("mucom88path") if mc is None: mc = Mml2vgmInfo.fileSelect( "mucom88.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)") if not Mml2vgmInfo.confirm("mucom88.exeの場所は以下でよろしいですか\r\n" + mc): return None Mml2vgmInfo.setSettingValue("mucom88path", mc) Mml2vgmInfo.saveSetting() #念のため if mc is None or mc == "": Mml2vgmInfo.msg("mucom88.exeを指定してください") return None #ファイル選択 muc = Mml2vgmInfo.fileSelect("mucファイルの選択") if muc is None: return None #ファイル情報の整理 #Mml2vgmInfo.msgLogWindow(muc) wp = Path.GetDirectoryName(muc) #Mml2vgmInfo.msgLogWindow(wp) Directory.SetCurrentDirectory(wp) #mucom88.exeでコンパイルを行いmubファイルを生成する args = "-c " + muc Mml2vgmInfo.runCommand(mc, args, True) #mubファイルが出来たかチェック(mucom88.exeはコンパイルが成功するとmucom88.mubというファイルができる) mm = Path.Combine(wp, "mucom88.mub") #Mml2vgmInfo.msgLogWindow(mm) if not File.Exists(mm): return None #mucom88.mubを本来のファイル名にリネーム mub = Path.Combine(wp, Path.GetFileNameWithoutExtension(muc) + ".mub") #Mml2vgmInfo.msgLogWindow(mub) File.Delete(mub) File.Move(mm, mub) #mucom88.exeで演奏を開始 Mml2vgmInfo.runCommand(mc, mub, False) #戻り値を生成(何もしないけど念のため) si = ScriptInfo() si.responseMessage = "" return si
def deploy_file(filename): "Copies a file to the bin\Debug folder, replacing any file of the same name already there." new_filename = build_dir + "\\" + filename[filename.rfind("\\") + 1 :] try: if File.Exists(new_filename): File.Delete(new_filename) except: # don't worry about replacing read-only files that we can't delete pass else: File.Copy(filename, new_filename)
def replaceData(books): ERROR_LEVEL = 0 if not crVersion(): return # ComicRack version ok? s = File.ReadAllLines(globalvars.DATFILE) if not s[0].startswith('#@ VERSION'): MessageBox.Show( 'Your configuration needs conversion.\nPlease use the configurator first.', 'Data Manager %s' % globalvars.VERSION) return ini = dmutils.iniFile(globalvars.USERINI) if ini.read('ShowStartupDialog') == 'False': pass else: theForm = startupForm() theForm.ShowDialog() theForm.Dispose() if theForm.DialogResult == DialogResult.Yes: # closed with Yes button pass elif theForm.DialogResult == DialogResult.Cancel: # closed with window close button return elif theForm.DialogResult == DialogResult.No: # closed with No button return elif theForm.DialogResult == DialogResult.Retry: # closed with configure button dmConfig() return try: # delete temporary files from last data manager run File.Delete(globalvars.TMPFILE) File.Delete(globalvars.ERRFILE) File.Delete(globalvars.LOGFILE) except Exception, err: MessageBox.Show( 'One of the temporary files of the Data Manager could not be deleted.\nPlease restart ComicRack.' ) return
def SaveFamiliesOfCategory(doc, run): # Function to save the families of the categories specified in the project information # of the document elements = [] familyList = [] docPath = doc.PathName docPath = re.findall(r"^.*\\", docPath)[0] saveAsOptions = SaveAsOptions() saveAsOptions.OverwriteExistingFile = True category = doc.ProjectInformation.LookupParameter("Author").AsString() if not category: return "No category set to Author parameter" else: categories = doc.Settings.Categories category = categories.get_Item(category) collector = FilteredElementCollector(doc).OfClass(Family) for family in collector: if family.FamilyCategoryId.ToString() == category.Id.ToString(): elements.append(family) for element in elements: eName = element.Name famDirectory = docPath + category.Name + "\\" famPath = famDirectory + eName + ".rfa" famPathBackup = famDirectory + eName + ".0001.rfa" if run: if not Directory.Exists(famDirectory): Directory.CreateDirectory(famDirectory) if File.Exists(famPath): File.Delete(famPath) famDoc = doc.EditFamily(element) famDoc.SaveAs(famPath, saveAsOptions) famDoc.Close(False) familyList.append(famPath) if File.Exists(famPathBackup): File.Delete(famPathBackup) else: familyList.append(famPath) return familyList
def setUp(): ''' Sets up the DLLs directory. ''' #if it exists, we cannot continue because we will #not have the correct permissions to move/remove the #DLLs directory if Directory.Exists(DLLS_DIR): print "ERROR - cannot test anything with a pre-existing DLLs directory" raise Exception( "Cannot move/delete DLLs which is being used by this process!") Directory.CreateDirectory(DLLS_DIR) File.Copy(IP_DIR + "\\IronPython.dll", DLLS_DIR + "\\IronPython.dll") Directory.SetCurrentDirectory(DLLS_DIR) #create a number of "normal" assemblies okAssemblies(50) #create 5 assemblies in the fooFIVE namespace with nearly #identical contents dupAssemblies(5) #recreate the sys module overrideNative() #ensure corrupt DLLs cannot work corruptDLL() #ensure unmanaged DLLs don't break it unmanagedDLL() #create an exe and a DLL competing for the same #namespace dllVsExe() #create an exe in it's own namespace exeOnly() #create a DLL that's really a *.txt and #create a *.txt that's really a DLL textFiles() #creates "unique" DLL names that should be loadable #by IP uniqueDLLNames() #cleanup after ourselves File.Delete(DLLS_DIR + "\\IronPython.dll")
def ExecuteDynamoScript(uiapp, dynamoScriptFilePath, showUI=False): externalCommandResult = None # NOTE: The temporary copy of the Dynamo script file is created in same folder as the original so # that any relative paths in the script won't break. tempDynamoScriptFilePath = Path.Combine( Path.GetDirectoryName(dynamoScriptFilePath), Path.GetRandomFileName()) File.Copy(dynamoScriptFilePath, tempDynamoScriptFilePath) try: SetDynamoScriptRunType(tempDynamoScriptFilePath, DYNAMO_RUNTYPE_AUTOMATIC) externalCommandResult = ExecuteDynamoScriptInternal( uiapp, tempDynamoScriptFilePath, showUI) finally: File.Delete(tempDynamoScriptFilePath) return externalCommandResult
def removeczi(removedir): # check directory for files to export czi2remove = Directory.GetFiles(removedir, '*.czi') print 'Number of files to be removed: ', len(czi2remove) for czi in czi2remove: # delete the splitted CZI files when option was checked try: File.Delete(czi) print 'Removed: ', czi except: print 'Could not remove: ', czi print 'Removal complete.'
def testFileStream(): print 'Verifying FileStream against MemoryStream' stopwatch = Stopwatch.StartNew() for i in xrange(128): m = MemoryStream() file = Path.GetTempFileName() f = FileStream(file, FileMode.Open) try: streams = [m, f] randomOperations(128, streams) finally: f.Close() File.Delete(file) stopwatch.Stop() print '%s' % stopwatch.Elapsed
def ConsolidateSnapshotData(dataExportFolderPath, output): try: snapshotDataFilePath = GetSnapshotDataFilePath(dataExportFolderPath) temporarySnapshotDataFilePath = GetTemporarySnapshotDataFilePath(dataExportFolderPath) if File.Exists(snapshotDataFilePath): if File.Exists(temporarySnapshotDataFilePath): File.Delete(temporarySnapshotDataFilePath) elif File.Exists(temporarySnapshotDataFilePath): File.Move(temporarySnapshotDataFilePath, snapshotDataFilePath) else: output() output("WARNING: could not find snapshot data file in snapshot data folder:") output() output("\t" + dataExportFolderPath) except Exception, e: output() output("WARNING: failed to properly consolidate the snapshot data in folder:") output() output("\t" + dataExportFolderPath) exception_util.LogOutputErrorDetails(e, output)
def cleanUp(): ''' Just removes the DLLs directory we created. ''' #the following while loop is necessary as #the Delete call fails (ipy.exe subprocess has #not really released some files yet). for i in xrange(5): threw = False for file in Directory.GetFiles(DLLS_DIR): if not file.endswith('IronPython.Wpf.dll'): try: File.Delete(file) except: print 'cannot delete', file threw = True pass if threw: from time import sleep sleep(1) continue else: break
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) Zen.Application.Documents.Add(plotfigure)
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(): ''' Returns stdout and stderr output for a console test. ''' #On some platforms 'ip_session.log' is not immediately created after #calling the 'close' method of the file object writing to 'ip_session.log'. #Give it a few seconds to catch up. sleep(1) for i in xrange(5): if "ip_session.log" in nt.listdir(nt.getcwd()):
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 to_str(l): return [str(x) for x in l]
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 to_str(l): return [str(x) for x in l]
famDirectory = docPath + category.Name + "\\" if saveBool: if not Directory.Exists(famDirectory): Directory.CreateDirectory(famDirectory) for element in elements: eName = element.Name famPath = famDirectory + eName + ".rfa" famPathBackup = famDirectory + eName + ".0001.rfa" if saveBool: try: if not Directory.Exists(famDirectory): Directory.CreateDirectory(famDirectory) except: outList.append("Could not create directory") try: if File.Exists(famPath): File.Delete(famPath) famDoc = doc.EditFamily(element) famDoc.SaveAs(famPath) famDoc.Close(False) outList.append(famPath) if File.Exists(famPathBackup): File.Delete(famPathBackup) except: outList.append("Export Error: " + eName) else: outList.append("Test: " + famPath) OUT = outList
def onClick(sender, args): if Directory.Exists(childMenuItem.Tag): for fileName in Directory.EnumerateFiles(childMenuItem.Tag): File.Delete(fileName)
def deleteFilesFromDirectoryWithExtension(dir, file_extension): files = Directory.GetFileSystemEntries(dir) for file in files: if file.EndsWith(file_extension): print "deleting %s" % file File.Delete(file)
# create the name for the required TMP folder and the output OME-TIFF tmpfolder = Path.Combine(Path.GetDirectoryName(czifile), Path.GetFileNameWithoutExtension(czifile)) omefile = tmpfolder + '_PY.ome.tiff' print 'TMP Folder : ', tmpfolder print 'OME-TIFF to be created : ', omefile # define parameters and run bioformats2raw bf2raw_params = '"' + czifile + '" ' + '"' + tmpfolder + '"' + ' --resolutions ' + str( resolutions) + ' --compression=raw' print 'Command String : ', bf2raw_params done1 = run_tool(bf2raw, bf2raw_params) print 'Done with conversion to RAW.', done1 # # define parameters and run raw2ometiff raw2ome_params = '"' + tmpfolder + '" ' + '"' + omefile + '"' + ' --compression=' + compression print 'Command String : ', raw2ome_params done2 = run_tool(raw2ome, raw2ome_params) print 'Done with conversion to pyramidal OME-TIFF', done2 # delete bfmemo file and TMP folder if cleanup: print 'Cleaning up ...' delname = Path.Combine(czidir, '.' + cziname + '.bfmemo') print 'Deleting : ', delname File.Delete(delname) print 'Deleting Folder : ', tmpfolder Directory.Delete(tmpfolder, True) print 'Done.'
discardWorksetsOnDetach, processDocument, output) else: result = revit_script_util.RunDocumentAction( uiapp, openInUI, centralFilePath, processDocument, output) except Exception, e: aborted = True snapshotError = exception_util.GetExceptionDetails(e) raise finally: if openCreateNewLocal and deleteLocalAfter: try: if File.Exists(localFilePath): output() output("Deleting local file...") File.Delete(localFilePath) output() output("Local file deleted.") except Exception, e: output() output("WARNING: failed to delete the local file!") if enableDataExport: snapshotEndTime = time_util.GetDateTimeNow() snapshotData = snapshot_data_exporter.ExportSnapshotData( sessionId, centralFilePath, snapshotStartTime, snapshotEndTime, dataExportFolderPath, revitJournalFilePath, snapshotError) snapshot_data_util.ConsolidateSnapshotData( dataExportFolderPath, output)
def RunBatchTaskScript(scriptFilePath): aborted = False uiapp = revit_session.GetSessionUIApplication() sessionId = revit_script_util.GetSessionId() centralFilePath = revit_script_util.GetRevitFilePath() openInUI = revit_script_util.GetOpenInUI() enableDataExport = revit_script_util.GetEnableDataExport() dataExportFolderPath = revit_script_util.GetDataExportFolderPath() showMessageBoxOnTaskError = revit_script_util.GetShowMessageBoxOnTaskError( ) centralFileOpenOption = revit_script_util.GetCentralFileOpenOption() deleteLocalAfter = revit_script_util.GetDeleteLocalAfter() discardWorksetsOnDetach = revit_script_util.GetDiscardWorksetsOnDetach() progressNumber = revit_script_util.GetProgressNumber() progressMax = revit_script_util.GetProgressMax() output = revit_script_util.Output if enableDataExport and not path_util.DirectoryExists( dataExportFolderPath): output() output("ERROR: data export folder does not exist!") if not str.IsNullOrWhiteSpace(dataExportFolderPath): output() output("\t" + dataExportFolderPath) aborted = True elif not path_util.FileExists(centralFilePath): output() output("ERROR: Revit project file does not exist!") if not str.IsNullOrWhiteSpace(centralFilePath): output() output("\t" + centralFilePath) aborted = True else: if enableDataExport: snapshotStartTime = time_util.GetDateTimeNow() snapshotError = None snapshotEndTime = None revitJournalFilePath = uiapp.Application.RecordingJournalFilename snapshotData = snapshot_data_exporter.ExportTemporarySnapshotData( sessionId, centralFilePath, snapshotStartTime, snapshotEndTime, dataExportFolderPath, revitJournalFilePath, snapshotError) localFilePath = None openCreateNewLocal = False # default is False because the file may not be a workshared Central file. isCentralModel = False isLocalModel = False try: output() output("Processing file (" + str(progressNumber) + " of " + str(progressMax) + "): " + centralFilePath) if revit_file_util.IsWorkshared(centralFilePath): if revit_file_util.IsLocalModel(centralFilePath): output() output( "WARNING: the file being processed appears to be a Workshared Local file!" ) isLocalModel = True if revit_file_util.IsCentralModel(centralFilePath): output() output("The file is a Central Model file.") isCentralModel = True if centralFileOpenOption == BatchRvt.CentralFileOpenOption.CreateNewLocal: openCreateNewLocal = True elif path_util.HasFileExtension(centralFilePath, ".rfa"): output() output("The file is a Family file.") else: output() output("The file is a Non-workshared file.") if enableDataExport: output() output("Export folder is: " + dataExportFolderPath) def processDocument(doc): revit_script_util.SetScriptDocument(doc) def executeTaskScript(): success = False output() output("Task script operation started.") if path_util.HasFileExtension( scriptFilePath, script_util.DYNAMO_SCRIPT_FILE_EXTENSION): if revit_dynamo.IsDynamoRevitModuleLoaded(): revit_dynamo.ExecuteDynamoScript(uiapp, scriptFilePath, showUI=False) success = True else: success = False output() output(revit_dynamo_error. DYNAMO_REVIT_MODULE_NOT_FOUND_ERROR_MESSAGE) else: script_util.ExecuteScript(scriptFilePath) success = True if success: output() output("Task script operation completed.") else: output() output( "ERROR: An error occurred while executing the task script! Operation aborted." ) return result = script_host_error.WithErrorHandling( executeTaskScript, "ERROR: An error occurred while executing the task script! Operation aborted.", output, showMessageBoxOnTaskError) return result result = None activeDoc = None #revit_script_util.GetActiveDocument(uiapp) if activeDoc is not None: result = processDocument(activeDoc) else: if openCreateNewLocal: revitVersion = RevitVersion.GetSupportedRevitVersion( revit_session.GetSessionRevitVersionNumber()) localFilePath = RevitVersion.GetRevitLocalFilePath( revitVersion, centralFilePath) try: if File.Exists(localFilePath): output() output("Deleting existing local file...") File.Delete(localFilePath) output() output("Local file deleted.") except Exception, e: output() output("WARNING: failed to delete the local file!") path_util.CreateDirectoryForFilePath(localFilePath) result = revit_script_util.RunNewLocalDocumentAction( uiapp, openInUI, centralFilePath, localFilePath, processDocument, output) elif isCentralModel or isLocalModel: result = revit_script_util.RunDetachedDocumentAction( uiapp, openInUI, centralFilePath, discardWorksetsOnDetach, processDocument, output) else: