Skip to content

Instantly share code, notes, and snippets.

@Disassembler0
Last active February 19, 2019 20:04
Show Gist options
  • Save Disassembler0/0905984a308ff312f54998fe02e2b567 to your computer and use it in GitHub Desktop.
Save Disassembler0/0905984a308ff312f54998fe02e2b567 to your computer and use it in GitHub Desktop.
import subprocess
def install_package(package):
percent = 0
# Alpine apk provides machine-readable progress in bytes_downloaded/bytes_total format output to file descriptor of choice, so create a pipe for it
pipe_rfd, pipe_wfd = os.pipe()
with os.fdopen(pipe_rfd) as pipe_rf:
with subprocess.Popen(['apk', '--progress-fd', str(pipe_wfd), '--no-cache', 'add', package], pass_fds=[pipe_wfd]) as p:
# Close write pipe for vmmgr to not block the pipe once apk finishes
os.close(pipe_wfd)
while p.poll() == None:
# Wait for line end or EOF in read pipe and process it
data = pipe_rf.readline()
if data:
progress = data.rstrip().split('/')
percent = math.floor(int(progress[0]) / int(progress[1]) * 100)
# If the apk command didn't finish with returncode 0, raise an exception
if p.returncode:
raise subprocess.CalledProcessError(p.returncode, p.args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment