def ConnectSDcardFile(): global sdfile try: os.mount(sd, '/sd') except OSError as e: oledshowfattext(["SD card", "failed"]) time.sleep_ms(5000) if not sum((f[0] == "LOG") for f in os.ilistdir("sd")): os.mkdir("sd/LOG") fnum = 1 + max( (int(f[0][:3]) for f in os.ilistdir("sd/LOG") if f[3] > 10), default=0) fname = "sd/LOG/{:03d}.TXT".format(fnum) oledshowfattext(["SDfile", fname[:6], fname[6:]]) print("Opening file", fname) sdfile = open(fname, "w") sdfile.write("Logfile: {}".format(fname)) sdfile.write("Device number: 3") sdfile.write( "Rt[ms]d\"[isodate]\"e[latdE]n[latdN]f[lngdE]o[lngdN] GPS cooeffs\n") sdfile.write("Qt[ms]u[ms midnight]y[lat600000]x[lng600000]a[alt] GPS\n") sdfile.write("Vt[ms]v[kph100]d[deg100] GPS velocity\n") sdfile.write("Ft[ms]p[milibars] bluefly pressure\n") sdfile.write("Gt[ms]r[rawhumid]a[rawtemp] si7021Humidity meter\n") sdfile.write("Nt[ms]r[rawadc]s[resistance] nickel wire sensor\n") sdfile.write("\n") return sdfile
def delete_files_recursively(path, blacklist): # unlike listdir, ilistdir is supported by unix and stm32 platform files = os.ilistdir(path) for _file in files: if _file[0] in blacklist: continue f = "%s/%s" % (path, _file[0]) # regular file if _file[1] == 0x8000: try: os.remove(f) except: if cb_on_error is not None: cb_on_error("Error", "Could not delete %s" % f) # directory elif _file[1] == 0x4000: isEmpty = delete_files_recursively(f, blacklist) if isEmpty: try: os.rmdir(f) except: if cb_on_error is not None: cb_on_error("Error", "Could not delete %s" % f) files = os.ilistdir(path) num_of_files = sum(1 for _ in files) if (num_of_files == 2 and simulator) or num_of_files == 0: """ Directory is empty - it contains exactly 2 directories - current directory and parent directory (unix) or 0 directories (stm32) """ return True return False
def ConnectSDcardFile(): global spi, sdfile, sd spi = SPI(sck=Pin(5), mosi=Pin(22), miso=Pin(27)) try: sd = sdcard.SDCard(spi, Pin(23)) os.mount(sd, '/sd') except OSError as e: return ("SD card", str(e.args[0])) if not sum((f[0]=="LOG") for f in os.ilistdir("sd")): os.mkdir("sd/LOG") fnum = 1+max((int(f[0][:3]) for f in os.ilistdir("sd/LOG") if f[3]>10), default=0) fname = "sd/LOG/{:03d}.TXT".format(fnum) print("Opening file", fname) sdfile = open(fname, "w") sdfile.write("Logfile: {}\n".format(fname)) sdfile.write("Device number: 3\n") sdfile.write("Rt[ms]d\"[isodate]\"e[latdE]n[latdN]f[lngdE]o[lngdN] GPS cooeffs\n") sdfile.write("Qt[ms]u[ms midnight]y[lat600000]x[lng600000]a[alt] GPS\n") sdfile.write("Vt[ms]v[kph100]d[deg100] GPS velocity\n") sdfile.write("Ft[ms]p[milibars] bluefly pressure\n") sdfile.write("Gt[ms]r[rawhumid]a[rawtemp] si7021Humidity meter\n") sdfile.write("Nt[ms]r[rawadc]s[resistance] nickel wire sensor\n") sdfile.write("Zt[ms]xyz[linacc]abc[gravacc]wxyz[quat]s[calibstat] orient\n"); sdfile.write("Yt[ms]s\"calibconsts\" orient calib\n"); sdfile.write("\n") sdfile.flush() return (["SDfile", fname[:6], fname[6:]])
def delete_recursively(path, include_self=False): # remove trailing slash if path is None: raise RuntimeError("Path is not specified") path = path.rstrip("/") files = os.ilistdir(path) for _file in files: if _file[0] in [".", ".."]: continue f = "%s/%s" % (path, _file[0]) # regular file if _file[1] == 0x8000: os.remove(f) # directory elif _file[1] == 0x4000: delete_recursively(f) os.rmdir(f) files = os.ilistdir(path) num_of_files = sum(1 for _ in files) if (num_of_files == 2 and simulator) or num_of_files == 0: """ Directory is empty - it contains exactly 2 directories - current directory and parent directory (unix) or 0 directories (stm32) """ if include_self: os.rmdir(path) return True raise RuntimeError("Failed to delete folder %s" % path)
def l(command='ls'): global cwd index = 0 command, *args = command.split(" ") if command == 'cd': cwd = args[0] for name, type, inode, size in os.ilistdir(cwd): index += 1 isdir = True if type == 0x4000 else False full_path = '{}/{}'.format(cwd, name) if command == 'ls': print('{} {} {}'.format(index, 'd' if isdir else ' ', name)) if command == 'rm' and str(index) in args and input( 'remove {}? y\\n\n'.format(full_path)) == 'y': rm(full_path, isdir) if command == 'cat' and str(index) in args: with open(full_path, 'r') as fh: line = fh.readline() while line: print(line, end='') line = fh.readline() print() command = input( 'command (rm <file index> <file index>..., cd <abspath>, cat <index>):\n' ) l(command)
def find(target, path='/', filter='^.*\.py$', recurse=False, output=''): # create list of files file_list = list(os.ilistdir(path)) # only recurse through the dirs if needed if recurse: for f in file_list: if f[1] == 16384: find(target, merge(path, f[0]), filter, recurse, output) r = ure.compile(filter) # scan the files for f in file_list: if f[1] == 32768: if filter == '' or r.match(f[0]): scanfile = merge(path, f[0]) h = open(scanfile) linenumber = 1 for line in h: if target in line: hit = '{0}:\t(Line {1})\t{2}'.format( scanfile, linenumber, line) if output != '': with open(output, 'a') as op: op.write(hit) else: print(hit, end='') linenumber += 1 h.close()
def app_start(): cedir = '/' while True: dirlist = [] for item in ilistdir(cedir): dirlist.append(item[0] + ('/' if item[1] == TYPE_DIR else '')) sindex = selectVList(cedir[-16:], dirlist, 0, 1) if sindex == -1: sleep_ms(300) if cedir == '/': return 0 cedir = '/'.join(cedir.split('/')[:-1]) # go back if cedir == '': cedir = '/' continue selected = dirlist[sindex] if selected[-1] == '/': selected = selected[:-1] newpath = cedir + ('' if cedir == '/' else '/') + selected filestats = stat(newpath) if filestats[0] == TYPE_FILE: print("FILE %s" % newpath) msgBox(selected, [ 'TYPE_FILE', 'Size:%dB' % filestats[6], 'Path:', newpath[-16:] ]) else: cedir = newpath
async def select_file(self, extensions): files = sum([[ f[0] for f in os.ilistdir(self.sdpath) if f[0].lower().endswith(ext) and f[1] == 0x8000 ] for ext in extensions], []) if len(files) == 0: raise HostError( "\n\nNo matching files found on the SD card\nAllowed: %s" % ", ".join(extensions)) # elif len(files) == 1: # return self.sdpath+"/"+ files[0] files.sort() buttons = [] for ext in extensions: title = [(None, ext + " files")] barr = [(self.sdpath + "/" + f, self.truncate(f)) for f in files if f.lower().endswith(ext)] if len(barr) == 0: buttons += [(None, "%s files - No files" % ext)] else: buttons += title + barr fname = await self.manager.gui.menu(buttons, title="Select a file", last=(None, "Cancel")) return fname
def getsize(path: str): """Get size of file in bytes. Dirs are not supported.""" filename = path[path.rfind("/") + 1:] for f in os.ilistdir(dirname(path)): if f[0] == filename and f[1] == FILE_TYPE: return f[3] raise FileNotFoundError("No such file or directory: '%s'." % filename)
def load_wallets(self, network_name): self.network = NETWORKS[network_name] fingerprint = hexlify(self.fingerprint).decode() self.storage_path = "%s/%s/%s" % (self.storage_root, network_name, fingerprint) # FIXME: refactor with for loop try: # create network folder d = "/".join(self.storage_path.split("/")[:-1]) os.mkdir(d) except: pass try: os.mkdir(self.storage_path) except: pass files = [ f[0] for f in os.ilistdir(self.storage_path) if f[0].endswith("_wallet.json") ] self._wallets = [] for fname in files: fname = self.storage_path + "/" + fname with open(fname) as f: content = f.read() with open(fname.replace(".json", ".sig"), "rb") as f: sig = ec.Signature.parse(f.read()) if self.idkey.verify(sig, hashes.sha256(content)): self._wallets.append( Wallet.parse(content, self.network, fname=fname)) else: raise RuntimeError("Invalid signature for wallet")
def rmtree(self, directory): for entry in os.ilistdir(directory): if entry[1] == 0x4000: self.rmtree(directory + '/' + entry[0]) else: os.remove(directory + '/' + entry[0]) os.rmdir(directory)
def add_wallet(self, w): self.wallets.append(w) wallet_ids = sorted([int(f[0]) for f in os.ilistdir(self.path) \ if f[0].isdigit() and f[1] == 0x4000]) newpath = self.path + ("/%d" % (max(wallet_ids) + 1)) platform.maybe_mkdir(newpath) w.save(self.keystore, path=newpath)
def logfile_name(): "Returns the first unused logfile name in the format bat<num>.txt" index = 0 for f, *t in os.ilistdir(): m = re.match("bat([0-9]+)\\.txt", f) if m: index = max(index, int(m.group(1))) return "bat{}.txt".format(index + 1)
def is_key_saved(self): flash_files = [ f[0] for f in os.ilistdir(self.flashpath) if f[0].lower().startswith(self.fileprefix(self.flashpath)) ] flash_exists = (len(flash_files) > 0) if not platform.is_sd_present(): return flash_exists platform.mount_sdcard() sd_files = [ f[0] for f in os.ilistdir(self.sdpath) if f[0].lower().startswith(self.fileprefix(self.sdpath)) ] sd_exists = (len(sd_files) > 0) platform.unmount_sdcard() return sd_exists or flash_exists
def __main__(args): _print_mount_stats("/") for pt in os.ilistdir("/"): f = pt[0] if len(pt) == 3: #Currently means vfs mount point print("") _print_mount_stats("/" + f)
def __find_file(self): ld = os.ilistdir() fn = None for f in ld: if f[0].endswith(".env"): fn = f[0] break return fn
def get_wallet_fname(self): files = [int(f[0].split("_")[0]) for f in os.ilistdir(self.storage_path) if f[0].endswith("_wallet.json")] if len(files) > 0: idx = max(files)+1 else: idx = 0 fname = self.storage_path+"/"+("%d_wallet.json" % idx) return fname
def _rmtree(self, directory): for entry in os.ilistdir(directory): is_dir = entry[1] == 0x4000 if is_dir: self._rmtree(directory + '/' + entry[0]) else: os.remove(directory + '/' + entry[0]) os.rmdir(directory)
def deleteFolder(RPATH): if RPATH[-1] == '/': RPATH = RPATH[:-1] for x in os.ilistdir(RPATH): if x[1] == 0x4000: #TYPE_DIR deleteFolder(RPATH + '/' + x[0]) else: os.remove(RPATH + '/' + x[0]) os.rmdir(RPATH)
def isfile(path: str): """Check if both a file exists and if it is a file. Original isfile does follow symlinks, this implementation does not.""" if isdir(dirname(path)): filename = path[path.rfind("/") + 1:] for f in os.ilistdir(dirname(path)): if f[0] == filename and f[1] == FILE_TYPE: return True return False
def rm(path, isdir): print('--- rm {}'.format(path)) if isdir: for name, type, inode, size in os.ilistdir(path): isdir = True if type == 0x4000 else False rm('{}/{}'.format(path, name), isdir) os.rmdir(path) else: os.remove(path)
def rmtree(self, directory): print("Remove Directory: %s" % directory) for entry in os.ilistdir(directory): is_dir = entry[1] == 0x4000 if is_dir: self.rmtree(directory + '/' + entry[0]) else: os.remove(directory + '/' + entry[0]) os.rmdir(directory)
def test_create_config(self): """Test initial config creation""" ks = self.get_keystore() ks.init() files = [f[0] for f in os.ilistdir(TEST_DIR)] self.assertTrue("secret" in files) self.assertTrue("pin" in files) self.assertEqual(ks.is_pin_set, False) self.assertEqual(ks.pin_attempts_left, ks.pin_attempts_max) self.assertTrue(ks.pin_attempts_left is not None)
def _copy_directory(self, fromPath, toPath): if not self._exists_dir(toPath): self._mk_dirs(toPath) for entry in os.ilistdir(fromPath): is_dir = entry[1] == 0x4000 if is_dir: self._copy_directory(fromPath + '/' + entry[0], toPath + '/' + entry[0]) else: self._copy_file(fromPath + '/' + entry[0], toPath + '/' + entry[0])
def _list_files(self): files = [stat[0] for stat in os.ilistdir() if stat[0] != '.' and stat[0] != '..'] con = self._con for f in files: self._send_byte(FlashProtocol.NEW_FILE_NAME) con.write(struct.pack('I', len(f))) con.write(f.encode('utf-8')) self._send_byte(FlashProtocol.LIST_FILES_EXIT)
def rmtree(self, directory): # Metodo usado para apagar arquivos ou diretorios passados por parametro for entry in os.ilistdir(directory): is_dir = entry[1] == 0x4000 if is_dir: self.rmtree(directory + '/' + entry[0]) else: os.remove(directory + '/' + entry[0]) os.rmdir(directory)
def test_change_secret(self): """Test wipe exception if secret is changed""" # create keystore ks = self.get_keystore() init_keystore(ks) files = [f[0] for f in os.ilistdir(TEST_DIR)] self.assertTrue("secret" in files) self.assertTrue("pin" in files) # now change secret value with open(TEST_DIR + "/secret", "wb") as f: # a different value f.write(b"5" * 32) ks = FlashKeyStore() # check it raises with self.assertRaises(platform.CriticalErrorWipeImmediately): init_keystore(ks) # files are deleted files = [f[0] for f in os.ilistdir(TEST_DIR)] self.assertFalse("secret" in files) self.assertFalse("pin" in files)
def rm_rf(fn): try: for sub in ilistdir(fn): if sub[0] not in ('.', '..'): rm_rf(fn + '/' + sub[0]) os.rmdir(fn) except Exception as e: try: os.remove(fn) except Exception as e: print('WARNING: rm(%s) failed: %s' % (fn, e))
def rmtree(self, directory): """Remove the directory tree.""" for entry in os.ilistdir(directory): is_dir = (entry[1] == 0x4000 ) # 0x4000 for directories and 0x8000 for regular files if is_dir: self.rmtree(directory + '/' + entry[0]) # Recurse into subdirectory else: os.remove(directory + '/' + entry[0]) # Remove this object os.rmdir(directory) # Remove the now empty directory.
def rm(d): # Remove file or tree try: if os.stat(d)[0] == 16384: # Dir for f in os.ilistdir(d): rm("/".join((d, f[0]))) # File or Dir os.rmdir(d) else: # File os.remove(d) except: print("rm of '%s' failed" % d)