Skip to content

Instantly share code, notes, and snippets.

@ToMe25
Created July 8, 2022 16:16
Show Gist options
  • Save ToMe25/87926996d7775cf273b6346ea19ac529 to your computer and use it in GitHub Desktop.
Save ToMe25/87926996d7775cf273b6346ea19ac529 to your computer and use it in GitHub Desktop.
A python implementation of the OC2 import.lua script
#!/usr/bin/micropython
import devices
import math
import sys
io_device = devices.bus().find("file_import_export")
if not io_device:
sys.stderr.write("A File Import/Export Card is required for this functionality.\n")
sys.exit(1)
io_device.reset()
if not io_device.requestImportFile():
sys.stderr.write("No users present to request file from.\n")
sys.exit(1)
while True:
try:
info = io_device.beginImportFile()
except Exception as error:
if error.args[0] == "import was canceled":
sys.stderr.write("Import was canceled by the user.\n")
sys.exit(1)
else:
raise error
if info:
if len(sys.argv) > 1:
name = sys.argv[1]
elif "name" in info:
name = info["name"]
else:
name = "imported"
size = info["size"]
break
def file_exists(path):
try:
f = open(path, "r")
f.close()
return True
except OSError:
return False
def is_dir(path):
if not file_exists(path):
return False
f = open(path, "r")
try:
f.read()
except OSError:
f.close()
return True
f.close()
return False
while file_exists(name):
sys.stdout.write("File '%s' exists. " % name)
dir = is_dir(name)
if not dir:
sys.stdout.write("[O]verwrite/")
choice = input("[U]se another name/[C]ancel? ")
if not choice or choice == "" or choice == "c" or choice == "C":
sys.exit(0)
elif choice == "u" or choice == "U":
name = input("Enter new name: ")
elif not dir and (choice == "o" or choice == "O"):
break
else:
sys.stderr.write("Invalid option: %s\n" % choice)
sys.exit(1)
sys.stdout.write("Importing " + name)
file = open(name, "wb")
readCount = 0
lastPrintedPercent = 0
while True:
bytes = io_device.readImportFile()
if not bytes:
break
if len(bytes) > 0:
file.write(bytearray(bytes))
readCount += len(bytes)
percent = math.floor(100 * readCount / size)
if percent >= lastPrintedPercent + 5:
sys.stdout.write("\n%d%% " % percent)
lastPrintedPercent = percent
else:
sys.stdout.write(".")
sys.stdout.write("\n")
file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment