예제 #1
0
    def remove(self):
        try:
            remove(FILE)
        except OSError:
            pass

        self.net_id = self.motor_reversed = None
예제 #2
0
def try_remove(fn: str) -> None:
    """Try to remove a file if it existst."""
    try:
        os.remove(fn)
    except OSError:
        print("LOG remove error")
        pass
예제 #3
0
파일: config.py 프로젝트: educoay/Dobby
def Load(Config_Name=None, Delete_On_Error=True, Full_Path=None):
    # Reads config /<Path>/<Name>.json and returns a dict containing json from file
    # Unless Full_Path is specified, Full_Path has to contain the full path including file name
    # Returns false if unable to load config

    # Add .json to name if not already there
    if Config_Name.endswith(".json") == False:
        Config_Name = Config_Name + ".json"

    # Check if we got a path to load
    if Config_Name == None and Full_Path == None:
        raise Error("Unable to read config, no config name or full path given")

    if Full_Path == None:
        Full_Path = '/conf/' + Config_Name

    # Check if we got a config store on local fs
    try:
        with open(Full_Path, 'r') as f:
            Config = ujson.load(f)
        return Config

    # No config store on fs or other error
    except OSError:
        raise Error("Unable to read config path: " + Full_Path)
    except ValueError:
        # if fails, delete config file if told to do so
        if Delete_On_Error == True:
            if Full_Path != None:
                uos.remove(Full_Path)
            else:
                uos.remove("/conf/" + Config_Name)
            # return false to indicate failure
            raise Error("Bad config: " + Config_Name +
                        " deleted the config file")
예제 #4
0
def main():
    status = get_daemon_status()

    print("WebREPL daemon auto-start status:", "enabled" if status else "disabled")
    print("\nWould you like to (E)nable or (D)isable it running on boot?")
    print("(Empty line to quit)")
    resp = input("> ").upper()

    if resp == "E":
        if exists(CONFIG):
            resp2 = input_choice("Would you like to change WebREPL password? (y/n) ", ("y", "n", ""))
        else:
            print("To enable WebREPL, you must set password for it")
            resp2 = "y"

        if resp2 == "y":
            try:
                os.remove(CONFIG)
            except:
                pass
            passwd = input_pass()
            with open(CONFIG, "w") as f:
                f.write("PASS = %r\n" % passwd)


    if resp not in ("D", "E") or (resp == "D" and not status) or (resp == "E" and status):
        print("No further action required")
        sys.exit()

    change_daemon(resp == "E")

    print("Changes will be activated after reboot")
    resp = input_choice("Would you like to reboot now? (y/n) ", ("y", "n", ""))
    if resp == "y":
        machine.reset()
예제 #5
0
def delete_file(fn):
    # "unlink" gets renamed to "remove" in micropython,
    # so support both
    if hasattr(os, 'unlink'):
        os.unlink(fn)
    else:
        os.remove(fn)
예제 #6
0
    def format(self):
        import uos
        log.info("Formatting filesystem ...")

        while uos.listdir("/"):
            lst = uos.listdir("/")
            uos.chdir("/")
            while lst:
                try:
                    uos.remove(lst[0])
                    log.info("Removed '" + uos.getcwd() + "/" + lst[0] + "'")
                    lst = uos.listdir(uos.getcwd())
                except:
                    dir = lst[0]
                    log.info("Directory '" + uos.getcwd() + "/" + dir +
                             "' detected. Opening it...")
                    uos.chdir(dir)
                    lst = uos.listdir(uos.getcwd())
                    if len(lst) == 0:
                        log.info("Directory '" + uos.getcwd() +
                                 "' is empty. Removing it...")
                        uos.chdir("..")
                        uos.rmdir(dir)
                        break

        log.info("Format completed successfully")
예제 #7
0
    def DeleteAll(self):
        for file in self.List():
            print("[LogFileMngr] Deleting {}".format(file))
            os.remove(file)

        self.Last = self.First = self.LineCount = 0
        self.SFile.WriteData(0, self.First, self.Last, self.LineCount)
