Пример #1
0
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
Пример #2
0
def createfolder(basedir, formatstring='%Y-%m-%d_%H-%M-%S'):
    """Creates a new folder inside an existing folder using a specific format

    :param basedir: Folder inside which the new directory should be created
    :type basedir: str
    :param formatstring: String format for the new folder, defaults to '%Y-%m-%d_%H-%M-%S'
    :type formatstring: str, optional
    :return: Newly created directory
    :rtype: str
    """

    # construct new directory name based on date and time
    newdir = Path.Combine(basedir, datetime.now().strftime(formatstring))
    # check if the new directory (for whatever reasons) already exists
    try:
        newdir_exists = Directory.Exists(newdir)
        if not newdir_exists:
            # create new directory if is does not exist
            Directory.CreateDirectory(newdir)
        if newdir_exists:
            # raise error if it really already exists
            raise SystemExit
    except OSError as e:
        if e.errno != errno.EEXIST:
            newdir = None
            raise  # This was not a "directory exist" error..

    return newdir
def export_animations():
    # verify and gather target material data
    for material in BrawlAPI.NodeListOfType[MDL0MaterialNode]():
        if material.Name == target:
            if check_textures(material) and check_animations(material):

                # create preset directory
                Directory.CreateDirectory(path)

                # export material
                material.Export(Path.Combine(path, material.Name + ".mdl0mat"))

                # export shader
                material.ShaderNode.Export(Path.Combine(path, material.Name + ".mdl0shade"))

                # export textures
                for texture in textures:
                    texture.Export(Path.Combine(path, texture.Name + ".tex0"))

                # export animation
                for srt in BrawlAPI.NodeListOfType[SRT0Node]():
                    for srt_subnode in srt.Children:
                        if srt_subnode.Name == material.Name:
                            srt.Export(Path.Combine(path, srt.Name + ".srt0"))
                            break
                
                # only once
                break
def path_builder(path, category, sub_folder):
    if sub_folder:
        new_path = path + '\\' + category
        Directory.CreateDirectory(new_path)
        return new_path
    else:
        return path
Пример #5
0
def gen_one_report(module, cpy_path, outdir='baselines'):
    if not Directory.Exists(outdir):
        Directory.CreateDirectory(outdir)

    print('processing', module)
    diffs = diff_module(module, cpy_path)
    return gen_bug_report(module, diffs, outdir)
Пример #6
0
    def __initialize(cls):

        # get the basic locations that the other locations build on
        script_dir = Directory.GetParent(__file__).FullName
        profile_dir = Environment.GetFolderPath(
           Environment.SpecialFolder.ApplicationData) + \
           r"\Comic Vine Scraper"

        # set the standard locations for settings files
        cls.SETTINGS_FILE = profile_dir + r'\settings.dat'
        cls.ADVANCED_FILE = profile_dir + r'\advanced.dat'
        cls.GEOMETRY_FILE = profile_dir + r'\geometry.dat'
        cls.SERIES_FILE = profile_dir + r'\series.dat'
        cls.LOCAL_CACHE_DIRECTORY = profile_dir + r'\localCache'
        cls.I18N_DEFAULTS_FILE = script_dir + r"\en.zip"

        # do a special trick to things run from within the IDE,
        # where certain files like 'en.zip' are in different locations
        ide_i18n_file = Directory.GetParent(
           Directory.GetParent( script_dir).FullName ).FullName + \
           r'\src\resources\languages\en.zip'
        if not File.Exists(cls.I18N_DEFAULTS_FILE) \
              and File.Exists( ide_i18n_file ):
            cls.I18N_DEFAULTS_FILE = ide_i18n_file

        # import settings from legacy location, if needed.
        # ensure profile directory exists.
        cls.__import_legacy_settings(script_dir, profile_dir)
        if not File.Exists(profile_dir):
            Directory.CreateDirectory(profile_dir)
Пример #7
0
def dircheck(basefolder):
    """Check if a directory or folder already exits.
    Create the folder if it does not exist

    :param basefolder: folder to check
    :type basefolder: str
    :return: new_directory
    :rtype: str
    """

    # check if the destination basefolder exists
    base_exists = Directory.Exists(basefolder)

    if base_exists:
        print('Selected Directory Exists: ', 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)

    if not base_exists:
        Directory.CreateDirectory(basefolder)
        newdir = basefolder

    return newdir
Пример #8
0
def GetNewFilePath(fileName, subDir="./"):
    path = Path.Combine(GetOutputDir(), subDir)
    if (not Directory.Exists(path)):
        Directory.CreateDirectory(path)
    path = Path.Combine(path, fileName)
    path = Path.GetFullPath(path)
    if (File.Exists(path)):
        File.Delete(path)
    True (not File.Exists(path), "Verify file does not exist: " + path)
    return path
