コード例 #1
0
def change_dir(path, sock=None):
    try:
        uos.chdir(path)
    except:
        out = "not a directory"
        print(out)
        send_output(sock, out)
コード例 #2
0
ファイル: pye.py プロジェクト: soft9000/Micropython-Editor
 def get_file(self, fname):
     if fname:
         try:
             self.fname = fname
             if fname in ('.', '..') or (os.stat(fname)[0] & 0x4000): ## Dir
                 os.chdir(fname)
                 self.work_dir = os.getcwd()  # let the os module do the normalization
                 self.fname = "/" if self.work_dir == "/" else self.work_dir.split("/")[-1]
                 self.content = ["Directory '{}'".format(self.work_dir), ""] + sorted(os.listdir('.'))
                 self.is_dir = True
             else:
                 if is_micropython:
                     with open(fname) as f:
                         self.content = f.readlines()
                 else:
                     with open(fname, errors="ignore") as f:
                         self.content = f.readlines()
                 self.write_tabs = False
                 i = 0
                 for l in self.content:
                     self.content[i] = self.expandtabs(l.rstrip())
                     i += 1
         except OSError:
             self.message = "Error: file '" + fname + "' may not exist"
     self.hash = self.hash_buffer()
コード例 #3
0
 def edit_loop(self):
     if not self.content:
         self.content = [""]
     self.total_lines = len(self.content)
     os.chdir(self.work_dir)
     self.redraw(self.message == "")
     while True:
         self.display_window()
         key, char = self.get_input()
         self.message = ''
         key = self.handle_edit_keys(key, char)
         if key == KEY_QUIT:
             if self.hash != self.hash_buffer():
                 res = self.line_edit("File changed! Quit (y/N)? ", "N")
                 if not res or res[0].upper() != 'Y':
                     continue
             self.scroll_region(0)
             self.mouse_reporting(False)
             self.goto(Editor.height, 0)
             self.clear_to_eol()
             self.undo = []
             return key
         elif key == KEY_NEXT:
             return key
         elif key == KEY_GET:
             if self.mark is not None:
                 self.clear_mark()
                 self.display_window()
             return key
コード例 #4
0
ファイル: pye.py プロジェクト: soft9000/Micropython-Editor
    def edit_loop(self): ## main editing loop
        if not self.content: ## ensure content
            self.content = [""]
        self.total_lines = len(self.content)
        os.chdir(self.work_dir)
        self.redraw(self.message == "")

        while True:
            self.display_window()  ## Update & display window
            key, char = self.get_input()  ## Get Char of Fct-key code
            self.message = '' ## clear message

            if key == KEY_QUIT:
                if self.hash != self.hash_buffer():
                    res = self.line_edit("File changed! Quit (y/N)? ", "N")
                    if not res or res[0].upper() != 'Y':
                        continue
                self.scroll_region(0)
                self.mouse_reporting(False) ## disable mouse reporting
                self.goto(Editor.height, 0)
                self.clear_to_eol()
                self.undo = []
                return key
            elif key == KEY_NEXT:
                return key
            elif key == KEY_GET:
                if self.mark is not None:
                    self.mark = None
                    self.display_window()  ## Update & display window
                return key
            else:
                self.handle_edit_keys(key, char)
コード例 #5
0
def test(bdev, vfs_class):
    print("test", vfs_class)

    # mkfs
    vfs_class.mkfs(bdev)

    # construction
    vfs = vfs_class(bdev)

    # mount
    uos.mount(vfs, "/lfs")

    # import
    with open("/lfs/lfsmod.py", "w") as f:
        f.write('print("hello from lfs")\n')
    import lfsmod

    # import package
    uos.mkdir("/lfs/lfspkg")
    with open("/lfs/lfspkg/__init__.py", "w") as f:
        f.write('print("package")\n')
    import lfspkg

    # chdir and import module from current directory (needs "" in sys.path)
    uos.mkdir("/lfs/subdir")
    uos.chdir("/lfs/subdir")
    uos.rename("/lfs/lfsmod.py", "/lfs/subdir/lfsmod2.py")
    import lfsmod2

    # umount
    uos.umount("/lfs")

    # clear imported modules
    sys.modules.clear()
