Exemplo n.º 1
0
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)
Exemplo n.º 2
0
    def groupHeaders(self, theFile=globalvars.DATFILE):
        '''
		returns a list of group headers in the rule set
		'''
        headers = []
        if File.Exists(theFile):
            s1 = File.ReadAllLines(theFile)
            s1 = [line for line in s1 if String.StartsWith(line, '#@ GROUP')]
            for line in s1:
                headers.Add(String.Replace(line, '#@ GROUP ', ''))

        return headers
Exemplo n.º 3
0
    def read(self, myKey):
        '''
		retrieves the value of myKey in Ini-file theFile
		returns '' if key myKey was not found
		'''
        if File.Exists(self.theFile):
            myLines = File.ReadAllLines(self.theFile)
            for line in myLines:
                s = str.split(unicode(line), '=')
                if str.Trim(s[0]) == myKey:
                    return str.Trim(s[1])
        return ''
 def GetTestModeData(self):
     testModeData = None
     testModeDataFilePath = self.GetTestModeDataFilePath()
     if File.Exists(testModeDataFilePath):
         testModeData = json_util.DeserializeToJObject(
             File.ReadAllText(testModeDataFilePath))
     else:
         testModeData = json_util.JObject()
         testModeData[TEST_MODE_DATA__SESSION_ID] = None
         testModeData[TEST_MODE_DATA__REVIT_PROCESS_IDS] = json_util.JArray(
         )
     return testModeData
Exemplo n.º 5
0
def readFile(theFile):
    if File.Exists(theFile):
        s = File.ReadAllLines(theFile)
    else:
        return str('')

    tmp = str('')
    # s = [line for line in s if str.Trim(line) <> '']
    for line in s:
        tmp += '%s%s' % (line, System.Environment.NewLine)
    if len(s) == 0 and theFile == globalvars.LOGFILE:
        tmp = 'Your criteria matched no book. No data was touched by the Data Manager.'
    return tmp
Exemplo n.º 6
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")
Exemplo n.º 7
0
def __PrintFileInformation(fullpath):
    "Displays a file's information."
    fi = FileInfo(fullpath)
    info = "Full Path:  " + fullpath + "\n"
    info += "File Name:  " + Path.GetFileName(fullpath) + "\n"
    info += "File Attributes:  " + __FileAttributes(fullpath) + "\n"
    info += "Date Created:  " + File.GetCreationTime(
        fullpath).ToString() + "\n"
    info += "Last Date Accessed:  " + File.GetLastAccessTime(
        fullpath).ToString() + "\n"
    info += "Last Date Modified:  " + File.GetLastWriteTime(
        fullpath).ToString() + "\n"
    info += "File Size (Bytes):  " + fi.Length.ToString() + "\n"
    rs.MessageBox(info, 0, "Current Model Information")
Exemplo n.º 8
0
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 ReadRevitFileList(self, output):
    revitFileList = None
    if self.RevitProcessingOption == BatchRvt.RevitProcessingOption.BatchRevitFileProcessing:
      if self.RevitFileList is not None:
        output()
        output("Reading Revit File list from object input.")
        revitFileList = self.RevitFileList
      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:
          revitFileList = revit_file_list.GetRevitFileList(self.RevitFileListFilePath)
          self.RevitFileList = revitFileList  

      if revitFileList is None:
        output()
        output("ERROR: Could not read the Revit File list.")
      elif len(revitFileList) == 0:
        output()
        output("ERROR: Revit File list is empty.")
        revitFileList = None
    return revitFileList
Exemplo n.º 10
0
    def write(self, theText):
        '''
		writes the context of the configurator window to a file
		returns ERROR constant (NOERROR if successful)
		if the parser made any alterations the editedByParser property will be
		set to True
		'''
        self.editedByParser = False
        theText = unicode(theText)
        s = String.Split(theText, '\n')
        # s = str.split(str(theText),'\n')
        tmp = str('')
        errlines = 0
        myParser = parser()
        pre = ''

        s = [line for line in s if str.Trim(line) <> '']

        for line in s:
            myParser.validate(unicode(line))
            if myParser.err:
                pre = myParser.commentedLine(line)
                errlines += 1
                self.editedByParser = True
            else:
                pre = unicode(line)
            tmp += '%s%s' % (pre, System.Environment.NewLine)
        if len(tmp) > 0:
            try:
                File.WriteAllText(self.theFile, tmp)
            except Exception, err:
                return self.ERRORSAVEFILE
