예제 #1
0
 def readList(self, listname):
     l = open(listname, 'r')
     for line in l:
         line = line.partition('//')[0].strip()  # remove comments
         if not len(line):
             continue
         if line[0] == '"' and line[-1] == '"':
             line = line[1:-1]
         oldpwd = os.getcwd()
         os.chdir(self.baseFolder)
         if os.path.dirname(line) == '' or os.path.isdir(
                 os.path.dirname(line)):
             for f in win32api.FindFiles(line):
                 path = os.path.join(os.path.dirname(line), f[8])
                 if os.path.isfile(path) and path.find(
                         '.svn') == -1:  # omit .svn folders
                     if self.hashCache is not None:
                         newhash = hashlib.sha1(open(
                             path, 'rb').read()).hexdigest()
                         self.hashCache.execute(
                             'INSERT OR REPLACE INTO `hashes_%s` (`path`, `hash`) VALUES (?, ?)'
                             % self.newTblName, [path, newhash])
                         if self.oldTblName is not None:
                             oldhash = self.hashCache.execute(
                                 'SELECT `hash` FROM `hashes_%s` WHERE `path` = ?'
                                 % self.oldTblName, [path]).fetchone()
                             if oldhash is not None and oldhash[
                                     0] == newhash:
                                 continue
                     self.nodeList.append(path)
         os.chdir(oldpwd)
     l.close()
예제 #2
0
def _rmtree_windows(path):
    """ Windows-specific rmtree that handles path lengths longer than MAX_PATH.
        Ported from clobberer.py.
    """
    assert _is_windows()
    path = os.path.realpath(path)
    full_path = '\\\\?\\' + path
    if not os.path.exists(full_path):
        return
    if not PYWIN32:
        if not os.path.isdir(path):
            return run_cmd('del /F /Q "%s"' % path)
        else:
            return run_cmd('rmdir /S /Q "%s"' % path)
    # Make sure directory is writable
    win32file.SetFileAttributesW('\\\\?\\' + path,
                                 win32file.FILE_ATTRIBUTE_NORMAL)
    # Since we call rmtree() with a file, sometimes
    if not os.path.isdir('\\\\?\\' + path):
        return win32file.DeleteFile('\\\\?\\' + path)

    for ffrec in win32api.FindFiles('\\\\?\\' + path + '\\*.*'):
        file_attr = ffrec[0]
        name = ffrec[8]
        if name == '.' or name == '..':
            continue
        full_name = os.path.join(path, name)

        if file_attr & win32file.FILE_ATTRIBUTE_DIRECTORY:
            _rmtree_windows(full_name)
        else:
            win32file.SetFileAttributesW('\\\\?\\' + full_name,
                                         win32file.FILE_ATTRIBUTE_NORMAL)
            win32file.DeleteFile('\\\\?\\' + full_name)
    win32file.RemoveDirectory('\\\\?\\' + path)
예제 #3
0
파일: p4status.py 프로젝트: tom-seddon/bin
def add_files_in_folder(files, folder, only_ro):
    if got_win32api:
        datas = win32api.FindFiles(os.path.join(folder, "*"))
        for data in datas:
            if (data[0] & win32file.FILE_ATTRIBUTE_DIRECTORY) == 0:
                if (data[0] & clear_flags) == 0:
                    files.add(os.path.join(folder, data[8]))

        for data in datas:
            if data[0] & win32file.FILE_ATTRIBUTE_DIRECTORY:
                if data[8] != "." and data[8] != "..":
                    add_files_in_folder(files, os.path.join(folder, data[8]),
                                        only_ro)
    else:
        for dirpath, dirnames, filenames in os.walk(folder):
            for name in filenames:
                name = os.path.join(dirpath, name)
                if only_ro:
                    try:
                        st = os.stat(name)
                    except WindowsError as e:
                        if e.winerror == 123:
                            # "The filename, directory name, or volume
                            # label syntax is incorrect" - probably a
                            # malformed file name.
                            print >> sys.stderr, 'WARNING: ignoring file with invalid name: %s' % name
                            continue
                        else:
                            raise
                    if (st.st_mode & stat.S_IWUSR) == 0: continue
                files.add(name)
예제 #4
0
def _short2longfile(pathname):
    # if we can't figure out the long name, just return the short
    try:
        list = win32api.FindFiles(pathname)
    except:
        list = []
    if not list or len(list) > 1:
        return pathname
    return list[0][8]
