MicroPython on Nucleo-F401RE, 4. my.py

之前說要分享的小程式my.py
也放在GitHub: my.py

import os

def cat(f):
    with open(f) as file:
        str = file.read()
        print(str)

def rm(f):
    os.remove(f)
    
def cd(directory):
    os.chdir(directory)

def run(f):
    with open(f) as file:
        str = file.read()
        exec(str, globals())

def ls(prex=None):
    s = os.statvfs(os.getcwd())
    print("current directory: {}, available size: {}KB".format(os.getcwd(), s[0] * s[4] / 1024))
    print()
    for (name, type, inode, size) in sorted(os.ilistdir()):
        if prex == None or name.startswith(prex):
            if type == 0x8000:
                print(" - {:8d} \t {}".format(size, name))
            else:
                print(" D {:8d} \t {}".format(size, name))

def ip():
    import network
    wlan = network.WLAN(network.STA_IF)

    print('ip: {}'.format(wlan.ifconfig()[0]))
    
def fileExists(path):
    file_size = 0
    try:
        s = os.stat(path)
        if s[0] != 0x4000:
            file_size = s[6]
        return file_size
    except OSError as e:
        if (e.args[0] == 2):
            print('No such file!')
            return None
        
def cp(src, dest):
    if fileExists(src):
        with open(src, 'rb') as f_src, open(dest, 'wb') as f_dest:
            while True:
                chunk = f_src.read(64)
                if len(chunk) == 0:
                    break
                f_dest.write(chunk)

使用方法:
在REPL提示符號下, 先import my, 然後就可以下:
my.ls()  列出目前目錄下有什麼檔案
my.rm(f)  刪除檔案
my.cd(dir) 切換目錄
my.cat(f) 列出檔案內容
my.cp(src, dest) 複製檔案

當然前提是要先將my.py複製到開發板上的檔案系統去, 方法請參照之前貼文2
注意: 其中ip()這個函數是給ESP82666板子用的, F401RE並沒有WiFi功能哦!

留言

這個網誌中的熱門文章

D-BUS學習筆記

關於藍牙裝置找尋(inquiry, scan)兩三事

Cisco Switch學習筆記: EtherChannel