Exemplo n.º 11
0
def __load_testdata(file):
   """
   Reads the testdata out of a file.  Testdata consists of exactly three 
   strings on each line, each one enclosed in quotation marks (" or ').  
   The first is the filename to be parsed, the second is the series name
   that should be parsed out of it, and the third is the issue number string
   that should be parsed out of it.
   
   Blank lines and lines that begin with # are ignored.
   """
   retval = []
   if File.Exists(file): 
      with StreamReader(file, Encoding.UTF8, False) as sr:
         line = sr.ReadLine()
         while line is not None:
            line = line.strip()
            if len(line) > 0 and not line.startswith("#"):
               if line.startswith('"'):
                  data = re.findall(r'"(.*?)"', line)
               else:
                  data = re.findall(r"'(.*?)'", line)
               if len(data) == 3:
                  data.append("")
               if len(data) != 4:
                  raise Exception("badly formatted test data");
               retval.append( data ) 
            line = sr.ReadLine()
   return retval
    def __deserialize_from_xml(file_full_name):
        iaddin_custom_frame_instance = None
        try:
            filereader = None
            try:
                filereader = File.OpenText(file_full_name)
                if filereader:
                    content = filereader.ReadToEnd()
                    stringreader = StringReader(content)
                    xmlreader = None
                    try:
                        xmlreader = XmlReader.Create(stringreader)
                        if xmlreader:
                            iaddin_custom_frame_instance = XamlReader.Load(
                                xmlreader)
                    finally:
                        if xmlreader:
                            xmlreader.Dispose()
                            xmlreader = None
            finally:
                if filereader:
                    filereader.Dispose()
                    filereader = None
        except Exception as e:
            CommonUtil.sprint("Failed to desrialize: {}".format(e))
            iaddin_custom_frame_instance = None

        return iaddin_custom_frame_instance
Exemplo n.º 13
0
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()):
            tfile = open('ip_session.log', 'r')
            break
        print "Waiting for ip_session.log to be created..."
        sleep(1)

    outlines = tfile.readlines()
    tfile.close()

    errlines = []
    if File.Exists('ip_session_stderr.log'):
        tfile = open('ip_session_stderr.log', 'r')
        errlines = tfile.readlines()
        tfile.close()

    return (outlines, errlines)
Exemplo n.º 14
0
def unmanagedDLL():
    '''
    Places an unmanaged DLL inside DLLs.
    '''
    twain = Environment.GetEnvironmentVariable("SystemRoot") + "\\twain.dll"
    File.Copy(twain,
              DLLS_DIR + "\\twain.dll")
Exemplo n.º 15
0
def play_ik(stChara, name):
    from Manager import Studio
    from System.IO import File
    import os.path
    import UserData
    
    ik = Studio.Instance.studioUIIK
    fpath = os.path.abspath(os.path.join(UserData.Path, "IKPose", name))
    
    if not File.Exists(fpath):
        return
    @unity
    def run(ik, chara, name, path):
        oldChara = ik.currentSC
        try:
            #ik.currentName
            #ik.currentNameText.text = name
            ik.fileNameIF.text = name
            ik.currentSC = chara
            ik.IK_EnableChange(True)
            ik.Load(path)
            ik.IK_EffectorViewChange(False)
            ik.UpdateIKUI()
        finally:
            ik.currentSC = oldChara
    run(ik,stChara,name,fpath)
Exemplo n.º 16
0
    def OpenDocument(self):
        if self.openFileDialog.ShowDialog() != WinForms.DialogResult.OK:
            return

        filename = self.openFileDialog.FileName

        stream = File.OpenRead(filename)

        buff = System.Array.CreateInstance(System.Byte, 1024)
        buff.Initialize()
        data = []
        read = 1

        while read > 0:
            read, _ = stream.Read(buff, 0, 1024)
            temp = Encoding.ASCII.GetString(buff, 0, read)
            data.append(temp)

        data = ''.join(data)
        stream.Close()

        filename = self.filename = filename.lower()

        if filename.endswith('.rtf'):
            self.richTextBox.Rtf = data
            self.doctype = 2
        else:
            self.richTextBox.Text = data
            self.doctype = 1

        self.Text = 'Python Wordpad - %s' % filename
        self.richTextBox.Select(0, 0)
Exemplo n.º 17
0
def _check_magic_file(path_s):
   ''' ComicVine implementation of the identically named method in the db.py '''
   series_ref = 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
               series_ref = __url_to_seriesref(line)
   except:
      log.debug_exc("bad cvinfo file: " + sstr(file_s))
      
   if file_s and not series_ref:
      log.debug("ignoring bad cvinfo file: ", sstr(file_s))

   return series_ref # may be None!
