diff --git a/examdownloader-cli.py b/examdownloader-cli.py index 783d510..3f568e9 100644 --- a/examdownloader-cli.py +++ b/examdownloader-cli.py @@ -1,7 +1,6 @@ -import subprocess import sys import getpass -import examdownloader +from examdownloader import examdownloader, openFile module = 'CS1010S' username = 'E0123456' @@ -17,7 +16,7 @@ def startDownload(args): username = args[1] password = getpass.getpass('Enter password for ' + username + ': ') - ed = examdownloader.examdownloader('CLI') + ed = examdownloader('CLI') def updateStatus(msg, type='normal'): @@ -26,7 +25,7 @@ def updateStatus(msg, type='normal'): def downloadCallback(status, lastfile='', numFiles=0): if status: updateStatus(str(numFiles) + ' papers downloaded successfully!', 'success') - subprocess.call(['open', '-R', lastfile]) + openFile(lastfile) else: updateStatus('Paper not released by Department', 'error') diff --git a/examdownloader-gui.py b/examdownloader-gui.py index f80a835..079eb71 100644 --- a/examdownloader-gui.py +++ b/examdownloader-gui.py @@ -1,8 +1,7 @@ from Tkinter import * import tkFileDialog -import subprocess import thread -import examdownloader +from examdownloader import examdownloader, openFile FONT = ('Arial', 14, 'bold') @@ -75,12 +74,12 @@ def startDownload(self): username = self.usernameField.get() password = self.passwordField.get() destination = self.destField.get() - ed = examdownloader.examdownloader('GUI') + ed = examdownloader('GUI') def downloadCallback(status, lastfile='', numFiles=0): if status: self.updateStatus(str(numFiles) + ' papers downloaded successfully!', 'success') - subprocess.call(['open', '-R', lastfile]) + openFile(lastfile) else: self.updateStatus('Paper not released by Department', 'error') diff --git a/examdownloader.py b/examdownloader.py index 3106391..43bc31b 100644 --- a/examdownloader.py +++ b/examdownloader.py @@ -1,6 +1,28 @@ import httplib import urllib import os +import subprocess +import platform + + +def openFile(filepath): + """ + Try to open a file in a desktop environment + Fails gracefully if an exception occurs or no file is passed + """ + if not filepath: + return + try: + # snippet taken from here: https://stackoverflow.com/a/435669 by fearless_fool + if platform.system() == 'Darwin': # macOS + subprocess.call(['open', '-R', filepath]) + elif platform.system() == 'Windows': # Windows + os.startfile(filepath, 'open') + else: # linux variants + subprocess.call(['xdg-open', filepath]) + except OSError: + pass + class examdownloader(object): def __init__(self, mode):