Пример #9
0
def deletecomics(options, cr, deletelist, logfile):
    ''' Moves or deletes the specified comics and removes them from the library'''
    ''' Mostly ripped form StonePawn's Libary Organizer script'''

    if not Directory.Exists(DUPESDIRECTORY):
        try:
            Directory.CreateDirectory(DUPESDIRECTORY)
        except Exception, ex:
            MessageBox.Show('ERROR: ' + str(ex),
                            "ERROR creating dump directory" + DUPESDIRECTORY,
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            logfile.write('ERROR: ' + str(ex) + '\n')
            return
Пример #10
0
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")
Пример #11
0
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 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 DuplicatesManager(books):

    ########################################
    #
    # Starting log file
    #

    if not Directory.Exists(DUPESDIRECTORY):
        try:
            Directory.CreateDirectory(DUPESDIRECTORY)
        except Exception, ex:
            MessageBox.Show('ERROR: ' + str(ex),
                            "ERROR creating dump directory" + DUPESDIRECTORY,
                            MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            return
Пример #14
0
def dircheck(basefolder):

    # check if the destination basefolder exists
    base_exists = Directory.Exists(basefolder)

    if base_exists:
        print('Selected Directory Exists: ', 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)
    if not base_exists:
        Directory.CreateDirectory(basefolder)
        newdir = basefolder

    return newdir
Пример #15
0
def createfolder(basedir, formatstring='%Y-%m-%d_%H-%M-%S'):
    # construct new directoty name nased on date and time
    newdir = Path.Combine(basedir, datetime.now().strftime(formatstring))
    # check if the new directory (for whatever reasons) already exists
    try:
        newdir_exists = Directory.Exists(newdir)
        if not newdir_exists:
            # create new directory if is does not exist
            Directory.CreateDirectory(newdir)
        if newdir_exists:
            # raise error if it really already exists
            raise SystemExit
    except OSError as e:
        if e.errno != errno.EEXIST:
            newdir = None
            raise  # This was not a "directory exist" error..

    return newdir
Пример #16
0
 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 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
Пример #18
0
if not isinstance(categories, list):
    categories = [categories]
saveBool = IN[1]
outList = []

collector = FilteredElementCollector(doc).OfClass(Family)
for category in categories:
    elements = []
    for family in collector:
        if family.FamilyCategoryId.ToString() == category.Id.ToString():
            elements.append(family)

    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)
Пример #19
0
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 = []

Пример #20
0
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

doc = DocumentManager.Instance.CurrentDBDocument
ui_app = DocumentManager.Instance.CurrentUIApplication
app = ui_app.Application
uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveUIDocument

path_to_folder_file = 'C:/RS_logs/'
log_file_name = 'TaskDialogs_info.log'
path_to_log_file = "{}{}".format(path_to_folder_file, log_file_name)
test = []

if not Directory.Exists(path_to_folder_file):
	Directory.CreateDirectory(path_to_folder_file)


def LogSave(info):
	if info:
		string_list_info = []
		string_list_info.append("")
		string_list_info.append(DateTime.Now.ToLocalTime().ToString())
		# string_list_info.append(python_file_name)
		string_list_info.extend(info)
		IO.File.AppendAllLines(path_to_log_file, string_list_info, Text.Encoding.Unicode)


def UiAppOnDialogBoxShowing(sender_uiapp, args):
	activ_doc = sender_uiapp.ActiveUIDocument.Document
	activ_doc_name = "none"
# create list of images to be processed
imglist = []

for file in Directory.GetFiles(sourcefolder, itype):
    imglist.append(file)

# create the required dict with the correct key and value
# the required value here: list of the input images
input_images = {'list_input_images': imglist}

# define the savepath
savepath = Path.Combine(sourcefolder, 'saved_results')

# create the output directory if not existing
if not Directory.Exists(savepath):
    Directory.CreateDirectory(savepath)

# define the processing parameters (or use the defaults: params.Parameters
my_parameters = {'filtertype': 'Median', 'filter_kernel_size': 7}

# or use default parameters from the module
#my_parameters = params.Parameters

# run the local APEER module with using keywords
runoutputs, status, log = ZenApeer.Onsite.RunModule(
    moduleName=module_name,
    moduleVersion=module_version,
    inputs=input_images,
    parameters=my_parameters,
    storagePath=savepath)
Пример #22
0
copts.FileName = "C:\\Users\\files\\VMs\\Windows 10 x64-PRO-1703\\Windows 10 x64-PRO-1703-40599dd1.vmem"  
copts.VersionsToEnable = PTType.GENERIC
# To get some additional output 
copts.VerboseOutput = True
copts.VerboseLevel = 1


TotalRunTime = Stopwatch.StartNew()

# since we are not ignoring SaveData, this just get's our state from
vtero = Scan.Scanit(copts)

# Global
CollectKernel = False
newdir = copts.FileName + ".dumped.latest"
topDir = Directory.CreateDirectory(newdir)
Vtero.DiagOutput = False

proc_arr = vtero.Processes.ToArray()
low_proc = proc_arr[0]
for proc in proc_arr:
    if proc.CR3Value < low_proc.CR3Value:
        low_proc = proc

proc = low_proc
print "Assumed Kernel Proc: " + proc.ToString()
vtero.KernelProc = proc
proc.MemAccess = Mem(vtero.MemAccess)

# by default this will scan for kernel symbols 
kvs = proc.ScanAndLoadModules()
Пример #23
0
def GetOutputDir():
    path = Path.Combine(Environment.CurrentDirectory, "tests/TestOutput")
    if (not Directory.Exists(path)):
        Directory.CreateDirectory(path)
    return path
Пример #24
0
    seg_subfolder = Path.Combine(sourcefolder, 'Seg')

    if Directory.Exists(seg_subfolder):
        if len(Directory.GetFiles(seg_subfolder)) != 0:
            # subfolder exist and is not empty - stop here
            message = 'Subfolder already exits and is not empty. Stopping Execution.'
            print(message, sourcefolder)
            raise SystemExit
        if len(Directory.GetFiles(seg_subfolder)) == 0:
            print(
                'Subfolder already exists but is empty. Proceed with Segmentation.'
            )

    if not Directory.Exists(seg_subfolder):
        # subfolder does not exist - create one
        Directory.CreateDirectory(seg_subfolder)
        print('Created subfolder for segmentation results : ', seg_subfolder)

if segactiveimg:

    if not Zen.Application.Documents.ActiveDocument.IsZenImage:
        message = 'Active Document is not a ZenImage.'
        print(message, sourcefolder)
        raise SystemExit

    if Zen.Application.Documents.ActiveDocument.IsZenImage:
        image = Zen.Application.ActiveDocument
        imagefiles.append(image.FileName)

print(
    '-----------------------------------------------------------------------------'
numczi = czidir.Length

# this list contains the subdirectories created for splitting
splitdirs = []

if split == True:

    print 'Split CZI using Split Scenes (Write Files): yes'
    # Batch Loop - Load all CZI images and do Split Scenes (Write Files)
    for i in range(0, numczi):
        # get current CZI file
        czifile = czidir[i]
        file_woExt = Path.GetFileNameWithoutExtension(czifile)
        # create separate directory for the current file
        splitdir = Path.Combine(sourcedir, file_woExt + '_Single')
        Directory.CreateDirectory(splitdir)
        # store directory name inside list
        splitdirs.append(splitdir)
        print 'File to split: ', czifile
        image = Zen.Application.LoadImage(czifile, False)

        # split single CZI file containing all wells into single CZI files
        Zen.Processing.Utilities.SplitScenes(image, splitdir,
                                             ZenCompressionMethod.None, True,
                                             True, False)
        # close file
        image.Close()
        print 'Finished Split Scences (Write Files): ', czifile

elif split == False:
    # set the splitdir to the original folder when no splitting takes place
Пример #26
0
def exists(filename):
    Directory.CreateDirectory(_basePath)
    return File.Exists(get_path(filename))
Пример #27
0
def makedirs(path):
    if sys.platform == 'cli':
        if not dir_exists(path):
            Directory.CreateDirectory(path)
    else:
        os.makedirs(path)
Пример #28
0
def get_path(filename):
    Directory.CreateDirectory(_basePath)
    return Path.Combine(_basePath, filename)
Пример #29
0
def CreateDirectory(folderPath):
    directoryInfo = Directory.CreateDirectory(folderPath)
    return directoryInfo
Пример #30
0
    module_params = ZenApeer.Onsite.GetSampleModuleParameters(
        ams.ModuleName, ams.ModuleVersion)

    # get the module input programmatically
    module_inputs = get_module_inputs(module_params)

    # create the required dictionary with the correct key and value
    input_image = {module_inputs[0]: savepath_ovscan}

    # create the path to save the results
    #savepath_apeer = Path.Combine(OutputFolder, 'apeer_results')
    savepath_apeer = OutputFolder

    # create the output directory if not existing already
    if not Directory.Exists(savepath_apeer):
        Directory.CreateDirectory(savepath_apeer)

    # run the local APEER module with using keywords
    try:
        runoutputs, status, log = ZenApeer.Onsite.RunModule(
            moduleName=ams.ModuleName,
            moduleVersion=ams.ModuleVersion,
            inputs=input_image,
            parameters=ams.Parameters,
            storagePath=savepath_apeer)

        for op in runoutputs.GetEnumerator():
            print('-----    Outputs   -----')
            print(op.Key, ' : ', op.Value)

    except ApplicationException as e: