def ls(directory, long_format, recursive): """List contents of a directory on the board. Can pass an optional argument which is the path to the directory. The default is to list the contents of the root, /, path. For example to list the contents of the root run: ampy --port /board/serial/port ls Or to list the contents of the /foo/bar directory on the board run: ampy --port /board/serial/port ls /foo/bar Add the -l or --long_format flag to print the size of files (however note MicroPython does not calculate the size of folders and will show 0 bytes): ampy --port /board/serial/port ls -l /foo/bar """ # List each file/directory on a separate line. board_files = files.Files(_board) for f in board_files.ls(directory, long_format=long_format, recursive=recursive): print(f)
def test_ls_multiple_files(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock( return_value=b"['boot.py', 'main.py', 'foo.txt']") board_files = files.Files(pyboard) result = board_files.ls() self.assertListEqual(result, ['boot.py', 'main.py', 'foo.txt'])
def run(local_file, no_output): """Run a script and print its output. Run will send the specified file to the board and execute it immediately. Any output from the board will be printed to the console (note that this is not a 'shell' and you can't send input to the program). Note that if your code has a main or infinite loop you should add the --no-output option. This will run the script and immediately exit without waiting for the script to finish and print output. For example to run a test.py script and print any output until it finishes: ampy --port /board/serial/port run test.py Or to run test.py and not wait for it to finish: ampy --port /board/serial/port run --no-output test.py """ # Run the provided file and print its output. board_files = files.Files(_board) try: output = board_files.run(local_file, not no_output, not no_output) if output is not None: print(output.decode("utf-8"), end="") except IOError: click.echo( "Failed to find or read input file: {0}".format(local_file), err=True )
def mkdir(directory, exists_okay, make_parents): """ Create a directory on the board. Mkdir will create the specified directory on the board. One argument is required, the full path of the directory to create. By default you cannot recursively create a hierarchy of directories with one mkdir command. You may create each parent directory with separate mkdir command calls, or use the --make-parents option. For example to make a directory under the root called 'code': ampy --port /board/serial/port mkdir /code To make a directory under the root called 'code/for/ampy', along with all missing parents: ampy --port /board/serial/port mkdir --make-parents /code/for/ampy """ # Run the mkdir command. board_files = files.Files(_board) if make_parents: if directory[0] != '/': directory = "/" + directory dirpath = "" for dir in directory.split("/")[1:-1]: dirpath += "/" + dir board_files.mkdir(dirpath, exists_okay=True) board_files.mkdir(directory, exists_okay=exists_okay)
def put(local_file, remote_file): """Put a file on the board. Put will upload a local file to the board. If the file already exists on the board it will be overwritten with no warning! You must pass at least one argument which is the path to the local file to upload. You can pass a second optional argument which is the path and name of the file to put to on the connected board. For example to upload a main.py from the current directory to the board's root run: ampy --port /board/serial/port put main.py Or to upload a board_boot.py from a ./foo subdirectory and save it as boot.py in the board's root run: ampy --port /board/serial/port put ./foo/board_boot.py boot.py """ # Use the local filename if no remote filename is provided. if remote_file is None: remote_file = os.path.basename(local_file.name) # Put the file on the board. board_files = files.Files(_board) board_files.put(remote_file, local_file.read())
def rm(all, remote_file): """Remove a file from the board. Remove the specified file from the board's filesystem. Must specify one argument which is the path to the file to delete. Note that this can't delete directories which have files inside them, but can delete empty directories. For example to delete main.py from the root of a board run: ampy --port /board/serial/port rm main.py To delete all files and folders from the board: ampy --port /board/serial/port rm --all """ # Delete the provided file/directory on the board. board_files = files.Files(_board) filelist = board_files.ls(long_format=False) if all or remote_file == 'all': # remove all files for file in filelist: board_files.rm(file) else: # remove specified board_files.rm(remote_file)
def test_sha1sum(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock( return_value=b"da39a3ee5e6b4b0d3255bfef95601890afd80709") board_files = files.Files(pyboard) result = board_files.sha1sum('foo.txt') self.assertEqual(result, "da39a3ee5e6b4b0d3255bfef95601890afd80709")
def get(remote_file, local_file): """ Retrieve a file from the board. Get will download a file from the board and print its contents or save it locally. You must pass at least one argument which is the path to the file to download from the board. If you don't specify a second argument then the file contents will be printed to standard output. However if you pass a file name as the second argument then the contents of the downloaded file will be saved to that file (overwriting anything inside it!). For example to retrieve the boot.py and print it out run: ampy --port /board/serial/port get boot.py Or to get main.py and save it as main.py locally run: ampy --port /board/serial/port get main.py main.py """ # Get the file contents. board_files = files.Files(_board) contents = board_files.get(remote_file) # Print the file out if no local file was provided, otherwise save it. if local_file is None: print(contents.decode('utf-8')) else: local_file.write(contents)
def get(all, remote_file, local_file): """ Retrieve a file from the board. Get will download a file from the board and print its contents or save it locally. You must pass at least one argument which is the path to the file to download from the board. If you don't specify a second argument then the file contents will be printed to standard output. However if you pass a file name as the second argument then the contents of the downloaded file will be saved to that file (overwriting anything inside it!). For example to retrieve the boot.py and print it out run: ampy --port /board/serial/port get boot.py Or to get main.py and save it as main.py locally run: ampy --port /board/serial/port get main.py main.py Also to get all files to the current folder: ampy --port /board/serial/port get --all Or to the mentioned folder: ampy --port /board/serial/port get --all ./destination/ """ # Get the file contents. board_files = files.Files(_board) filelist = board_files.ls(long_format=False) # When --all flag is set - the next argument is remote_file # but will be used as a path to save files if all: if remote_file.endswith('/'): destination_folder = remote_file else: destination_folder = remote_file + '/' if not os.path.exists(destination_folder): print('''Specified path doesn\'t exist. Files will be downloaded to current location''') destination_folder = '' else: destination_folder = '' if all or remote_file == 'all': # download all files for file in filelist: contents = board_files.get(file) file = file.replace('/', destination_folder) with open(file, 'wb') as thefile: thefile.write(contents) else: # download specified contents = board_files.get(remote_file) # Print the file out if no local file was provided, otherwise save it. if local_file is None: print(contents.decode("utf-8")) else: local_file.write(contents)
def test_ls_bad_directory(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(side_effect=PyboardError( 'exception', b'', b'Traceback (most recent call last):\r\n File "<stdin>", line 3, in <module>\r\nOSError: [Errno 2] ENOENT\r\n' )) with self.raisesRegex(RuntimeError, 'No such directory: /foo'): board_files = files.Files(pyboard) result = board_files.ls('/foo')
def test_run_with_output(self): pyboard = mock.Mock() pyboard.execfile = mock.Mock(return_value=b"Hello world") board_files = files.Files(pyboard) with tempfile.NamedTemporaryFile() as program: program.write(b'print("Hello world")') program.flush() output = board_files.run(program.name) self.assertEqual(output, b"Hello world")
def test_rm_directory_not_empty(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(side_effect=PyboardError( 'exception', b'', b'Traceback (most recent call last):\r\n File "<stdin>", line 3, in <module>\r\nOSError: [Errno 13] EACCES\r\n' )) with self.raisesRegex(RuntimeError, 'Directory is not empty: foo'): board_files = files.Files(pyboard) result = board_files.rm('foo')
def test_rm_file_doesnt_exist(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(side_effect=PyboardError( 'exception', b'', b'Traceback (most recent call last):\r\n File "<stdin>", line 3, in <module>\r\nOSError: [Errno 2] ENOENT\r\n' )) with self.raisesRegex(RuntimeError, 'No such file/directory: foo.txt'): board_files = files.Files(pyboard) result = board_files.rm('foo.txt')
def test_mkdir_directory_already_exists(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(side_effect=PyboardError( 'exception', b'', b'Traceback (most recent call last):\r\n File "<stdin>", line 3, in <module>\r\nOSError: [Errno 17] EEXIST\r\n' )) with self.raisesRegex(RuntimeError, 'Directory already exists: /foo'): board_files = files.Files(pyboard) board_files.mkdir('/foo')
def test_rmdir_folder_doesnt_exist(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(side_effect=PyboardError( "exception", b"", b'Traceback (most recent call last):\r\n File "<stdin>", line 3, in <module>\r\nOSError: [Errno 2] ENOENT\r\n', )) with self.raisesRegex(RuntimeError, "No such directory: foo"): board_files = files.Files(pyboard) result = board_files.rmdir("foo")
def test_get_bad_file(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(side_effect=PyboardError( "exception", b"", b'Traceback (most recent call last):\r\n File "<stdin>", line 3, in <module>\r\nOSError: [Errno 2] ENOENT\r\n', )) with self.raisesRegex(RuntimeError, "No such file: foo.txt"): board_files = files.Files(pyboard) result = board_files.get("foo.txt")
def test_run_without_output(self): pyboard = mock.Mock() pyboard.exec_raw_no_follow = mock.Mock() board_files = files.Files(pyboard) with tempfile.NamedTemporaryFile() as program: program.write(b'print("Hello world")') program.flush() output = board_files.run(program.name, wait_output=False) self.assertEqual(output, None) pyboard.exec_raw_no_follow.assert_called_once_with( b'print("Hello world")')
def rm(remote_file): """Remove a file from the board. Remove the specified file from the board's filesystem. Must specify one argument which is the path to the file to delete. Note that this can't delete directories which have files inside them, but can delete empty directories. For example to delete main.py from the root of a board run: ampy --port /board/serial/port rm main.py """ # Delete the provided file/directory on the board. board_files = files.Files(_board) board_files.rm(remote_file)
def sha1sum(remote_file): """ Retrieve sha1sum of a file from the board. Sha1sum will calculate sha1 hash a file from the board and print its hex digest. You only need to pass the path to the file. For example to retrieve the sha1 hash of boot.py and print it out run: ampy --port /board/serial/port sha1sum boot.py """ # Get the hash of the file. board_files = files.Files(_board) sha1_hash = board_files.sha1sum(remote_file) # Print the hash output. print(sha1_hash)
def rmdir(remote_folder, missing_okay): """Forcefully remove a folder and all its children from the board. Remove the specified folder from the board's filesystem. Must specify one argument which is the path to the folder to delete. This will delete the directory and ALL of its children recursively, use with caution! For example to delete everything under /adafruit_library from the root of a board run: ampy --port /board/serial/port rmdir adafruit_library """ # Delete the provided file/directory on the board. board_files = files.Files(_board) board_files.rmdir(remote_folder, missing_okay=missing_okay)
def upgrade(ls, version, file, designation): """ 更新豌豆派固件. VERSION是用于指定更新固件的版本。 如果不填写该参数测默认更新最新的固件版本。 更新最新的豌豆派固件: wonderbits upgrade 如果想查询可更新的固件列表,可使用--ls或-l: wonderbits upgrade -l 需要更新本地文件可以使用--file或-f: wonderbits upgrade -f my_firmware.bin """ if ls: wb_tool.upload.version_ls(hardware_str) elif file: wb_tool.upload.update_bin(None, file) elif designation: MyUtil.wb_log(designation, version, '\r\n') if version: wb_tool.upload.update_bin(designation, version) else: wb_tool.upload.update_bin(designation) else: _board = pyboard.Pyboard(MySerial.choose_serial(), baudrate=115200, rawdelay=2) board_files = files.Files(_board) version_val = board_files.version() _board.close() if '-' in version_val: hardware_str = version_val.split('-')[0] else: hardware_str = 'wonderbits' MyUtil.wb_log(hardware_str, '\n') if version is None: wb_tool.upload.update_bin(hardware_str) else: wb_tool.upload.update_bin(hardware_str, version)
def ls(directory): """List contents of a directory on the board. Can pass an optional argument which is the path to the directory. The default is to list the contents of the root, /, path. For example to list the contents of the root run: ampy --port /board/serial/port ls Or to list the contents of the /foo/bar directory on the board run: ampy --port /board/serial/port ls /foo/bar """ # List each file/directory on a separate line. board_files = files.Files(_board) for f in board_files.ls(directory): print(f)
def mkdir(directory, exists_okay): """ Create a directory on the board. Mkdir will create the specified directory on the board. One argument is required, the full path of the directory to create. Note that you cannot recursively create a hierarchy of directories with one mkdir command, instead you must create each parent directory with separate mkdir command calls. For example to make a directory under the root called 'code': ampy --port /board/serial/port mkdir /code """ # Run the mkdir command. board_files = files.Files(_board) board_files.mkdir(directory, exists_okay=exists_okay)
def exec_file(): global _pyboard, _port, _cmd, _src result = None if _port is not None: _pyboard = pyboard.Pyboard(_port) _file_board = files.Files(_pyboard) if _cmd == 'run': if _src is not None: result = _file_board.run(_src) elif _cmd == 'ls': result = _file_board.ls() elif _cmd == 'get': if _src is not None: result = _file_board.get(_src) elif _cmd == 'put': if _src is not None: result = _file_board.put(_src) _pyboard = None _port = None _cmd = None _src = None _file_board = None print(result)
def put(local, remote): """Put a file or folder and its contents on the board. Put will upload a local file or folder to the board. If the file already exists on the board it will be overwritten with no warning! You must pass at least one argument which is the path to the local file/folder to upload. If the item to upload is a folder then it will be copied to the board recursively with its entire child structure. You can pass a second optional argument which is the path and name of the file/folder to put to on the connected board. For example to upload a main.py from the current directory to the board's root run: ampy --port /board/serial/port put main.py Or to upload a board_boot.py from a ./foo subdirectory and save it as boot.py in the board's root run: ampy --port /board/serial/port put ./foo/board_boot.py boot.py To upload a local folder adafruit_library and all of its child files/folders as an item under the board's root run: ampy --port /board/serial/port put adafruit_library Or to put a local folder adafruit_library on the board under the path /lib/adafruit_library on the board run: ampy --port /board/serial/port put adafruit_library /lib/adafruit_library """ # Use the local filename if no remote filename is provided. if remote is None: remote = os.path.basename(os.path.abspath(local)) # Check if path is a folder and do recursive copy of everything inside it. # Otherwise it's a file and should simply be copied over. if os.path.isdir(local): # Directory copy, create the directory and walk all children to copy # over the files. board_files = files.Files(_board) for parent, child_dirs, child_files in os.walk(local): # Create board filesystem absolute path to parent directory. remote_parent = posixpath.normpath( posixpath.join(remote, os.path.relpath(parent, local))) try: # Create remote parent directory. board_files.mkdir(remote_parent) # Loop through all the files and put them on the board too. for filename in child_files: with open(os.path.join(parent, filename), 'rb') as infile: remote_filename = posixpath.join( remote_parent, filename) board_files.put(remote_filename, infile.read()) except files.DirectoryExistsError: # Ignore errors for directories that already exist. pass else: # File copy, open the file and copy its contents to the board. # Put the file on the board. with open(local, 'rb') as infile: board_files = files.Files(_board) board_files.put(remote, infile.read())
def test_rm(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(return_value=b"") board_files = files.Files(pyboard) board_files.rm('foo.txt')
def put(local, remote): """Put a file or folder and its contents on the board. Put will upload a local file or folder to the board. If the file already exists on the board it will be overwritten with no warning! You must pass at least one argument which is the path to the local file/folder to upload. If the item to upload is a folder then it will be copied to the board recursively with its entire child structure. You can pass a second optional argument which is the path and name of the file/folder to put to on the connected board. For example to upload a main.py from the current directory to the board's root run: ampy --port /board/serial/port put main.py Or to upload a board_boot.py from a ./foo subdirectory and save it as boot.py in the board's root run: ampy --port /board/serial/port put ./foo/board_boot.py boot.py To upload a local folder adafruit_library and all of its child files/folders as an item under the board's root run: ampy --port /board/serial/port put adafruit_library Or to put a local folder adafruit_library on the board under the path /lib/adafruit_library on the board run: ampy --port /board/serial/port put adafruit_library /lib/adafruit_library """ # Use the local filename if no remote filename is provided. if remote is None: remote = os.path.basename(os.path.abspath(local)) # Check if path is a folder and do recursive copy of everything inside it. # Otherwise it's a file and should simply be copied over. if os.path.isdir(local): # Create progress bar for each file pb_bath = PorgressBarBath('Overall progress') for parent, child_dirs, child_files in os.walk(local, followlinks=True): for filename in child_files: path = os.path.join(parent, filename) size = os.stat(path).st_size pb_bath.add_subjob(PorgressBar(name=path,total=size )) # Directory copy, create the directory and walk all children to copy # over the files. board_files = files.Files(_board) for parent, child_dirs, child_files in os.walk(local, followlinks=True): # Create board filesystem absolute path to parent directory. remote_parent = posixpath.normpath( posixpath.join(remote, os.path.relpath(parent, local)) ) try: # Create remote parent directory. board_files.mkdir(remote_parent) except files.DirectoryExistsError: # Ignore errors for directories that already exist. pass # Loop through all the files and put them on the board too. for filename in child_files: local_path = os.path.join(parent, filename) with open(local_path, "rb") as infile: remote_filename = posixpath.join(remote_parent, filename) data = infile.read() job = pb_bath.get_subjob(local_path) callback = job.on_progress_done board_files.put(remote_filename, data, callback) else: # File copy, open the file and copy its contents to the board. # Put the file on the board. with open(local, "rb") as infile: data = infile.read() progress = PorgressBar(name=local, total=len(data)) board_files = files.Files(_board) board_files.put(remote, data, progress.on_progress_done) print('')
def test_get_with_data(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(return_value=b"hello world") board_files = files.Files(pyboard) result = board_files.get('foo.txt') self.assertEqual(result, b"hello world")
def version(): # Delete the provided file/directory on the board. board_files = files.Files(_board) print('Board firmware version is', board_files.version())
def test_put(self): pyboard = mock.Mock() pyboard.exec_ = mock.Mock(return_value=b"") board_files = files.Files(pyboard) board_files.put('foo.txt', 'hello world')