def __init__(self, tab_size, undo_limit, io_device):
     self.top_line = self.cur_line = self.row = self.vcol = self.col = self.margin = 0
     self.tab_size = tab_size
     self.changed = ''
     self.hash = 0
     self.message = self.fname = ""
     self.content = [""]
     self.undo = []
     self.undo_limit = undo_limit
     self.redo = []
     self.clear_mark()
     self.write_tabs = "n"
     self.work_dir = os.getcwd()
     self.io_device = io_device
     self.wr = io_device.wr
     self.is_dir = False
     self.key_max = 0
     for _ in Editor.KEYMAP.keys():
         self.key_max = max(self.key_max, len(_))
Exemple #2
0
    async def send_list_data(self, writer):

        path = uos.getcwd()
        items = uos.listdir(path)

        if path == '/':
            path = ''
        for i in items:
            file_stat = uos.stat(path + "/" + i)

            file_permissions = "drwxr-xr-x" if (file_stat[0] & 0o170000 == 0o040000) else "-rw-r--r--"
            file_size = file_stat[6]
            description = "{}    1 owner group {:>10} Jan 1 2000 {}\r\n".format(
                file_permissions, file_size, i)

            try:
                await writer.awrite(description)
            except Exception as err:
                log.error(err)
                pass
Exemple #3
0
def pwd():
    uos.getcwd()
Exemple #4
0
#rename_files.py
###############################################################
# Code for OpenMV M7 camera
# Goal is to rename the "pulse_led.py" file to "main.py" and reset the camera - Work in progress
# Author: Adam A. Koch (aakoch)
# Date: 2018-04-03
# Copyright (c) 2018 Adam A. Koch
# This work is licensed under the MIT license.
###############################################################

import uos, machine, pyb

uos.sync()

print("current directory=%s" % uos.getcwd())
print("directory contents=%s" % uos.listdir())

undo = False

if (undo):
    uos.rename("main.py", "pulse_led.py")
    uos.rename("main_backup.py", "main.py")
else:
    uos.rename("main.py", "main_backup.py")
    uos.rename("pulse_led.py", "main.py")
uos.sync()

print("current directory=%s" % uos.getcwd())
print("directory contents=%s" % uos.listdir())

if (not undo):
def webserver():
    configlist = ['WiFiName', 'WiFiPasswd']
    configdic = {}
    html = """<!DOCTYPE html>
        <html>
            <head> <title>ESP8266 Web Config</title> </head>
            <body> <h1>ESP8266 Web Config</h1>
                %s
                <table>
                    <FORM action="" method="GET">
                        %s%s
                    </form>
                </table>

            </body>
        </html>
        """
    row1 = [
        '<tr><td>%s</td><td><input type=\"text\" name=\"%s\" value=""></td></tr>'
        % (key, key) for key in configlist
    ]
    row2 = [
        '<tr><td></td><td><input type=\"submit\" value=\"SAVE\"></td></tr>'
    ]
    row3 = ['<tr><span style="color:red">Save Config to ESP8266</span></tr>']
    row4 = ['<tr><span style="color:red">Config Error</span></tr>']

    addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

    s = socket.socket()
    s.bind(addr)
    s.listen(1)

    print('listening on', addr)
    flag = 0
    while True:
        cl, addr = s.accept()
        print('client connected from', addr)
        cl_file = cl.makefile('rwb', 0)
        while True:

            line = cl_file.readline()
            print(line, type(line))
            if not line or line == b'\r\n':
                break
            else:
                configline = line.decode().split(' ')[1]
                if (configline[:2] == '/?'):
                    configdic = {
                        k: v
                        for k, v in (l.split('=', 1)
                                     for l in configline[2:].split('&'))
                    }
                    if ('' not in configdic.values()):
                        flag = 1
                    else:
                        flag = -1
        if (flag == 1):
            response = html % ('\n'.join(row3), '\n'.join(row1),
                               '\n'.join(row2))
            currdir = uos.getcwd()
            fconfig = open(currdir + 'config.ini', 'w')
            fconfig.write(ujson.dumps(configdic))
            fconfig.flush()
            fconfig.close()
        elif (flag == -1):
            response = html % ('\n'.join(row4), '\n'.join(row1),
                               '\n'.join(row2))
        else:
            response = html % ('\n', '\n'.join(row1), '\n'.join(row2))
        cl.send(response)
        cl.close()
        if (flag == 1):
            time.sleep(5)
            machine.reset()
except MemoryError:
    print("SKIP")
    raise SystemExit

# first we umount any existing mount points the target may have
try:
    uos.umount('/')
except OSError:
    pass
for path in uos.listdir('/'):
    uos.umount('/' + path)

uos.VfsFat.mkfs(bdev)
uos.mount(bdev, '/')

print(uos.getcwd())

f = open('test.txt', 'w')
f.write('hello')
f.close()

print(uos.listdir())
print(uos.listdir('/'))
print(uos.stat('')[:-3])
print(uos.stat('/')[:-3])
print(uos.stat('test.txt')[:-3])
print(uos.stat('/test.txt')[:-3])

f = open('/test.txt')
print(f.read())
f.close()
Exemple #7
0
 def __enter__(self):
     from uos import getcwd
     self.current_directory = getcwd()
# Untitled - By: Brady - Tue Sep 3 2019
import uos
import pyb
import sensor, time, image


print("here1")
dir = uos.urandom(3)
print(dir)
dir2 = uos.getcwd()
print(dir2)
print("here2")


#uos.mkdir("/Path")
print("here3")

print("here33")
dir2 = uos.getcwd()
print(dir2)
print("here4")
uos.chdir("/")
snap_img = image.Image("snapshot-384550201.pgm").mask_ellipse()
d0 = snap_img.find_lbp((0, 0, snap_img.width(), snap_img.height()))
lbp_list = []
name_list = []

uos.chdir("/Faces")
for filename in uos.listdir("/Faces"):
  if filename.endswith(".pgm") :
    img = None
        # if its a directory, then it should provide some children.
        children = os.listdir(dir_or_file)
    except OSError:
        # probably a file, remove if not required.
        rm_if_not_required(dir_or_file)
    else:
        # probably a directory, remove if not required.
        rmdir_if_not_required(dir_or_file)

        # queue the children to be inspected in next iteration (with correct path).
        for child in children:
            remove_unwanted(dir_or_file + "/" + child)  # pass the full path.


# gather required files / dirs.
required_files = {{required_files}}
required_files.add("boot.py")  # avoid f*****g up the boot.py.
required_dirs = {{required_dirs}}


# Remove unwanted files / dirs.
remove_unwanted(os.getcwd())

# create necessary dirs.
for dir in required_dirs:
    mkdir_p(dir)

# inform everyone which files have changed.
for file_and_hash in {{files_to_check_for_change_with_hash}}:
    print(did_it_change(*file_and_hash), end=" ")
Exemple #10
0
def abspath(s):
    if s[0] != "/":
        return uos.getcwd() + "/" + s
    return s
Exemple #11
0
    def get_path(self, argument):

        cwd = uos.getcwd()
        path = self.get_absolute_path(cwd, argument)
        log.debug("Get path is %s" % path)
        return path
def __filename():
    return '{}{}datapoints.txt'.format(uos.getcwd(), uos.sep)
Exemple #13
0
def pwd():
    return uos.getcwd()
Exemple #14
0
button_a = GPIO(GPIO.GPIO4, GPIO.PULL_UP)

# Init LCD
print("init LCD")
lcd.init(type=3, freq=40000000)
lcd.rotation(2)
sensor.reset(dual_buff=True)

# Init camera
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(100)
sensor.run(1)

# Find /SD
if uos.getcwd() != "/sd":
    sd_flag = False
else:
    sd_flag = True

clock = utime.clock()
img_cnt = 0