예제 #5
0
파일: template.py 프로젝트: hnur/pywin32
    def OpenDocumentFile(self, filename, bMakeVisible=1):
        if filename is not None:
            try:
                path = os.path.split(filename)[0]
                #				print "The editor is translating", `filename`,"to",
                filename = win32api.FindFiles(filename)[0][8]
                filename = os.path.join(path, filename)
#				print `filename`
            except (win32api.error, IndexError), details:
                pass
예제 #6
0
 def _do_get_hidden(self):
     path = self.path.encode(sys.getfilesystemencoding()).rstrip('/')#FindFiles on directories ending with '/' returns []
     files = win32api.FindFiles(path) #FindFIles might return multiple files,
                                      #if the path contains a wild character '*' or '?'.
                                      #However, '*' or '?' is not a valid character for file name on Win32.
                                      #So, there should be only 0 or 1 file returned here.
     if len(files) == 0:
         self._hidden = None
         return
     if len(files) > 1:
         raise Exception("OOPS: More than 1 files matched. A wildcharacter in filename?")
     self._hidden = bool(files[0][0] & win32con.FILE_ATTRIBUTE_HIDDEN)
예제 #7
0
파일: meum.py 프로젝트: yellowaug/pythonpro
    def change(self):
        selectchar = input("请输入项目编号(按回车确定):\n")

        if (selectchar == "1" and len(selectchar) == 1):
            print("111")
        elif (selectchar == "2" and len(selectchar) == 1):
            print("222")
        else:
            print("请输入正确的项目编号")
        os.system("pause")
        os.system("cls")
        re = MEUN()
        re.change()
        win32api.FindFiles()
예제 #8
0
def GetServiceClassString(cls, argv = None):
    if argv is None:
        argv = sys.argv
    import pickle
    modName = pickle.whichmodule(cls, cls.__name__)
    if modName == '__main__':
        try:
            fname = win32api.GetFullPathName(argv[0])
            path = os.path.split(fname)[0]
            # Eaaaahhhh - sometimes this will be a short filename, which causes
            # problems with 1.5.1 and the silly filename case rule.
            # Get the long name
            fname = os.path.join(path, win32api.FindFiles(fname)[0][8])
        except win32api.error:
            raise error("Could not resolve the path name '%s' to a full path" % (argv[0]))
        modName = os.path.splitext(fname)[0]
    return modName + "." + cls.__name__
예제 #9
0
 def readList(self, listname):
   l = open(listname, 'r')
   for line in l:
     line = line.partition('//')[0].strip()  # remove comments
     if not len(line):
       continue
     if line[0] == '"' and line[-1] == '"':
       line = line[1:-1]
     oldpwd = os.getcwd()
     os.chdir(self.baseFolder)
     if os.path.dirname(line) == '' or os.path.isdir(os.path.dirname(line)):
       for f in win32api.FindFiles(line):
         path = os.path.join(os.path.dirname(line), f[8])
         if os.path.isfile(path):
           self.nodeList.append(path)
     os.chdir(oldpwd)
   l.close()
예제 #10
0
def GetServiceClassString(cls, argv = None):
    if argv is None:
        argv = sys.argv
    import pickle
    modName = pickle.whichmodule(cls, cls.__name__)
    if modName == '__main__':
        try:
            fname = win32api.GetFullPathName(argv[0])
            path = os.path.split(fname)[0]
            # Eaaaahhhh - sometimes this will be a short filename, which causes
            # problems with 1.5.1 and the silly filename case rule.
            filelist = win32api.FindFiles(fname)
            # win32api.FindFiles will not detect files in a zip or exe. If list is empty,
            # skip the test and hope the file really exists. 
            if len(filelist) != 0:
                # Get the long name
                fname = os.path.join(path, filelist[0][8])
        except win32api.error:
            raise error("Could not resolve the path name '%s' to a full path" % (argv[0]))
        modName = os.path.splitext(fname)[0]
    return modName + "." + cls.__name__
예제 #11
0
def getShortPathName(filepath):
    "Converts the given path into 8.3 (DOS) form equivalent."
    import win32api, os
    if filepath[-1] == "\\":
        filepath = filepath[:-1]
    tokens = os.path.normpath(filepath).split("\\")
    if len(tokens) == 1:
        return filepath
    ShortPath = tokens[0]
    for token in tokens[1:]:
        PartPath = "\\".join([ShortPath, token])
        Found = win32api.FindFiles(PartPath)
        if Found == []:
            raise WindowsError, 'The system cannot find the path specified: "%s"' % (PartPath)
        else:
            if Found[0][9] == "":
                ShortToken = token
            else:
                ShortToken = Found[0][9]
            ShortPath = ShortPath + "\\" + ShortToken
    return ShortPath