コード例 #6
0
def setup():
    check_bootsec()
    print("Performing initial setup")
    uos.VfsFat.mkfs(bdev)
    vfs = uos.VfsFat(bdev)
    uos.mount(vfs, '/flash')
    uos.chdir('/flash')
    with open("boot.py", "w") as f:
        f.write("""\
# This file is executed on every boot (including wake-boot from deepsleep)
import badge, machine, esp, ugfx
badge.init()
ugfx.init()
esp.rtcmem_write(0,0)
esp.rtcmem_write(1,0)
if machine.reset_cause() != machine.DEEPSLEEP_RESET:
    print("cold boot")
    import splash
else:
    print("wake from sleep")
    load_me = esp.rtcmem_read_string()
    if load_me != "":
        print("starting %s", load_me)
        esp.rtcmem_write_string("")
        __import__(load_me)
    else:
        import splash
""")
    return vfs
コード例 #7
0
def publish_Backup():
    global msg_payload
    global payload_Topic
    global daily_Topic
    global precip_Topic
    global topic_ToSend
    global msg_ToSend
    global obs_publishReady
    global topic_File
    global msg_File
    global root_Path

    uos.chdir(root_Path)
    topic_ToSend.append(payload_Topic)
    msg_ToSend.append(msg_payload)
    obs_publishReady = obs_publishReady + 1

    if (payload_Topic == daily_Topic or payload_Topic == precip_Topic):
        log = uio.open(topic_File, mode="a")
        log.write(payload_Topic + "\n")
        time.sleep(0.5)
        log.close()
        log1 = uio.open(msg_File, mode="a")
        log1.write(msg_payload + "\n")
        time.sleep(0.5)
        log1.close()

    msg_payload = ""
    payload_Topic = ""
コード例 #8
0
 async def CWD(self, stream, argument):
     log.info("CWD argument is %s" % argument)
     try:
         os.chdir(argument)
         await stream.awrite("250 Okey.\r\n")
     except OSError as e:
         await stream.awrite("550 {}.\r\n".format(e))
     return True
コード例 #9
0
ファイル: __init__.py プロジェクト: straga/upy_archive
 async def CWD(self, stream, argument):
     log.debug("CWD argument is %s" % argument)
     try:
         uos.chdir(self.get_path(argument))
         await stream.awrite("250 Okey.\r\n")
     except Exception as e:
         await stream.awrite("550 {}.\r\n".format(e))
     return True
コード例 #10
0
def connect(host, port):
    global disk
    log("Connecting to " + host + ":" + str(port))
    disk = Socketdisk(host, port)
    vfs = uos.VfsFat(disk)
    uos.mount(vfs, "/__livereload__")
    uos.chdir("/__livereload__")
    sys.path.insert(0, "/__livereload__/lib")
    sys.path.insert(0, "/__livereload__")
コード例 #11
0
ファイル: image_convert.py プロジェクト: Michutt/e-visitcard
def generate_new_files():
    uos.chdir("images/generated")
    files = uos.listdir()
    uos.chdir("/flash")
    files1 = uos.listdir()
    for file in files:
        if file[-4:] == ".bmp":
            byte_image = convert_image("images/generated/" + file)
            save_image(byte_image, file)
コード例 #12
0
ファイル: __init__.py プロジェクト: straga/upy_archive
 async def CDUP(self, stream, argument):
     argument = '..' if not argument else '..'
     log.debug("CDUP argument is %s" % argument)
     try:
         uos.chdir(self.get_path(argument))
         await stream.awrite("250 Okey.\r\n")
     except Exception as e:
         await stream.awrite("550 {}.\r\n".format(e))
     return True