while True:
    # Transfer a frame to PC
    led_r.value(0)
    fbuffer = sensor.get_fb()
    img = sensor.snapshot()
    fbuffer = img
    led_r.value(1)
Exemple #15
0
def getcwd():
    if (sys.platform == 'uefi') and (sys.implementation.name == 'micropython'):
        return uos.getcwd()

    buf = bytearray(512)
    return getcwd_(buf, 512)
Exemple #16
0
def get_cwd(sock=None):
    cwd = uos.getcwd()
    print(cwd)
    send_output(sock, cwd)
except (ImportError, AttributeError):
    print("SKIP")
    raise SystemExit

# We need a directory for testing that doesn't already exist.
# Skip the test if it does exist.
temp_dir = "micropy_test_dir"
try:
    uos.stat(temp_dir)
    print("SKIP")
    raise SystemExit
except OSError:
    pass

# getcwd and chdir
curdir = uos.getcwd()
uos.chdir("/")
print(uos.getcwd())
uos.chdir(curdir)
print(uos.getcwd() == curdir)

# stat
print(type(uos.stat("/")))

# listdir and ilistdir
print(type(uos.listdir("/")))

# mkdir
uos.mkdir(temp_dir)

# file create
Exemple #18
0
def pwd():
    from uos import getcwd
    print(getcwd())
Exemple #19
0
    print("booting from SD")
    pycom.rgbled(C_WHITE_DIM)

    #add code and lib dir on sd to import path
    sys.path.append(CODE_PATH)
    sys.path.append(LIB_PATH)

    #change working dir to code directory
    try:
        uos.chdir(CODE_PATH)
    except Exception:
        print("could not change to code folder:")
        print(CODE_PATH)
        endless_blink(C_PURPLE, C_RED)

    print("sys.path:")
    print(sys.path)
    print("uos.getcwd():")
    print(uos.getcwd())

    #execute code from SD
    try:
        execfile('main.py')
    except Exception:
        print("could not execute main.py")
        endless_blink(C_BLUE, C_RED)