예제 #12
0
def RegisterClasses(*classes, **flags):
  quiet = 'quiet' in flags and flags['quiet']
  debugging = 'debug' in flags and flags['debug']
  for cls in classes:
    clsid = cls._reg_clsid_
    progID = _get(cls, '_reg_progid_')
    desc = _get(cls, '_reg_desc_', progID)
    spec = _get(cls, '_reg_class_spec_')
    verProgID = _get(cls, '_reg_verprogid_')
    defIcon = _get(cls, '_reg_icon_')
    threadingModel = _get(cls, '_reg_threading_', 'both')
    catids = _get(cls, '_reg_catids_', [])
    options = _get(cls, '_reg_options_', {})
    policySpec = _get(cls, '_reg_policy_spec_')
    clsctx = _get(cls, '_reg_clsctx_')
    tlb_filename = _get(cls, '_reg_typelib_filename_')
    # default to being a COM category only when not frozen.
    addPyComCat = not _get(cls, '_reg_disable_pycomcat_', pythoncom.frozen!=0)
    addnPath = None
    if debugging:
      # If the class has a debugging dispatcher specified, use it, otherwise
      # use our default dispatcher.
      dispatcherSpec = _get(cls, '_reg_debug_dispatcher_spec_')
      if dispatcherSpec is None:
        dispatcherSpec = "win32com.server.dispatcher.DefaultDebugDispatcher"
      # And remember the debugging flag as servers may wish to use it at runtime.
      debuggingDesc = "(for debugging)"
      options['Debugging'] = "1"
    else:
      dispatcherSpec = _get(cls, '_reg_dispatcher_spec_')
      debuggingDesc = ""
      options['Debugging'] = "0"

    if spec is None:
      moduleName = cls.__module__
      if moduleName == '__main__':
        # Use argv[0] to determine the module name.
        try:
         # Use the win32api to find the case-sensitive name
          moduleName = os.path.splitext(win32api.FindFiles(sys.argv[0])[0][8])[0]
        except (IndexError, win32api.error):
          # Can't find the script file - the user must explicitely set the _reg_... attribute.
          raise TypeError("Can't locate the script hosting the COM object - please set _reg_class_spec_ in your object")

      spec = moduleName + "." + cls.__name__
      # Frozen apps don't need their directory on sys.path
      if not pythoncom.frozen:
        scriptDir = os.path.split(sys.argv[0])[0]
        if not scriptDir: scriptDir = "."
        addnPath = win32api.GetFullPathName(scriptDir)

    RegisterServer(clsid, spec, desc, progID, verProgID, defIcon,
                   threadingModel, policySpec, catids, options,
                   addPyComCat, dispatcherSpec, clsctx, addnPath)
    if not quiet:
      print('Registered:', progID or spec, debuggingDesc)
    # Register the typelibrary
    if tlb_filename:
      tlb_filename = os.path.abspath(tlb_filename)
      typelib = pythoncom.LoadTypeLib(tlb_filename)
      pythoncom.RegisterTypeLib(typelib, tlb_filename)
      if not quiet:
        print('Registered type library:', tlb_filename)
  extra = flags.get('finalize_register')
  if extra:
    extra()
예제 #13
0
def FindFiles(spec, local=1):
    if local:
        return win32api.FindFiles(spec)
    else:
        return wincerapi.CeFindFiles(spec)
예제 #14
0
import win32api

#make long integers are used
neg_gig2 = -2147483648L
gig2 = 2147483648L
gig4 = 4294967296L

#additional stores every whole group of 4 gigs
#base stores the remainder as an (unfortunately)signed int
#ignore the rest of what is returned in the array
file = 'c:/pagefile.sys'
(additional, base) = win32api.FindFiles(file)[0][4:6]

size = base

#if you get a negative size, that means the size is between 2 and 4 gigs
#The more negative the smaller the file
if base < 0L:
    size = long(abs(neg_gig2 - base)) + gig2

#For every additional you add 4 gigs
if additional:
    size = size + (additional * gig4)