コード例 #13
0
def face_recog(calc_time, vi_ip):
    pin = pyb.millis()
    print(pin)
    print(calc_time)
    cc = 0
    #pyb.elapsed_millis(start)
    while pyb.elapsed_millis(pin) < calc_time:
        print("top of face recog function")
        #snapshot on face detection
        RED_LED_PIN = 1
        BLUE_LED_PIN = 3
        sensor.reset()  # Initialize the camera sensor.
        sensor.set_contrast(3)
        sensor.set_gainceiling(16)
        sensor.set_pixformat(sensor.GRAYSCALE)
        sensor.set_framesize(sensor.HQVGA)  # or sensor.QQVGA (or others)
        #sensor.alloc_extra_fb()
        sensor.skip_frames(time=2000)  # Let new settings take affect.
        face_cascade = image.HaarCascade("frontalface", stages=25)
        uos.chdir("/")
        pyb.LED(RED_LED_PIN).on()
        print("About to start detecting faces...")
        sensor.skip_frames(time=2000)  # Give the user time to get ready.
        pyb.LED(RED_LED_PIN).off()
        print("Now detecting faces!")
        pyb.LED(BLUE_LED_PIN).on()
        diff = 10  # We'll say we detected a face after 10 frames.
        try:
            while (diff):
                img = sensor.snapshot()
                sensor.alloc_extra_fb(img.width(), img.height(),
                                      sensor.GRAYSCALE)
                faces = img.find_features(face_cascade,
                                          threshold=0.5,
                                          scale_factor=1.5)
                sensor.dealloc_extra_fb()
                if faces:
                    diff -= 1
                    for r in faces:
                        img.draw_rectangle(r)
                elif (pyb.elapsed_millis(pin)) > calc_time:
                    raise Exception
            pyb.LED(BLUE_LED_PIN).off()
            print("Face detected! Saving image...")
            pic_name = "snapshot-person.pgm"
            sensor.snapshot().save(
                pic_name)  # Save Pic. to root of SD card -- uos.chdir("/")
            pyb.delay(100)
            facial_recog(pic_name, vi_ip)
            gc.collect()
        except Exception as go:
            print("we are in exception")
            pyb.LED(BLUE_LED_PIN).off()
            gc.collect()
コード例 #14
0
def ftps_downloadFile(fileport=0, sz=0, df_chunk=1000):
    global temp_File
    global topic_ToSend
    global msg_ToSend
    global msg_Topic
    global obs_publishReady
    global wdt
    global temp_Path
    global file_szRcvd

    file_Size = sz
    data_Received = 0
    uos.chdir(temp_Path)
    log = uio.open(temp_File, mode="w")
    try:
        ftp_conn2 = FTP(port=fileport, user=None, passwd=None, timeout=20)
        ftp_conn2.download(port=fileport)
        time.sleep(5)
    except:
        log.close()
        topic_ToSend.append(msg_Topic)
        msg_ToSend.append("Could not Access FTPS for download")
        obs_publishReady = obs_publishReady + 1
    else:
        excess_Data = file_Size % df_chunk
        while (data_Received < file_Size):
            if ((file_Size - data_Received) > df_chunk):
                try:
                    data = ftp_conn2.rcv(df_chunk)
                except OSError:
                    pass
                else:
                    data_Received = data_Received + len(data)
                    wdt.feed()
                    if len(data) > 0:
                        log.write(data)
                        time.sleep(0.5)
                    else:
                        pass
            else:
                try:
                    data = ftp_conn2.rcv(excess_Data)
                except OSError:
                    pass
                else:
                    data_Received = data_Received + len(data)
                    wdt.feed()
                    if len(data) > 0:
                        log.write(data)
                        time.sleep(0.5)
                    else:
                        pass
    log.close()
    file_szRcvd = data_Received
コード例 #15
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)
コード例 #16
0
def filesys_get_sta(path='/'):
    '''
    {"f1_name":[size], "f2_name":[size]}
    '''
    cur_path = os.getcwd()
    os.chdir(path)
    ret = {}
    for item in os.listdir():
        ret.update({item: os.stat(item)[6]})

    return ret