#sd was not mounted
print("no SD found")
endless_blink(C_YELLOW, C_RED)
Exemple #20
0
def main():
    print(
        ' __   __  ___   _______  ______    _______  _______  __   __  _______  _______ '
    )
    print(
        '|  |_|  ||   | |       ||    _ |  |       ||       ||  | |  ||       ||       |'
    )
    print(
        '|       ||   | |       ||   | ||  |   _   ||    _  ||  |_|  ||   _   ||  _____|'
    )
    print(
        '|       ||   | |       ||   |_||_ |  | |  ||   |_| ||       ||  | |  || |_____ '
    )
    print(
        '|       ||   | |      _||    __  ||  |_|  ||    ___||_     _||  |_|  ||_____  |'
    )
    print(
        '| ||_|| ||   | |     |_ |   |  | ||       ||   |      |   |  |       | _____| |'
    )
    print(
        '|_|   |_||___| |_______||___|  |_||_______||___|      |___|  |_______||_______|'
    )
    print('small OS for micropython ver ' + version + ' by theCodeman')
    print('https://github.com/TheCodeman/myos')
    print('MicroPython Version : {} Platform : {}'.format(
        sys.version, sys.platform))

    timer.init(period=1000, mode=machine.Timer.PERIODIC, callback=intCallback)

    while True:
        str = input(uos.getcwd() + '>')
        cmd = str.split()
        #        print(cmd)
        if len(str) != 0:
            if cmd[0] == 'cd':
                try:
                    uos.chdir(cmd[1])
                except:
                    print('bad dir')

            elif cmd[0] == 'ls':
                print('Current Directory ', uos.getcwd())
                total = 0
                #F       1366    lora.py
                print('Type    Size    Filename')
                print('----------------------------------')
                if len(cmd) == 2:
                    path = cmd[1]
                else:
                    path = uos.getcwd()
                try:
                    for l in uos.ilistdir(path):
                        if l[1] & 0x4000:
                            print('D{0:>31}'.format(l[0]))
                        else:
                            # F       3360    myos.py
                            total += int(uos.stat(l[0])[6])
                            print('F       {0:<8}{1:>16}'.format(
                                uos.stat(l[0])[6], l[0]))
                    print('----------------------------------')
                    print('File Size Total: {0}'.format(total))
                except Exception as e:
                    print(e)

            elif cmd[0] == 'cp':
                if len(cmd) == 3:
                    try:
                        with open(cmd[1], 'rb') as source:
                            print('Source {0}'.format(cmd[1]))
                            data = source.read()
                            source.close()
                    except Exception as e:
                        print(e)
                    try:
                        with open(cmd[2], 'wb') as dest:
                            print('Dest {0}'.format(cmd[2]))
                            dest.write(data)
                            dest.close()
                    except Exception as e:
                        print(e)
                else:
                    print(
                        'cp requires source filename and destination filename '
                    )

            elif cmd[0] == 'run':
                if len(cmd) == 2:
                    __import__(cmd[1])
                    del sys.modules[cmd[1]]
                else:
                    print('Need File Name')

            elif cmd[0] == 'lr':
                if networkUp:
                    if len(cmd) == 1:
                        res = ssh.list(settings.remoteIP + settings.remotePath,
                                       settings.uname, settings.upass)
                    else:
                        res = ssh.list(
                            settings.remoteIP + settings.remotePath + cmd[1],
                            settings.uname, settings.upass)
                    print(res[0])
                    if res[0] == 0:
                        print(res[1])
                        print(res[2])
                else:
                    print('No Network Connection')
            elif cmd[0] == 'put':
                if networkUp:
                    res = ssh.put(settings.remoteIP + settings.remotePath +
                                  cmd[1],
                                  settings.uname,
                                  settings.upass,
                                  file=cmd[1])
                    if res[0] == 0:
                        print('File %s copied to %s' %
                              (cmd[1], settings.remotePath))
                else:
                    print('No Network Connection')
            elif cmd[0] == 'get':
                if networkUp:
                    res = ssh.get(settings.remoteIP + settings.remotePath +
                                  cmd[1],
                                  settings.uname,
                                  settings.upass,
                                  file='$$$.tmp')
                    if res[0] == 0:
                        try:
                            uos.remove(cmd[1])
                        except:
                            pass
                        uos.rename('$$$.tmp', cmd[1])
                        print('File %s copied from %s' %
                              (cmd[1], settings.remotePath))
                    else:
                        uos.remove('$$$.tmp')
                        print('File Not Found')
                else:
                    print('No Network Connection')
            elif cmd[0] == 'edit':
                pye(cmd[1])

            elif cmd[0] == 'rm':
                try:
                    uos.remove(cmd[1])
                except:
                    print('no file')

            elif cmd[0] == 'md':
                try:
                    uos.mkdir(cmd[1])
                except:
                    print("Need Directory Name")

            elif cmd[0] == 'rmdir':
                try:
                    uos.rmdir(cmd[1])
                except:
                    print("Need Directory Name")

            elif cmd[0] == 'reset':
                machine.reset()

            elif cmd[0] == 'cat':
                line = 0
                try:
                    f = open(cmd[1], 'r')
                    while True:
                        str = f.readline()
                        if str == "":
                            break
                        print(str, end="")
                        line += 1
                        if line > 25:
                            print(
                                '----- press space to continue or q to quit -----',
                                end="")
                            ret = getch()
                            print(
                                '\r                                                \r',
                                end="")
                            if ret == 'q':
                                break
                            else:
                                line = 0
                    f.close()
                except:
                    print('no file')

            elif cmd[0] == 'time':
                print('Time set to: {}'.format(
                    utime.strftime('%c', utime.localtime())))

            elif cmd[0] == 'df':
                if len(cmd) == 1:
                    fs_stat = uos.statvfs(uos.getcwd())
                else:
                    fs_stat = uos.statvfs(cmd[1])
                fs_size = fs_stat[0] * fs_stat[2]
                fs_free = fs_stat[0] * fs_stat[3]
                print('File System Size {:,} - Free Space {:,}'.format(
                    fs_size, fs_free))

            elif cmd[0] == 'wget':
                if networkUp:
                    try:
                        response = urequests.get(cmd[1])

                        if response.status_code == 200:
                            print(type(response))
                            print(response.text)
                            print(type(response.text))
                            fileName = cmd[1].split('/')
                            print(fileName)
                            print(fileName[-1])
                            f = open(fileName[-1], 'w')
                            f.write(response.text)
                            f.close()
                        else:
                            print('Error: {0} {1}'.format(
                                response.status_code,
                                response.reason.decode('utf-8')))
                    except Exception as e:
                        print(e)
                else:
                    print('No Network Connection')
            elif cmd[0] == 'wifi':
                try:
                    if cmd[1] == 'active':
                        nic.active(True)
                    if cmd[1] == 'deactive':
                        nic.active(False)
                    if cmd[1] == 'config':
                        status = nic.ifconfig()
                        print(
                            'IP: {0}\n\rSubnet: {1}\r\nGateway: {2}\r\nDNS: {3}'
                            .format(status[0], status[1], status[2],
                                    status[3]))
                    if cmd[1] == 'isconnected':
                        print(nic.isconnected())
                    if cmd[1] == 'connect':
                        try:
                            nic.connect(cmd[2], cmd[3])
                        except Exception as e:
                            print(e)
                    if cmd[1] == 'scan':
                        stations = nic.scan()
                        for s in stations:
                            if s[4] == 0:
                                authmode = 'Open'
                            if s[4] == 1:
                                authmode = 'Wep'
                            if s[4] == 2:
                                authmode = 'WPA-PSK'
                            if s[4] == 3:
                                authmode = 'WPA2-PSK'
                            if s[4] == 4:
                                authmode = 'WPA/WPA2-PSK'
                            print(
                                'SSID: {0:<32} Channel: {1} RSSSI: {2} Auth Type: {3}'
                                .format(s[0].decode('utf-8'), s[2], s[3],
                                        authmode))
                except Exception as e:
                    print(e)
                    print(' no action')

            elif cmd[0] == 'umountsd':
                try:
                    uos.umountsd()
                except Exception as e:
                    print(e)

            elif cmd[0] == 'mountsd':
                try:
                    uos.mountsd()
                except Exception as e:
                    print(e)

            elif cmd[0] == 'help':
                print('Command List')
                print('----------------------------------')
                print('ls      - list files current directory')
                print(
                    'lr      - list files on remote server optional directory')
                print('cat     - display file')
                print('rm      - remove file')
                print('df      - display drive space')
                print('time    - display time and date')
                print('get     - scp from server')
                print('put     - scp to server')
                print('md      - make directory')
                print('rmdir   - remove directory')
                print('run     - run python script')
                print('edit    - edit file using pye')
                print('modules - list installed modules')
                print('reset   - reset board')
                print('wget    - get file over http and save to file')
                print('----------------------------------')

            elif cmd[0] == 'exit':
                timer.deinit()
                return 1

            elif cmd[0] == 'update':
                if networkUp:
                    res = ssh.get(settings.remoteIP + settings.remotePath +
                                  'micropyos.py',
                                  settings.uname,
                                  settings.upass,
                                  file='$$$.tmp')
                    if res[0] == 0:
                        try:
                            uos.remove('micropyos.py')
                        except:
                            pass
                        uos.rename('$$$.tmp', 'micropyos.py')
                        print('File %s copied from %s' %
                              ('micropyos.py', settings.remotePath))
                    else:
                        uos.remove('$$$.tmp')
                        print('File Not Found')
                    timer.deinit()
                    return 2
                else:
                    print('No Network Connection')

            elif cmd[0] == 'modules':
                for m in sys.modules:
                    print(m)

            elif cmd[0] == 'settings':
                pye('settings.py')

            else:
                print('unknown command')