print size, 'bytes or ', size / 1024, 'kb'
예제 #15
0
 def Initialize(self, dir, silent=False):
     """ディレクトリからファイル情報を取得し、リストを初期化する。入力は絶対パスでなければならない。情報が取得できなかった場合、errorCodes.OK以外が返る。silentがTrueなら読み上げは行われない。"""
     self.ClearCache()
     if isinstance(
             dir, list
     ):  # パラメータがリストなら、browsableObjects のリストとして処理刷る(ファイルリストを取得しないでコピーする)
         self._copyFromList(dir)
         return errorCodes.OK
     # end copy
     self.files.clear()
     self.folders.clear()
     dir_spl = dir[len(os.path.splitdrive(dir)[0]) + 1:].split("\\")
     level = len(dir_spl)
     if dir_spl[0] == "":
         level -= 1
     if not silent:
         r = []
         if globalVars.app.config['on_list_moved'][
                 'read_directory_level'] == 'True':
             drive = os.path.splitdrive(dir)[0]
             if len(drive) == 2:
                 drive = drive[0]
             if level == 0:
                 r.append("%sルート" % drive)
             else:
                 r.append("%sの%d " % (drive, level))
                 if globalVars.app.config['on_list_moved'][
                         'read_directory_name'] == 'True':
                     r.append(dir_spl[level - 1])
         if len(r) > 0:
             globalVars.app.say("".join(r))
     # end read
     self.rootDirectory = dir
     self.log.debug("Getting file list for %s..." % self.rootDirectory)
     t = misc.Timer()
     try:
         lst = win32api.FindFiles(os.path.join(dir, "*"))
     except pywintypes.error as err:
         self.log.error("Cannot open the directory! {0}".format(err))
         if err.winerror == 5:
             return errorCodes.ACCESS_DENIED
         dialog(_("エラー"),
                _("フォルダを開くことができませんでした(%(error)s)") % {"error": str(err)})
         return errorCodes.FATAL
     # end except
     if len(lst) == 0:
         self.log.debug("Blank folder.")
         return errorCodes.OK
     # end 空のフォルダだったらさっさと帰る
     for elem in lst:
         if elem[8] == "." or elem[8] == "..":
             continue
         fullpath = os.path.join(dir, elem[8])
         shfileinfo = self.GetShellInfo(fullpath)
         if os.path.isfile(fullpath):
             f = browsableObjects.File()
             f.Initialize(dir, elem[8], fullpath, (elem[4] << 32) + elem[5],
                          elem[3], elem[0], shfileinfo[4], elem[1], elem[9],
                          shfileinfo[0])
             self.files.append(f)
         else:
             f = browsableObjects.Folder()
             f.Initialize(dir, elem[8], fullpath, -1, elem[3], elem[0],
                          shfileinfo[4], elem[1], elem[9], shfileinfo[0])
             self.folders.append(f)
         # end どっちについかするか?
     # end 追加ループ
     self.log.debug("File list created in %f seconds." % t.elapsed)
     self.log.debug(
         str(len(self.folders)) + " directories and " +
         str(len(self.files)) + " files found.")
     if self.sortCursor != 0 or self.sortDescending != 0:
         self.log.debug("Triggering sorting")
         self.ApplySort()
     # end ソートが必要ならソート
     return errorCodes.OK
예제 #16
0
                next_data_addr = next_data_addr + 1
                if len(buf) >= buf_max:
                    self.send_to_target(buf_addr, buf)
                    buf_addr = next_data_addr
                    assert (buf_addr & 0x7) == 0
                    buf = []
        """ if buffer is not algined then pad it """
        while ((len(buf) % 8) <> 0):
            buf.append(0xFF)
        self.send_to_target(buf_addr, buf)


s19path = win32api.GetFullPathName(sys.argv[1])

print "s19 file " + s19path
if (len(win32api.FindFiles(s19path)) == 0):
    print "Please give correct s19 file."
    sys.exit(0)

start_time = time.time()
temp_time = time.localtime()
str_date = str(temp_time[1]) + ":" + str(temp_time[2]) + ":" + str(
    temp_time[0])
str_time = str(temp_time[3]) + ":" + str(temp_time[4]) + ":" + str(
    temp_time[5])
print "Start Date [MM:DD:YYYY] " + str_date
print "Start Time [HH:MM:SS]   " + str_time
fp = open(s19path, 'rb')
rcount = 0
data = fp.readlines()
s = SRecord()