コード例 #17
0
ファイル: pye.py プロジェクト: soft9000/Micropython-Editor
def pye_edit(content, tab_size=4, undo=50, io_device=None):
## prepare content
    ## test, if the IO class if provided
    if io_device is None:
        print("IO device not defined")
        return

    gc.collect() ## all (memory) is mine
    index = 0
    undo = max(4, (undo if type(undo) is int else 0)) # minimum undo size
    current_dir = os.getcwd()  ## remember current dir
    if content:
        slot = []
        for f in content:
            slot.append(Editor(tab_size, undo, io_device))
            if type(f) == str and f: ## String = non-empty Filename
                try:
                    slot[index].get_file(f)
                except Exception as err:
                    slot[index].message = "{!r}".format(err)
            else:
                try:
                    slot[index].content = [str(_) for _ in f] ## iterable item -> make strings and edit
                except:
                    slot[index].content = [str(f)]
            index += 1
    else:
        slot = [Editor(tab_size, undo, io_device)]
        slot[0].get_file(current_dir)
## edit
    while True:
        try:
            index %= len(slot)
            key = slot[index].edit_loop()  ## edit buffer
            if key == KEY_QUIT:
                if len(slot) == 1: ## the last man standing is kept
                    break
                del slot[index]
            elif key == KEY_GET:
                f = slot[index].line_edit("Open file: ", "", "_.-")
                if f is not None:
                    slot.append(Editor(tab_size, undo,io_device))
                    index = len(slot) - 1
                    slot[index].get_file(f)
            elif key == KEY_NEXT:
                index += 1
        except Exception as err:
            slot[index].message = "{!r}".format(err)
            ## raise
## All windows closed, clean up
    Editor.yank_buffer = []
## close
    os.chdir(current_dir)  ## restore dir
    return slot[0].content if (slot[0].fname == "") else slot[0].fname
コード例 #18
0
ファイル: inisetup.py プロジェクト: ztech-top/micropython
def setup():
    check_bootsec()
    print("Performing initial setup")
    uos.VfsFat.mkfs(bdev)
    vfs = uos.VfsFat(bdev)
    uos.mount(vfs, '/flash')
    uos.chdir('/flash')
    with open("boot.py", "w") as f:
        f.write("""\
# This file is executed on every boot (including wake-boot from deepsleep)
""")
    return vfs
コード例 #19
0
def face_detect(init_start, calc_time):
    print("~~~~~~~~~~~~~~~~FACE_DETECT~~~~~~~~~~~~~~~~~~~~~~")
    gc.collect()  #garbage collection
    while pyb.elapsed_millis(init_start) < calc_time:  #while time not expired
        #snapshot on face detection
        RED_LED_PIN = 1
        BLUE_LED_PIN = 3
        sensor.reset()  # Initialize the camera sensor.
        sensor.set_contrast(3)  #set to highest contrast setting
        sensor.set_gainceiling(16)
        sensor.set_pixformat(
            sensor.GRAYSCALE)  #grayscale for facial recognition
        sensor.set_framesize(sensor.HQVGA)
        sensor.skip_frames(time=2000)  # Let new settings take affect.
        face_cascade = image.HaarCascade(
            "frontalface",
            stages=25)  #Using Frontal Face Haar Cascade Classifier
        uos.chdir("/")
        pyb.LED(RED_LED_PIN).on()
        print("About to start detecting faces...")
        sensor.skip_frames(time=2000)  # Give the user time to get ready.
        pyb.LED(RED_LED_PIN).off()
        print("Now detecting faces!")
        pyb.LED(BLUE_LED_PIN).on()
        diff = 10  # We'll say we detected a face after 10 frames.
        try:
            while (diff):
                img = sensor.snapshot()
                sensor.alloc_extra_fb(
                    img.width(), img.height(),
                    sensor.GRAYSCALE)  #allocate more space for image
                faces = img.find_features(
                    face_cascade, threshold=0.5,
                    scale_factor=1.5)  #detecting face features
                sensor.dealloc_extra_fb()
                if faces:
                    diff -= 1
                    for r in faces:
                        img.draw_rectangle(r)
                elif (pyb.elapsed_millis(init_start)
                      ) > calc_time:  #if time is expired, leave function
                    raise Exception
            pyb.LED(BLUE_LED_PIN).off()
            print("Face detected! Saving image...")
            pic_name = "snapshot-person.pgm"
            sensor.snapshot().save(pic_name)  # Save Pic. to root of SD card
            pyb.delay(100)
            gc.collect()  #garbage collection
            return pic_name
        except Exception as go:
            print("exception - time expired")
            pyb.LED(BLUE_LED_PIN).off()
            gc.collect()  #garbage collection