예제 #8
0
def delete_any_dot_py_files(logger):
    """
    delete_any_dot_py_files removes any .py files from the XBee filesystem.

    This function should be invoked at the top of main.py/main.mpy before importing any custom modules.

    Rationale: .py files have priority over .mpy files in MicroPython "import" statements.
    Since we've deployed our application as .mpy files, we don't want any .py files with
    the same name to be imported instead. For example, "import common" should load
    common.mpy instead of common.py. This prevents surprises during development if
    you have old .py versions of the code on the device. More importantly, this is
    a security thing-- we want to stop someone from loading malicious .py files
    with the same names as our .mpy files.

    Note that the Connect Sensor C code must handle removal of main.py. The reason is that
    we deploy main.mpy to the device but if the device already contained a main.py, the latter
    version of main would be invoked and thus this function would never have a chance to run!
    """
    try:
        for filename in uos.listdir("/flash"):
            if filename.endswith(".py"):
                fullpath = "/flash/" + filename
                uos.remove(fullpath)
    except Exception as ex:
        logger.print("delete_any_dot_py_files: Exception occurred. Details: %s" % ex)
    def try_connect_from_file(self):
        print("Trying to load WiFi credentials from {:s}".format(
            self.CRED_FILE))
        try:
            os.stat(self.CRED_FILE)
        except OSError as e:
            if e.args[0] == uerrno.ENOENT:
                print("{:s} does not exist".format(self.CRED_FILE))
                return False

        contents = open(self.CRED_FILE, "rb").read().split(b",")
        if len(contents) == 2:
            self.ssid, self.password = contents
        else:
            print("Invalid credentials file:", contents)
            return False

        if not self.connect_to_wifi():
            print(
                "Failed to connect with stored credentials, starting captive portal"
            )
            os.remove(self.CRED_FILE)
            return False

        return True
예제 #10
0
def clear_cfg():
    try:
        uos.remove("obi_socket.cfg")
    except:
        pass
    else:
        pass
예제 #11
0
def cleanup():
    logging.info('Starting cleanup...')
    dir = uos.listdir()
    for f in dir:
        if f.endswith('.log'):
            logging.info('Found file: {}', f)
            try:
                year = int(f[:4])
                month = int(f[4:6])
                mday = int(f[6:8])
                filedate = time.mktime((year, month, mday, 0, 0, 0, 0, 0))
                year, month, mday, hour, minute, second, weekday, yearday = time.localtime(
                )
                two_days_ago = time.mktime(
                    (year, month, mday - 2, 0, 0, 0, 0, 0))
                if filedate < two_days_ago:
                    logging.debug('Removing...')
                    uos.remove(f)
                else:
                    logging.debug('Keeping...')

            except Exception as e:
                # logging.error('ERROR: cleanup {}', str(e))
                logging.debug('Skipping...')
                pass
    logging.info('Cleanup ended')
예제 #12
0
def rmvdir(dir):
    for i in os.ilistdir(dir):
        if i[1] == 16384:
            rmvdir('{}/{}'.format(dir, i))
        elif i[1] == 32678:
            os.remove('{}/{}'.format(dir, i[0]))
    os.rmdir(dir)
예제 #13
0
    def remove(self):
        try:
            remove(FILE)
        except OSError:
            pass

        self.net_id = self.group = self.state1 = self.state2 = None
    def write_jpeg_image(self, img):
        img.save(self.tmp_path)
        stat = uos.stat(self.tmp_path)
        #print("tmp_path=", self.tmp_path, stat)
        size = stat[6]
        #print("size=", size)

        tmp_f = open(self.tmp_path, "rb")
        #r_len_sum = 0
        #w_len_sum = 0

        self.bin_f.write("jpeg\x00")  # key=jpeg
        self.bin_f.write(size.to_bytes(4, 'big'))  # 4 byte length
        while True:
            data = tmp_f.read(256)
            r_len = len(data)
            #print("r_len=", r_len)
            if 0 < r_len:
                #r_len_sum += r_len
                w_len = self.bin_f.write(data)
                #w_len_sum += w_len
                #print("w_len=", w_len)
            else:
                #print("r_len_sum=", r_len_sum, " w_len_sum=", w_len_sum)
                break
            data = None
        self.bin_f.flush()
        tmp_f.close()
        uos.remove(self.tmp_path)
        self._write_jpeg_count += 1
예제 #15
0
 def _NetConFileDelete(self):
     print("[NetCon] Deleting file {}".format(self.RootDir +
                                              self.PATH_NET_CON))
     try:
         os.remove(self.RootDir + self.PATH_NET_CON)
     except OSError:
         pass
예제 #16
0
def remove_file(path, sock=None):
    try:
        uos.remove(path)
    except:
        out = "could not remove %s" % path
        print(out)
        send_output(sock, out)
예제 #17
0
def fimage(x, y, file, type=1):
    if file[:3] == '/sd':
        utils.filecp(file, '/flash/fcache', blocksize=8192)
        lcd.image(x, y, '/flash/fcache', 0, type)
        os.remove('/flash/fcache')
    else:
        lcd.image(x, y, file, 0, type)