Exemplo n.º 18
0
    def _request_ironython(self, *args, **kwargs):
        method, url = args
        headers = kwargs.get("headers")
        params = kwargs.get("params")
        json_data = kwargs.get("json_data")
        byte_data = kwargs.get("byte_data")
        urlencode = kwargs.get("urlencode")
        filepath = kwargs.get("filepath")

        try:
            # prepare params
            if params:
                url = self._add_url_params(url, params)

            web_request = WebRequest.Create(url)
            web_request.Method = method.upper()
            web_request.Timeout = self.timeout

            # prepare headers
            if headers:
                for key, value in headers.items():
                    if key == "Content-Type":
                        web_request.ContentType = value
                    elif key == "Content-Length":
                        web_request.ContentLength = value
                    else:
                        web_request.Headers.Add(key, value)

            byte_arrays = []
            if json_data:
                byte_arrays.append(
                    UTF8.GetBytes(json.dumps(json_data, ensure_ascii=False)))
            if filepath:
                byte_arrays.append(File.ReadAllBytes(filepath))
            if byte_data:
                pass
                # TODO - Add byte input for System.Net
            if urlencode:
                byte_arrays.append(UTF8.GetBytes(self._url_encode(urlencode)))

            for byte_array in byte_arrays:
                web_request.ContentLength = byte_array.Length
                with web_request.GetRequestStream() as req_stream:
                    req_stream.Write(byte_array, 0, byte_array.Length)
            try:
                with web_request.GetResponse() as response:
                    success = response.StatusDescription in SUCCESS_CODES

                    with response.GetResponseStream() as response_stream:
                        with StreamReader(response_stream) as stream_reader:
                            data = json.loads(stream_reader.ReadToEnd())
            except SystemError:
                return None, None
            finally:
                web_request.Abort()

        except Exception as e:
            raise e

        return data, success
Exemplo n.º 19
0
def canWriteToDir(d):
	try:
		with File.Create(Path.Combine(d, "__test_file_name__"),
		1, FileOptions.DeleteOnClose) as f:
			return True
	except:
		return False
    def __serialize_to_xml__(iaddin_custom_frame_instance, file_full_name):
        done = False
        try:
            sb = StringBuilder()
            xml_writer_settings = XmlWriterSettings()
            xml_writer_settings.Indent = True
            xml_writer_settings.ConformanceLevel = ConformanceLevel.Fragment
            xml_writer_settings.OmitXmlDeclaration = True
            writer = None
            try:
                writer = XmlWriter.Create(sb, xml_writer_settings)
                if writer:
                    mgr = XamlDesignerSerializationManager(writer)
                    if mgr:
                        mgr.XamlWriterMode = XamlWriterMode.Expression
                        XamlWriter.Save(iaddin_custom_frame_instance, mgr)
                        filewriter = None
                        try:
                            filewriter = File.CreateText(file_full_name)
                            if filewriter:
                                filewriter.Write(sb.ToString())
                                done = True
                        finally:
                            if filewriter:
                                filewriter.Dispose()
                                filewriter = None
            finally:
                if writer:
                    writer.Dispose()
                    writer = None
        except Exception as e:
            CommonUtil.sprint("Failed to serialize: {}".format(e))
            done = False

        return done
Exemplo n.º 21
0
def main():
    if len(sys.argv) != 2:
        print "Usage: ipy run_compiled.py <testfile.py>"
        sys.exit(-1)
    
    testName = sys.argv[1]
    
    print "Compiling ", testName ,"..."
    clr.CompileModules("compiledTest.dll", testName)    
    File.Move(testName, testName+".bak")    
    try:
        print "Running test from compiled binary..."    
        clr.AddReference("compiledTest")    
        __import__(Path.GetFileNameWithoutExtension(testName))    
    finally:
        File.Move(testName+".bak" , testName)
Exemplo n.º 22
0
 def __init__(self, xamlPath):
     stream = File.OpenRead(xamlPath)
     try:
         self.Root = XamlReader.Load(stream)
     except SystemError, e:
         print 'Error parsing xaml file: {0}'.format(xamlPath)
         #print str(e)
         raise e
Exemplo n.º 23
0
 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()
Exemplo n.º 24
0
def WriteKey(iniFilePath, strKey, strValue):
    dictKeys = LoadFile(iniFilePath)
    dictKeys[strKey] = strValue
    strFile = ""
    for item in dictKeys:
        strFile += item + ' = ' + dictKeys[item] + System.Environment.NewLine
    File.WriteAllText(iniFilePath, strFile)
    pass
Exemplo n.º 25
0
 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()
Exemplo n.º 26
0
 def Process(self, logItem, parameters):
     if self.Matches(logItem):
         from System.IO import File
         f = File.AppendText('out.log')
         f.WriteLine(logItem.Message)
         f.Close()
     ret = PR.ContinueWithProcessing()
     ret.RuleIsMatching = True
     return ret