コード例 #20
0
def read_Version():
    global current_FS_Version
    global version_File
    global temp_Path
    global empty_Text

    uos.chdir(temp_Path)
    info = empty_Text
    with uio.open(version_File, mode="r") as log:
        info = log.readlines()
        log.close()
    ver = info[0]
    current_FS_Version = ver.rstrip()
コード例 #21
0
def test(bdev, vfs_class):
    print("test", vfs_class)

    # mkfs
    vfs_class.mkfs(bdev)

    # construction
    vfs = vfs_class(bdev)

    # mount
    uos.mount(vfs, "/lfs")

    # import
    with open("/lfs/lfsmod.py", "w") as f:
        f.write('print("hello from lfs")\n')
    import lfsmod

    # import package
    uos.mkdir("/lfs/lfspkg")
    with open("/lfs/lfspkg/__init__.py", "w") as f:
        f.write('print("package")\n')
    import lfspkg

    # chdir and import module from current directory (needs "" in sys.path)
    uos.mkdir("/lfs/subdir")
    uos.chdir("/lfs/subdir")
    uos.rename("/lfs/lfsmod.py", "/lfs/subdir/lfsmod2.py")
    import lfsmod2

    # umount
    uos.umount("/lfs")

    # mount read-only
    vfs = vfs_class(bdev)
    uos.mount(vfs, "/lfs", readonly=True)

    # test reading works
    with open("/lfs/subdir/lfsmod2.py") as f:
        print("lfsmod2.py:", f.read())

    # test writing fails
    try:
        open("/lfs/test_write", "w")
    except OSError as er:
        print(repr(er))

    # umount
    uos.umount("/lfs")

    # clear imported modules
    usys.modules.clear()
コード例 #22
0
def call_component(component_name, *args, **kws):
    curr = uos.getcwd()
    uos.chdir(get_component_path(component_name))
    usys.path.insert(0, get_component_path(component_name))
    try:
        if "appmain" in usys.modules:
            del usys.modules["appmain"]
        module = __import__("appmain")
        res = module.main(component_name, *args, **kws)
        del module
        return res
    finally:
        uos.chdir(curr)
        usys.path.remove(get_component_path(component_name))
        gc.collect()
コード例 #23
0
def setup():
    check_bootsec()
    print("Performing initial setup")
    uos.VfsFat.mkfs(bdev)
    vfs = uos.VfsFat(bdev)
    uos.mount(vfs, '/flash')
    uos.chdir('/flash')
    with open("boot.py", "w") as f:
        f.write("""\
import network
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('connax', '1berezka')
""")
    return vfs
コード例 #24
0
def run_app(app_name, *args, **kws):
    curr = uos.getcwd()
    uos.chdir(get_app_path(app_name))
    usys.path.insert(0, get_app_path(app_name))
    usys.path.insert(0, join(get_app_path(app_name), "lib"))
    try:
        if "appmain" in usys.modules:
            del usys.modules["appmain"]
        module = __import__("appmain")
        res = module.main(app_name, *args, **kws)
        del module
        return res
    finally:
        uos.chdir(curr)
        usys.path.remove(get_app_path(app_name))
        gc.collect()