예제 #18
0
def clean_dir(file):
    """Removes unwanted files.

    Params:
        file(str)
    """
    uos.remove(file)
예제 #19
0
파일: core.py 프로젝트: straga/upy_archive
 async def DELE(self, stream, argument):
     try:
         uos.remove(self.get_path(argument))
         await _awrite(stream, "257 Okey.\r\n")
     except Exception as e:
         await _awrite(stream, "550 {}.\r\n".format(e))
     return True
예제 #20
0
 async def DELE(self, stream, argument):
     try:
         os.remove(argument)
         await stream.awrite("257 Okey.\r\n")
     except OSError as e:
         await stream.awrite("550 {}.\r\n".format(e))
     return True
예제 #21
0
    def capture_to_file(self, fn, overwrite):
        # bit 0 - clear FIFO write done flag
        cam_spi_write(b'\x04', b'\x01', self.hspi, self.cspin)
        cam_spi_write(b'\x01', b'\x00', self.hspi, self.cspin)
        # bit 1 - start capture then read status
        cam_spi_write(b'\x04', b'\x02', self.hspi, self.cspin)
        #time.sleep_ms(10)

        # read status
        res = cam_spi_read(b'\x41', self.hspi, self.cspin)
        cnt = 0
        #if (res == b'\x00'):
        #    print("initiate capture may have failed, return byte: %s" % ubinascii.hexlify(res))

        # read the image from the camera fifo
        while True:
            res = cam_spi_read(b'\x41', self.hspi, self.cspin)
            mask = b'\x08'
            if (res[0] & mask[0]):
                break
            #print("continuing, res register %s" % ubinascii.hexlify(res))
            #time.sleep_ms(10)
            cnt += 1
        #print("slept in loop %d times" % cnt)

        # read the fifo size
        b1 = cam_spi_read(b'\x44', self.hspi, self.cspin)
        b2 = cam_spi_read(b'\x43', self.hspi, self.cspin)
        b3 = cam_spi_read(b'\x42', self.hspi, self.cspin)
        val = b1[0] << 16 | b2[0] << 8 | b3[0]
        print("ov2640_capture: %d bytes in fifo" % val)
        gc.collect()

        bytebuf = [ 0, 0 ]
        picbuf = [ b'\x00' ] * PICBUFSIZE
        l = 0
        bp = 0
        if (overwrite == True):
            #print("deleting old file %s" % fn)
            try:
                uos.remove(fn)
            except OSError:
                pass
        while ((bytebuf[0] != b'\xd9') or (bytebuf[1] != b'\xff')):
            bytebuf[1] = bytebuf[0]
            if (bp > (len(picbuf) - 1)):
                #print("appending buffer to %s" % fn)
                appendbuf(fn, picbuf, bp)
                bp = 0

            bytebuf[0] = cam_spi_read(b'\x3d', self.hspi, self.cspin)
            l += 1
            #print("read so far: %d, next byte: %s" % (l, ubinascii.hexlify(bytebuf[0])))
            picbuf[bp] = bytebuf[0]
            bp += 1
        if (bp > 0):
            #print("appending final buffer to %s" % fn)
            appendbuf(fn, picbuf, bp)
        print("read %d bytes from fifo, camera said %d were available" % (l, val))
        return (l)
예제 #22
0
 def delete(cls, pkey, fail_silently=False):
     fname = cls.fname(pkey)
     try:
         uos.remove(fname)
     except OSError as e:
         if fail_silently:
             print(e)
예제 #23
0
    def remove_database(self, name):
        name_ = name

        if not name_.endswith(".brain"):
            name_ = name + ".brain"

        try:
            display = ""

            if name_ == self._name:
                display = "Erasing current database => '{}' ".format(name_)
                with open("{}/{}".format(DB_FOLDER, name_), "w") as erase:
                    erase.write("")
                    erase.close()
                self._initialize()

            elif name_ != self._name:
                display = "Removing Database => '{}' ".format(name_)
                uos.remove("{}/{}".format(DB_FOLDER, name_))

            if self._verbose == 1:
                return display

        except OSError:
            return "Database => '{}' not found".format(name_)
예제 #24
0
    def remove(self):
        try:
            remove(FILE)
        except OSError:
            pass

        self.net_id = self.state = self.color = None
예제 #25
0
def change_daemon(action):
    LINES = ("import webrepl", "webrepl.start()")
    old_lines = []

    with open(RC) as old_f:
        for line in old_f:
            old_lines.append(line)
    os.remove(RC)

    with open(RC , "w") as new_f:
        found = False
        for l in old_lines:
            for patt in LINES:
                if patt in l:
                    found = True
                    if action and l.startswith("#"):
                        l = l[1:]
                    elif not action and not l.startswith("#"):
                        l = "#" + l
            new_f.write(l)
        if not found:
            new_f.write("\nimport webrepl\n")
            new_f.write("import web\n")
            new_f.write("web.ap_init()\n")
            new_f.write("webrepl.start()\n")