Exemplo n.º 27
0
 def load_iron_python_dll():
     import clr
     from System.IO import File
     #When assemblies are installed into the GAC, we should not expect
     #IronPython.dll to exist alongside IronPython.dll
     if File.Exists(path_combine(sys.prefix, "IronPython.dll")):
         clr.AddReferenceToFileAndPath(path_combine(sys.prefix, "IronPython.dll"))
     else:
         clr.AddReference("IronPython")
Exemplo n.º 28
0
def parseSequence(xmlNode, directory, warningList, errorList):
    for childNode1 in xmlNode.ChildNodes:
        if childNode1.Name.Equals("sequence"):
            parseSequence(childNode1, directory, warningList, errorList)

        elif childNode1.Name.Equals("message"):
            if childNode1.InnerText.Length == 0:
                if childNode1.InnerText.Length == 0:
                    if CultureInfo.CurrentCulture.Equals(
                            CultureInfo.GetCultureInfo("ja-JP")):
                        warningList.Add("メッセージタグ内のテキストが空です。")
                    else:
                        warningList.Add(
                            "The inner text is empty in message tag.")

        elif childNode1.Name.Equals("motion"):
            for childNode2 in childNode1.ChildNodes:
                if childNode2.Name.Equals("image"):
                    if childNode2.InnerText.Length > 0 and not File.Exists(
                            Path.Combine(directory, childNode2.InnerText)):
                        if CultureInfo.CurrentCulture.Equals(
                                CultureInfo.GetCultureInfo("ja-JP")):
                            errorList.Add(
                                String.Format("指定されたファイルが見つかりません。 \"{0}\"",
                                              childNode2.InnerText))
                        else:
                            errorList.Add(
                                String.Format(
                                    "Could not find the specified file. \"{0}\"",
                                    childNode2.InnerText))

        elif childNode1.Name.Equals("sound"):
            if childNode1.InnerText.Length > 0 and not File.Exists(
                    Path.Combine(directory, childNode1.InnerText)):
                if CultureInfo.CurrentCulture.Equals(
                        CultureInfo.GetCultureInfo("ja-JP")):
                    errorList.Add(
                        String.Format("指定されたファイルが見つかりません。 \"{0}\"",
                                      childNode1.InnerText))
                else:
                    errorList.Add(
                        String.Format(
                            "Could not find the specified file. \"{0}\"",
                            childNode1.InnerText))
def load_profiles_from_file(file_path):
    """
    Loads profiles from a file.
    
    file_path->The absolute path the xml file

    Returns a dict of the profiles
    """
    profiles = {}

    lastused = ""

    if File.Exists(file_path):
        try:
            with StreamReader(file_path) as xmlfile:
                xmldoc = XmlDocument()
                xmldoc.Load(xmlfile)

            if xmldoc.DocumentElement.Name == "Profiles":
                nodes = xmldoc.SelectNodes("Profiles/Profile")
            #Individual exported profiles are saved with the document element as Profile
            elif xmldoc.DocumentElement.Name == "Profile":
                nodes = xmldoc.SelectNodes("Profile")

            #Changed from 1.7 to 2.0 to use Profiles/Profile instead of Settings/Setting
            elif xmldoc.DocumentElement.Name == "Settings":
                nodes = xmldoc.SelectNodes("Settings/Setting")
            elif xmldoc.DocumentElement.Name == "Setting":
                nodes = xmldoc.SelectNodes("Setting")

            #No valid root elements
            else:
                MessageBox.Show(file_path + " is not a valid Library Organizer profile file.", "Not a valid profile file", MessageBoxButtons.OK, MessageBoxIcon.Error)
                return profiles, lastused

            if nodes.Count > 0:
                for node in nodes:                    
                    profile = Profile()
                    profile.Name = node.Attributes["Name"].Value
                    result = profile.load_from_xml(node)

                    #Error loading the profile
                    if result == False:
                        MessageBox.Show("An error occured loading the profile " + profile.Name + ". That profile has been skipped.")

                    else:
                        profiles[profile.Name] = profile


            #Load the last used profile
            rootnode = xmldoc.DocumentElement
            if rootnode.HasAttribute("LastUsed"):
                lastused = rootnode.Attributes["LastUsed"].Value.split(",")

        except Exception, ex:
            MessageBox.Show("Something seems to have gone wrong loading the xml file.\n\nThe error was:\n" + str(ex), "Error loading file", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exemplo n.º 30
0
def reload(cad, path):
    try:
        if (path and File.Exists(path)):
            cad.ReloadFrom(path)
            return True
        else:
            cad.Reload()
            return True
    except:
        return False