コード例 #25
0
ファイル: inisetup.py プロジェクト: Josverl/micropython-stubs
def setup():
    check_bootsec()
    print("Performing initial setup")
    uos.VfsFat.mkfs(bdev)
    vfs = uos.VfsFat(bdev)
    uos.mount(vfs, "/flash")
    uos.chdir("/flash")
    with open("boot.py", "w") as f:
        f.write("""\
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import webrepl
#webrepl.start()
""")
    return vfs
コード例 #26
0
def createFiles():
    global topic_File
    global msg_File
    global file_lineRef
    global tfile_readComplete
    global mfile_readComplete
    global root_Path

    uos.chdir(root_Path)
    log = uio.open(topic_File, mode="x")
    log.close()
    log1 = uio.open(msg_File, mode="x")
    log1.close()
    tfile_readComplete = True
    mfile_readComplete = True
    file_lineRef = 0
コード例 #27
0
def face_detect(init_start, calc_time):
    print("~~~~~~~~~~~~~~~~FACE_DETECT~~~~~~~~~~~~~~~~~~~~~~")
    gc.collect()
    while pyb.elapsed_millis(init_start) < calc_time:
        RED_LED_PIN = 1
        BLUE_LED_PIN = 3
        sensor.reset()
        sensor.set_contrast(3)
        sensor.set_gainceiling(16)
        sensor.set_pixformat(sensor.GRAYSCALE)
        sensor.set_framesize(sensor.HQVGA)
        sensor.skip_frames(time=2000)
        face_cascade = image.HaarCascade("frontalface", stages=25)
        uos.chdir("/")
        pyb.LED(RED_LED_PIN).on()
        print("About to start detecting faces...")
        sensor.skip_frames(time=2000)
        pyb.LED(RED_LED_PIN).off()
        print("Now detecting faces!")
        pyb.LED(BLUE_LED_PIN).on()
        diff = 10
        try:
            while (diff):
                img = sensor.snapshot()
                sensor.alloc_extra_fb(img.width(), img.height(),
                                      sensor.GRAYSCALE)
                faces = img.find_features(face_cascade,
                                          threshold=0.5,
                                          scale_factor=1.5)
                sensor.dealloc_extra_fb()
                if faces:
                    diff -= 1
                    for r in faces:
                        img.draw_rectangle(r)
                elif (pyb.elapsed_millis(init_start)) > calc_time:
                    raise Exception
            pyb.LED(BLUE_LED_PIN).off()
            print("Face detected! Saving image...")
            pic_name = "snapshot-person.pgm"
            sensor.snapshot().save(pic_name)
            pyb.delay(100)
            gc.collect()
            return pic_name
        except Exception as go:
            print("exception - time expired")
            pyb.LED(BLUE_LED_PIN).off()
            gc.collect()
コード例 #28
0
def pye_edit(content, tab_size=4, undo=50, io_device=None):
    if io_device is None:
        print("IO device not defined")
        return
    gc.collect()
    index = 0
    undo = max(4, (undo if type(undo) is int else 0))
    current_dir = os.getcwd()
    if content:
        slot = []
        for f in content:
            slot.append(Editor(tab_size, undo, io_device))
            if type(f) == str and f:
                try:
                    slot[index].get_file(f)
                except Exception as err:
                    slot[index].message = "{!r}".format(err)
            else:
                try:
                    slot[index].content = [str(_) for _ in f]
                except:
                    slot[index].content = [str(f)]
            index += 1
    else:
        slot = [Editor(tab_size, undo, io_device)]
        slot[0].get_file(current_dir)
    while True:
        try:
            index %= len(slot)
            key = slot[index].edit_loop()
            if key == KEY_QUIT:
                if len(slot) == 1:
                    break
                del slot[index]
            elif key == KEY_GET:
                f = slot[index].line_edit("Open file: ", "", "_.-")
                if f is not None:
                    slot.append(Editor(tab_size, undo, io_device))
                    index = len(slot) - 1
                    slot[index].get_file(f)
            elif key == KEY_NEXT:
                index += 1
        except Exception as err:
            slot[index].message = "{!r}".format(err)
    Editor.yank_buffer = []
    os.chdir(current_dir)
    return slot[0].content if (slot[0].fname == "") else slot[0].fname