예제 #26
0
def del_pin_from_flash(pin_file: str) -> bool:
    """ deletes the given pin_file; returns true if found and deleted """
    if pin_file in os.listdir():
        os.remove(pin_file)

        return True

    return False
예제 #27
0
 def remove_wifi_setup(self):
     """ Remove configuration file.
     """
     try:
         uos.remove(self.WIFI_CFG_FILE)
         print("WIFI configuration removed")
     except:
         print("File {} not found".format(self.WIFI_CFG_FILE))
예제 #28
0
def mode(mode, ssid, pw):
    try:
        uos.remove('ap.py')
    except:
        pass
    with open('ap.py', 'w') as f:
        f.write('\nmode="' + mode + '"\n')
        f.write('ssid="' + ssid + '"\n')
        f.write('pw="' + pw + '"\n')
예제 #29
0
def enable_boot():
    l = uos.listdir()
    if "boot.disabled" in l:
        if "boot.py" in l:
            uos.remove("boot.py")

        uos.rename("boot.disabled", "boot.py")
    else:
        print("Unable to enable boot! Most likely is boot not disabled")
예제 #30
0
 def test_ConstructorWithUserMeta(self):
     user_meta_fmt = "<II"
     os.remove(test_StructFile.TEST_FILE)
     sf = StructFile.StructFile(test_StructFile.TEST_FILE,
                                test_StructFile.TEST_FMT, user_meta_fmt)
     self.assertEqual(sf.DataSize,
                      ustruct.calcsize(test_StructFile.TEST_FMT))
     file_exists = TestUtil.FileExists(test_StructFile.TEST_FILE)
     self.assertTrue(file_exists)
예제 #31
0
def rm_r(dir: str) -> None:
    os.chdir(dir)
    for f in os.listdir():
        try:
            os.remove(f)
        except OSError:
            pass
    for f in os.listdir():
        rm_r(f)
    os.chdir("..")
    os.rmdir(dir)
예제 #32
0
def rm_if_not_required(file: str) -> None:
    if file not in required_files:
        try:
            os.remove(file)
        except OSError:
            pass
예제 #33
0
    uos.mkdir('/test_mnt')
except OSError:
    print('OSError')

# rename across a filesystem
try:
    uos.rename('/test_mnt/a', '/test_mnt2/b')
except OSError:
    print('OSError')

# delegating to mounted filesystem
uos.chdir('test_mnt')
print(uos.listdir())
print(uos.getcwd())
uos.mkdir('test_dir')
uos.remove('test_file')
uos.rename('test_file', 'test_file2')
uos.rmdir('test_dir')
print(uos.stat('test_file'))
print(uos.statvfs('/test_mnt'))
open('test_file')
open('test_file', 'wb')

# umount
uos.umount('/test_mnt')
uos.umount('/test_mnt2')

# umount a non-existent mount point
try:
    uos.umount('/test_mnt')
except OSError:
예제 #34
0
    try:
        uos.mkdir(exist)
    except OSError as er:
        print('mkdir OSError', er.args[0] == 17) # EEXIST

uos.chdir('/')
print(uos.stat('test5.txt')[:-3])

uos.VfsFat.mkfs(bdev2)
uos.mount(bdev2, '/sys')
print(uos.listdir())
print(uos.listdir('sys'))
print(uos.listdir('/sys'))

uos.rmdir('dir2')
uos.remove('test5.txt')
print(uos.listdir())

uos.umount('/')
print(uos.getcwd())
print(uos.listdir())
print(uos.listdir('sys'))

# test importing a file from a mounted FS
import sys
sys.path.clear()
sys.path.append('/sys')
with open('sys/test_module.py', 'w') as f:
    f.write('print("test_module!")')
import test_module
예제 #35
0
try:
    import uos as os
except ImportError:
    import os

if not hasattr(os, "remove"):
    print("SKIP")
    raise SystemExit

# cleanup in case testfile exists
try:
    os.remove("testfile")
except OSError:
    pass

try:
    f = open("testfile", "r+b")
    print("Unexpectedly opened non-existing file")
except OSError:
    print("Expected OSError")
    pass

f = open("testfile", "w+b")
f.write(b"1234567890")
f.seek(0)
print(f.read())
f.close()

# Open with truncation
f = open("testfile", "w+b")
f.write(b"abcdefg")