def overrideNative(): ''' Tries to override the native IP sys module. ''' #create the "sys" C# file file_name = Directory.GetCurrentDirectory() + "\\sys.cs" file = open(file_name, "w") print >> file, cs_native file.close() #compile the assembly compileAssembly(file_name) #create the "re" C# file file_name = Directory.GetCurrentDirectory() + "\\re.cs" file = open(file_name, "w") print >> file, cs_native_re file.close() #compile the assembly compileAssembly(file_name)
def exeOnly(): ''' Creates an EXE in it's own namespace. ''' #create an EXE C# file file_name = Directory.GetCurrentDirectory() + "\\fooEXEONLY.cs" file = open(file_name, "w") print >> file, cs_ipy % ("EXEONLY", 100) file.close() #create the exe compileExe(file_name)
def dircheck(basefolder): # check if the destination basefolder exists base_exists = Directory.Exists(basefolder) if base_exists: # specify the desired output format for the folder, e.g. 2017-08-08_17-47-41 format = '%Y-%m-%d_%H-%M-%S' # create the new directory newdir = createfolder(basefolder, formatstring=format) print 'Created new directory: ', newdir return newdir
def run(self, Mml2vgmInfo, index): #設定値の読み込み Mml2vgmInfo.loadSetting() #初回のみ(設定値が無いときのみ)sox.exeの場所をユーザーに問い合わせ、設定値として保存する gt = Mml2vgmInfo.getSettingValue("soxpath") if gt is None: gt = Mml2vgmInfo.fileSelect( "sox.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)") if not Mml2vgmInfo.confirm("sox.exeの場所は以下でよろしいですか\r\n" + gt): return None Mml2vgmInfo.setSettingValue("soxpath", gt) Mml2vgmInfo.saveSetting() #念のため if gt is None or gt == "": Mml2vgmInfo.msg("sox.exeを指定してください") return None #ファイル情報の整理 for fnf in Mml2vgmInfo.fileNamesFull: ext = Path.GetExtension(fnf) bas = Path.GetFileNameWithoutExtension(fnf) wp = Path.GetDirectoryName(fnf) Directory.SetCurrentDirectory(wp) si = ScriptInfo() argList = [ "--i \"{0}{1}\"", "\"{0}{1}\" -r 8000 -b 8 -c 1 \"{0}_8k{1}\"", "\"{0}{1}\" -r 14000 -b 8 -c 1 \"{0}_14k{1}\"", "\"{0}{1}\" -r 16000 -b 8 -c 1 \"{0}_16k{1}\"", "\"{0}{1}\" -r 18500 -b 8 -c 1 \"{0}_18500{1}\"", "\"{0}{1}\" -b 16 -r 14000 -e signed-integer -c 1 \"{0}_16b_14k{1}\"", "\"{0}{1}\" -b 16 -r 16000 -e signed-integer -c 1 \"{0}_16b_16k{1}\"", "\"{0}{1}\" -b 16 -r 18500 -e signed-integer -c 1 \"{0}_16b_18500{1}\"", "\"{0}{1}\" -n trim 0 1.5 noiseprof \"{0}.noise-profile\"", "\"{0}{1}\" \"{0}_cleaned{1}\" noisered \"{0}.noise-profile\" 0.2 " ] args = argList[index].format(bas, ext) ret = Mml2vgmInfo.runCommand(gt, args, True) if ret != "": Mml2vgmInfo.msg(ret) else: if index != 0: Mml2vgmInfo.msg("success") Mml2vgmInfo.refreshFolderTreeView() return si
def initialize_directory(pth_root, init_z_buf_dir, debug=False): print("Initializing save path: {}".format(pth_root)) dir_cfg = {} if not Directory.Exists(pth_root): raise ( "!!! ROOT_SAVE_PATH does not exist.\nSet a valid path at the top of this script.\n{}" .format(pth_root)) success = False for char in 'abcdefghijkmnpqrstuvwxyz': dstmp = datetime.date.today().strftime('%y%m%d') if debug: dstmp = "_debug_" + dstmp dir_cfg['pth_save'] = os.path.join( pth_root, '{}{}_{}'.format(dstmp, char, os.path.splitext(sc.doc.Name)[0])) if not Directory.Exists(dir_cfg['pth_save']): Directory.CreateDirectory(dir_cfg['pth_save']) success = True break if not success: print( "!!!! failed to initalize save path.\nClear out the following path by hand.\n{}" .format(pth_root)) exit() dir_cfg['pth_save_render'] = os.path.join(dir_cfg['pth_save'], 'rndr') dir_cfg['pth_save_line'] = os.path.join(dir_cfg['pth_save'], 'line') dir_cfg['pth_save_depth'] = os.path.join(dir_cfg['pth_save'], 'dpth') Directory.CreateDirectory(dir_cfg['pth_save_render']) Directory.CreateDirectory(dir_cfg['pth_save_line']) if init_z_buf_dir: Directory.CreateDirectory(dir_cfg['pth_save_depth']) return dir_cfg
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 __getFolderItems(self, picturesOnly, count): if picturesOnly: list = [] else: def IsSpecialFolder(dir): d = Path.GetFileName(dir).lower() return d.startswith('_vti_') or d.startswith( 'app_') or d.startswith('bin') or d.startswith('aspnet_') list = [ GetFolder(d) for d in Directory.GetDirectories(self.path)[:count] if not IsSpecialFolder(d) ] count -= len(list) if count > 0: list += [ GetPicture(p) for p in Directory.GetFiles(self.path, '*.jpg')[:count] ] return list
def createAssembly(file_id, namespace_id, bar_num, default_filename="foo"): ''' Helper function creates a single "foo" assembly. Returns the file_name. ''' #create the C# file file_name = Directory.GetCurrentDirectory( ) + "\\" + default_filename + str(file_id) + ".cs" file = open(file_name, "w") print >> file, cs_ipy % (str(namespace_id), bar_num) file.close() #create the assembly compileAssembly(file_name)
def _GetDoc(docPath): docMgr = app.Modules.Get("Document Manager") doc = docMgr.DocumentList.Fetch(docPath) # make unique dir and file under the application temprorary dir dir = Path.Combine(DssPath.GetTemporaryDirectory(), Path.GetRandomFileName()) Directory.CreateDirectory(dir) filename = Path.Combine(dir, doc.Name) docMgr.DocumentList.Export(doc, filename, True) return filename
def unzip(path, parent): if sys.platform == 'cli': out_dir = str(tuple(ZipFile.OpenRead(path).Entries)[0]) if dir_exists(out_dir): Directory.Delete(out_dir, True) ZipFile.ExtractToDirectory(path, parent) if 'latest' in path: return out_dir else: with zipfile.ZipFile(item) as zf: zf.extractall() if 'latest' in path: return zf.filelist[0].filename return None
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). while 1: try: Directory.Delete(DLLS_DIR, True) break except: from time import sleep sleep(1) continue
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 textFiles(): ''' Creates *.txt files. One is actually a text file and the other is a DLL in disguise ''' #create a fake DLL file_name = Directory.GetCurrentDirectory() + "\\fooGARBAGE.dll" file = open(file_name, "w") print >> file, garbage file.close() #create a real DLL and give it the *.txt extension createAssembly("TXTDLL", "TXTDLL", 7) File.Move("fooTXTDLL.dll", "fooTXTDLL.txt")
def run(self, Mml2vgmInfo, index): #設定値の読み込み Mml2vgmInfo.loadSetting() #初回のみ(設定値が無いときのみ)git.exeの場所をユーザーに問い合わせ、設定値として保存する gt = Mml2vgmInfo.getSettingValue("gitpath") if gt is None: gt = Mml2vgmInfo.fileSelect( "git.exeを選択してください(この選択内容は設定値として保存され次回からの問い合わせはありません)") if not Mml2vgmInfo.confirm("git.exeの場所は以下でよろしいですか\r\n" + gt): return None Mml2vgmInfo.setSettingValue("gitpath", gt) Mml2vgmInfo.saveSetting() #念のため if gt is None or gt == "": Mml2vgmInfo.msg("git.exeを指定してください") return None si = ScriptInfo() commitMsg = "" if index == 1: #git コミット commitMsg = Mml2vgmInfo.inputBox("コミット時のコメントを入力してください") if commitMsg == "": return si #ファイル情報の整理 for fnf in Mml2vgmInfo.fileNamesFull: wp = Path.GetDirectoryName(fnf) Directory.SetCurrentDirectory(wp) if index == 0: #git ステージング args = "add " + fnf ret = Mml2vgmInfo.runCommand(gt, args, True) if ret != "": Mml2vgmInfo.msg(ret) else: #git コミット args = "commit -m\"" + commitMsg + "\"" ret = Mml2vgmInfo.runCommand(gt, args, True) if ret != "": Mml2vgmInfo.msg(ret) return si
def main(): ''' Runs the test by spawning off another IP process which utilizes the newly created DLLs directory. ''' try: setUp() Directory.SetCurrentDirectory(ORIG_DIR) from iptest.process_util import launch_ironpython_changing_extensions ret_val = launch_ironpython_changing_extensions("dllsite.py", add=["-S"], additionalScriptParams=("OKtoRun",)) finally: cleanUp() exit(ret_val)
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 __import_legacy_settings(cls, legacy_dir, profile_dir): ''' See if there are any legacy settings at the given legacy location, and copy them to the given profile location, if that location doesn't exist. ''' if not File.Exists(cls.SETTINGS_FILE): Directory.CreateDirectory(profile_dir) settings_file = legacy_dir + r'\settings.dat' advanced_file = legacy_dir + r'\advanced.dat' geometry_file = legacy_dir + r'\geometry.dat' series_file = legacy_dir + r'\series.dat' if File.Exists(settings_file): File.Copy(settings_file, cls.SETTINGS_FILE, False) if File.Exists(advanced_file): File.Copy(advanced_file, cls.ADVANCED_FILE, False) if File.Exists(geometry_file): File.Copy(geometry_file, cls.GEOMETRY_FILE, False) if File.Exists(series_file): File.Copy(series_file, cls.SERIES_FILE, False)
def getFilesYoungerThan(dir, younger_than=0): if exists(dir): files = Directory.GetFiles(dir) date_to_check = DateTime.Parse( DateTime.Now.AddDays(-younger_than).ToString("yyyy.MM.dd")) files_of_age = [] for file in files: file = FileInfo(file) print file result = DateTime.Compare(file.CreationTime, date_to_check) if result < 0: relationship = "is earlier than %s" % date_to_check elif result == 0: relationship = "is the same time as %s" % date_to_check files_of_age.append(file) else: relationship = "is later than %s" % date_to_check files_of_age.append(file) print relationship return files_of_age
def recycleBin(): summary = printHeader("RECYCLE BIN") if WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole( WindowsBuiltInRole.Administrator): for drive in DriveInfo.GetDrives(): try: recycleDir = DirectoryInfo(drive.Name + "$Recycle.Bin\\") for dir in DirectoryInfo.EnumerateDirectories(recycleDir): fileList = DirectoryInfo.GetFiles(dir) summary += printSubheader("Directory: {0}".format( dir.FullName)) for file in fileList: name = file.FullName.split("\\")[-1] if name.startswith("$I"): info = open(file.FullName, "r").read() summary += "{0}\t{1}\n".format( name.replace("$I", "$R"), info[26::2]) except IOError: pass else: for drive in DriveInfo.GetDrives(): try: recycleDir = drive.Name + "$Recycle.Bin\\" user = WindowsIdentity.GetCurrent() fileList = Directory.GetFiles(recycleDir + user.Owner.ToString()) summary += printSubheader( "Directory: {0}".format(recycleDir + user.Owner.ToString())) for file in fileList: name = file.split("\\")[-1] if name.startswith("$I"): info = open(file, "r").read() summary += "{0}\t{1}\n".format( name.replace("$I", "$R"), info[26::2]) except IOError: pass print summary
def ModulesToAssembly(modules, name, code="", references=None, outputDirectory=None, inMemory=False): CompilerParams = Compiler.CompilerParameters() if outputDirectory is None: outputDirectory = Directory.GetCurrentDirectory() if not inMemory: CompilerParams.OutputAssembly = Path.Combine(outputDirectory, name + ".dll") CompilerParams.GenerateInMemory = False else: CompilerParams.GenerateInMemory = True CompilerParams.TreatWarningsAsErrors = False CompilerParams.GenerateExecutable = False modulesListCompiler = ';'.join(map(str, modules)) CompilerParams.CompilerOptions = "/addmodule:" + modulesListCompiler print(CompilerParams.CompilerOptions) for reference in references or []: CompilerParams.ReferencedAssemblies.Add(reference) provider = CSharpCodeProvider() compile = provider.CompileAssemblyFromSource(CompilerParams, code) if compile.Errors.HasErrors: for err in compile.Errors: print(err) raise Exception("Compile error(s)") if inMemory: return compile.CompiledAssembly return compile.PathToAssembly
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
def initialize_directory(pth_root, init_fill_dir, debug=False): print("Initializing save path: {}".format(pth_root)) dir_cfg = {} if not Directory.Exists(pth_root): big_problem( "!!! Path does not exist.\nSelect a valid folder.\n{}".format( pth_root)) filename = "unsavedfile" try: filename = os.path.splitext(sc.doc.Name)[0].lower().replace(" ", "_") except: pass success = False for char in 'abcdefghijkmnpqrstuvwxyz': dstmp = datetime.date.today().strftime('%y%m%d') dir_cfg['pth_save'] = os.path.join( pth_root, '{}{}-{}'.format(dstmp, char, filename)) if not Directory.Exists(dir_cfg['pth_save']): Directory.CreateDirectory(dir_cfg['pth_save']) success = True break if not success: big_problem( "!!!! failed to initalize save path.\nClear out the following path by hand.\n{}" .format(pth_root)) dir_cfg['pth_save_rndr'] = os.path.join(dir_cfg['pth_save'], 'rndr') dir_cfg['pth_save_line'] = os.path.join(dir_cfg['pth_save'], 'line') dir_cfg['pth_save_fill'] = os.path.join(dir_cfg['pth_save'], 'fill') Directory.CreateDirectory(dir_cfg['pth_save_rndr']) Directory.CreateDirectory(dir_cfg['pth_save_line']) if init_fill_dir: Directory.CreateDirectory(dir_cfg['pth_save_fill']) return dir_cfg
def DirectoryExists(folderPath): return Directory.Exists(folderPath)
def testDeleteFilesInDirectoryTwoDaysAndYounger(self): all_files = directoryListing.getFilesYoungerThan(self.temp_dir_path) files = directoryListing.getFilesYoungerThan(self.temp_dir_path, 2) deleteFiles.deleteFiles(files) self.assertEqual( 0, len(Directory.GetFileSystemEntries(self.temp_dir_path)))
def testDeleteAllFilesInDirectory(self): files = directoryListing.getFilesOlderThan(self.temp_dir_path) deleteFiles.deleteFiles(files) self.assertEqual( 0, len(Directory.GetFileSystemEntries(self.temp_dir_path)))
alldocs = [] app = __revit__.Application # for f in files: ## modify this to point to the file in the input sheet # alldocs.append(app.OpenDocumentFile(f)) time = strftime("%Y-%m-%d %H%M%S", localtime()) path = 'Y:\Revit MEP\Revit Development\_Work in progress\FamilyParameterTest\modifedFiles' + time from System.IO import Directory Directory.CreateDirectory(path) #build list of 'actions' from spreadsheet inputs #(modify, add, delete parameters) params = [] addParams = [] deleteParams = [] renameTypes = [] #these are the docs we to operate on docs = [] docIds = []
def makedirs(path): if sys.platform == 'cli': if not dir_exists(path): Directory.CreateDirectory(path) else: os.makedirs(path)
def dir_exists(path_): if sys.platform == 'cli' and os.name != 'nt': return Directory.Exists(path_) else: return os.path.isdir(path_)
def CreateDirectory(folderPath): directoryInfo = Directory.CreateDirectory(folderPath) return directoryInfo
def onSignInClick(source, rea): config = None directory = Path.Combine( Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), Assembly.GetEntryAssembly().GetName().Name) backgroundBrush = None textColor = SystemColors.ControlTextBrush if Directory.Exists(directory): fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location) for fileName2 in Directory.EnumerateFiles(directory, "*.config"): if fileName1.Equals( Path.GetFileNameWithoutExtension(fileName2)): exeConfigurationFileMap = ExeConfigurationFileMap() exeConfigurationFileMap.ExeConfigFilename = fileName2 config = ConfigurationManager.OpenMappedExeConfiguration( exeConfigurationFileMap, ConfigurationUserLevel.None) if config is None: config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None) directory = None if config.AppSettings.Settings["BackgroundImage"] is not None: fileName = config.AppSettings.Settings[ "BackgroundImage"].Value if directory is None else Path.Combine( directory, config.AppSettings.Settings["BackgroundImage"].Value) fs = None bi = BitmapImage() try: fs = FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read) bi.BeginInit() bi.StreamSource = fs bi.CacheOption = BitmapCacheOption.OnLoad bi.CreateOptions = BitmapCreateOptions.None bi.EndInit() finally: if fs is not None: fs.Close() backgroundBrush = ImageBrush(bi) backgroundBrush.TileMode = TileMode.Tile backgroundBrush.ViewportUnits = BrushMappingMode.Absolute backgroundBrush.Viewport = Rect(0, 0, bi.Width, bi.Height) backgroundBrush.Stretch = Stretch.None if backgroundBrush.CanFreeze: backgroundBrush.Freeze() if backgroundBrush is None and config.AppSettings.Settings[ "BackgroundColor"] is not None: if config.AppSettings.Settings["BackgroundColor"].Value.Length > 0: backgroundBrush = SolidColorBrush( ColorConverter.ConvertFromString( config.AppSettings.Settings["BackgroundColor"].Value)) if backgroundBrush.CanFreeze: backgroundBrush.Freeze() if config.AppSettings.Settings["TextColor"] is not None: if config.AppSettings.Settings["TextColor"].Value.Length > 0: textColor = ColorConverter.ConvertFromString( config.AppSettings.Settings["TextColor"].Value) textBrush = SolidColorBrush(textColor) if textBrush.CanFreeze: textBrush.Freeze() window = Window() def onClick(source, args): global username, password if not String.IsNullOrEmpty( usernameTextBox.Text) and not String.IsNullOrEmpty( passwordBox.Password): username = usernameTextBox.Text password = passwordBox.Password def onSave(): try: fs = None sr = None sw = None try: fs = FileStream(__file__, FileMode.Open, FileAccess.ReadWrite, FileShare.Read) encoding = UTF8Encoding(False) sr = StreamReader(fs, encoding, True) lines = Regex.Replace( Regex.Replace( sr.ReadToEnd(), "username\\s*=\\s*\"\"", String.Format("username = \"{0}\"", username), RegexOptions.CultureInvariant), "password\\s*=\\s*\"\"", String.Format("password = \"{0}\"", password), RegexOptions.CultureInvariant) fs.SetLength(0) sw = StreamWriter(fs, encoding) sw.Write(lines) finally: if sw is not None: sw.Close() if sr is not None: sr.Close() if fs is not None: fs.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace) def onCompleted(task): global menuItem for window in Application.Current.Windows: if window is Application.Current.MainWindow and window.ContextMenu is not None: if window.ContextMenu.Items.Contains(menuItem): window.ContextMenu.Items.Remove(menuItem) window.ContextMenu.Opened -= onOpened if window.ContextMenu.Items[10].GetType( ).IsInstanceOfType(window.ContextMenu.Items[ window.ContextMenu.Items.Count - 4]): window.ContextMenu.Items.RemoveAt(10) menuItem = None Task.Factory.StartNew( onSave, TaskCreationOptions.LongRunning).ContinueWith( onCompleted, TaskScheduler.FromCurrentSynchronizationContext()) window.Close()