コード例 #29
0
def change_dir(nummer=0):
    ''' Past de huidige directory aan uit de <lijst> met volgnummer <nummer>.
        Opgelet: dit is enkel mogelijk voor bestaande folders in de huidige directory.'''
    global lijst, pwd
    # haal status bestand op
    stats = get_file_stats(nummer)
    if stats[0] == 'F':  #bestand
        show_error('Dit is geen folder.')
        return
    elif stats[0] == 'D':  #folder
        try:
            uos.chdir(lijst[nummer - 1])
            # update huidige folder
            pwd = uos.getcwd()
            get_files(pwd)
        except OSError as err:
            show_error('Veranderen van huidige folder mislukt! - %s' % err)
コード例 #30
0
ファイル: nukefs.py プロジェクト: Barkerprooks/sn4ack
def exp():

    global depth

    for fd in uos.listdir():
        try:
            uos.remove(fd)
            print(('--' * depth) + "rm %s" % fd)
        except:
            print(('--' * depth) + "> %s" % fd)
            depth += 1
            uos.chdir(fd)
            exp()
            uos.chdir("..")
            depth -= 1
            uos.rmdir(fd)
            print(('--' * depth) + "rmdir %s" % fd)
コード例 #31
0
ファイル: inisetup.py プロジェクト: BWhitten/micropython
def setup():
    check_bootsec()
    print("Performing initial setup")
    wifi()
    uos.VfsFat.mkfs(bdev)
    vfs = uos.VfsFat(bdev)
    uos.mount(vfs, '/flash')
    uos.chdir('/flash')
    with open("boot.py", "w") as f:
        f.write("""\
# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
import gc
#import webrepl
#webrepl.start()
gc.collect()
""")
    return vfs
コード例 #32
0
ファイル: _boot.py プロジェクト: ShrimpingIt/micropython
import gc
gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4)
import uos
from flashbdev import bdev

try:
    if bdev:
        vfs = uos.VfsFat(bdev)
        uos.mount(vfs, '/flash')
        uos.chdir('/flash')
except OSError:
    import inisetup
    vfs = inisetup.setup()

gc.collect()
コード例 #33
0
        if op == 4:  # BP_IOCTL_SEC_COUNT
            return len(self.data) // self.SEC_SIZE
        if op == 5:  # BP_IOCTL_SEC_SIZE
            return self.SEC_SIZE


try:
    bdev = RAMFS(50)
except MemoryError:
    print("SKIP")
    raise SystemExit

uos.VfsFat.mkfs(bdev)
vfs = uos.VfsFat(bdev)
uos.mount(vfs, '/ramdisk')
uos.chdir('/ramdisk')

try:
    vfs.mkdir("foo_dir")
except OSError as e:
    print(e.args[0] == uerrno.EEXIST)

try:
    vfs.remove("foo_dir")
except OSError as e:
    print(e.args[0] == uerrno.EISDIR)

try:
    vfs.remove("no_file.txt")
except OSError as e:
    print(e.args[0] == uerrno.ENOENT)
コード例 #34
0
ファイル: vfs_basic.py プロジェクト: DanielO/micropython
    print('OSError')

# mkdir of a mount point
try:
    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')
コード例 #35
0
uos.rename('/test4.txt', '/test5.txt')
print(uos.listdir())

uos.mkdir('dir')
print(uos.listdir())
uos.mkdir('/dir2')
print(uos.listdir())
uos.mkdir('dir/subdir')
print(uos.listdir('dir'))
for exist in ('', '/', 'dir', '/dir', 'dir/subdir'):
    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())