diff --git a/TreeGopher.py b/TreeGopher.py index 591d48b..cb14d55 100644 --- a/TreeGopher.py +++ b/TreeGopher.py @@ -68,7 +68,7 @@ def populate(parentNode, request): window.FindElement('-QUERY-').update(request.url()) window.FindElement('-LOADING-').update(visible=True) - if not parentNode in openNodes: + if parentNode not in openNodes: passes = 0 from_cache = False try: @@ -80,25 +80,34 @@ def populate(parentNode, request): cache[request.url()] = resp passes += 1 except: - sg.popup("We're sorry!", request.url() + ' could not be fetched. Try again later.') + sg.popup( + "We're sorry!", + f'{request.url()} could not be fetched. Try again later.', + ) if passes == 1: try: menu = trim_menu(resp.menu()) passes += 1 except: - sg.popup("We're sorry!", request.url() + ' could not be parsed as a menu for one reason or another.') + sg.popup( + "We're sorry!", + f'{request.url()} could not be parsed as a menu for one reason or another.', + ) if passes == 2: if from_cache: - gophertree.insert(parentNode, request.url() + ' ', text='- This is a cached menu, double click to go to the live version -', values=[], icon=icons['cache']) + gophertree.insert( + parentNode, + f'{request.url()} ', + text='- This is a cached menu, double click to go to the live version -', + values=[], + icon=icons['cache'], + ) for item in menu: - if not item.request().url() in openNodes: + if item.request().url() not in openNodes: sub_url = item.request().url() if item.path.startswith("URL:"): sub_url = item.path[4:] - if item.type in icons: - icon = icons[item.type] - else: - icon = icons['9'] + icon = icons[item.type] if item.type in icons else icons['9'] if item.type == 'i': gophertree.insert(parentNode, sub_url, text=item.text, values=[], icon=icon) @@ -118,17 +127,21 @@ def download_thread(req, dlpath, gui_queue): # This uses Pituophis' Request( with open(dlpath, "wb") as dl: remote_file = req.stream().makefile('rb') while True: - piece = remote_file.read(1024) - if not piece: + if piece := remote_file.read(1024): + dl.write(piece) + else: break - dl.write(piece) gui_queue.put(dlpath) # put a message into queue for GUI history = [] def dlPopup(url): - return sg.popup_get_file('Where to save this file?', 'Download {}'.format( - url), default_path=url.split('/')[-1], save_as=True) + return sg.popup_get_file( + 'Where to save this file?', + f'Download {url}', + default_path=url.split('/')[-1], + save_as=True, + ) def go(url): global gophertree, openNodes, loadedTextURL @@ -152,19 +165,17 @@ def go(url): loadedTextURL = req.url() window.FindElement('-OUTPUT-').update(resp.text()) except: - sg.popup("We're sorry!", req.url() + ' could not be fetched. Try again later.') + sg.popup("We're sorry!", f'{req.url()} could not be fetched. Try again later.') else: dlpath = dlPopup(req.url()) - if not dlpath is None: - window.FindElement('-DOWNLOADS-').update(value='Downloading {}'.format(dlpath)) + if dlpath is not None: + window.FindElement('-DOWNLOADS-').update(value=f'Downloading {dlpath}') threading.Thread(target=download_thread, args=(req, dlpath, gui_queue), daemon=True).start() window.FindElement('-LOADING-').update(visible=False) def plural(x): - if x > 1 or x < 1: - return 's' - return '' + return 's' if x > 1 or x < 1 else '' previousvalue = None @@ -185,26 +196,25 @@ def plural(x): url = url[:-9] del cache[url] go(url) - else: - if url.startswith('gopher'): - req = pituophis.parse_url(url) - if req.type == '1': - parentNode = url - if value['-USETREE-']: - populate(parentNode, req) - else: - go(parentNode) - elif req.type == '7': - q = sg.popup_get_text('Search on ' + req.host, '') - if not q is None: - req.query = q - go(req.url()) - elif req.type != 'i': + elif url.startswith('gopher'): + req = pituophis.parse_url(url) + if req.type == '1': + parentNode = url + if value['-USETREE-']: + populate(parentNode, req) + else: + go(parentNode) + elif req.type == '7': + q = sg.popup_get_text(f'Search on {req.host}', '') + if q is not None: + req.query = q go(req.url()) + elif req.type != 'i': + go(req.url()) - window.FindElement('-LOADING-').update(visible=False) - else: - os.startfile(url) + window.FindElement('-LOADING-').update(visible=False) + else: + os.startfile(url) previousvalue = value elif event == 'Go': go(value['-QUERY-'].rstrip()) @@ -223,7 +233,7 @@ def plural(x): pyperclip.copy(loadedTextURL) elif event == 'Save...': dlpath = dlPopup(loadedTextURL) - if not dlpath is None: + if dlpath is not None: with open(dlpath, 'w') as f: f.write(value['-OUTPUT-']) @@ -236,7 +246,11 @@ def plural(x): # if message received from queue, display the message in the Window if message: window.FindElement('-DOWNLOADS-').update(value='') - if sg.popup_yes_no('Finished downloading {}. Would you like to open the downloaded file?'.format(message)): + if sg.popup_yes_no( + f'Finished downloading {message}. Would you like to open the downloaded file?' + ): os.startfile(message) - window.FindElement('-CACHE-').update(value='{} menu{} in cache.'.format(len(cache), plural(len(cache)))) + window.FindElement('-CACHE-').update( + value=f'{len(cache)} menu{plural(len(cache))} in cache.' + ) window.close() \ No newline at end of file diff --git a/build/lib/pituophis/__init__.py b/build/lib/pituophis/__init__.py index 399be21..99ab4cd 100644 --- a/build/lib/pituophis/__init__.py +++ b/build/lib/pituophis/__init__.py @@ -149,13 +149,11 @@ def url(self): """ protocol = 'gopher' path = self.path - query = '' - if not (self.query == ''): - query = '%09' + self.query + query = f'%09{self.query}' if self.query != '' else '' hst = self.host - if not self.port == 70: - hst += ':{}'.format(self.port) - return '{}://{}/{}{}{}'.format(protocol, hst, self.type, path, query) + if self.port != 70: + hst += f':{self.port}' + return f'{protocol}://{hst}/{self.type}{path}{query}' class Item: @@ -227,8 +225,7 @@ def parse_menu(source): line) > 4: # discard Gopher+ and other naughty stuff line = line[:-1] line = '\t'.join(line) - matches = re.match(r'^(.)(.*)\t(.*)\t(.*)\t(.*)', line) - if matches: + if matches := re.match(r'^(.)(.*)\t(.*)\t(.*)\t(.*)', line): item.type = matches[1] item.text = matches[2] item.path = matches[3] @@ -251,12 +248,12 @@ def parse_url(url): up = urlparse(url) if up.scheme == '': - up = urlparse('gopher://' + url) + up = urlparse(f'gopher://{url}') req.path = up.path if up.query: - req.path += '?{}'.format(up.query) # NOT to be confused with actual gopher queries, which use %09 - # this just combines them back into one string + req.path += f'?{up.query}' + # this just combines them back into one string req.host = up.hostname req.port = up.port if up.port is None: @@ -347,7 +344,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', if not path.startswith('URL:'): # fix relative path if not path.startswith('/'): - path = realpath(gophermap_dir + '/' + path) + path = realpath(f'{gophermap_dir}/{path}') # globbing if '*' in path: @@ -387,10 +384,12 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', while '' in splt: splt.remove('') s.text = splt[len(splt) - 1] - if os.path.exists(file + '/gophertag'): - s.text = ''.join(list(open( - file + '/gophertag'))).replace( - '\r\n', '').replace('\n', '') + if os.path.exists(f'{file}/gophertag'): + s.text = ( + ''.join(list(open(f'{file}/gophertag'))) + .replace('\r\n', '') + .replace('\n', '') + ) s.path = file.replace(pub_dir, '/', 1) s.path = re.sub(r'/{2}', r'/', s.path) s.host = host @@ -399,15 +398,12 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', s.path = '' s.host = '' s.port = '0' - if s.type == '1': - d = 0 - else: - d = 1 - if not s.path.endswith('gophermap'): - if not s.path.endswith( - 'gophertag'): - listing.append( - [file, s, s.text, d]) + d = 0 if s.type == '1' else 1 + if not s.path.endswith( + 'gophermap' + ) and not s.path.endswith('gophertag'): + listing.append( + [file, s, s.text, d]) listing = natsorted(listing, key=itemgetter(0)) @@ -416,8 +412,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', listing = natsorted(listing, key=itemgetter(3)) - for item in listing: - new_menu.append(item[1]) + new_menu.extend(item[1] for item in listing) else: new_menu.append(errors['403_glob']) @@ -438,10 +433,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', mime = mimetypes.guess_type( pub_dir + path)[0] if mime is None: # is directory or binary - if os.path.isdir(file): - s.type = '1' - else: - s.type = '9' + s.type = '1' if os.path.isdir(file) else '9' else: for sw in mime_starts_with.keys(): if mime.startswith(sw): @@ -450,7 +442,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', new_menu.append(item.source()) else: - item = 'i' + item + '\t\t\t0' + item = f'i{item}' + '\t\t\t0' new_menu.append(item) return new_menu @@ -492,32 +484,25 @@ def handle(request): if os.path.isdir(res_path): # is directory if os.path.exists(res_path): - if os.path.isfile(res_path + '/gophermap'): - in_file = open(res_path + '/gophermap', "r+") - gmap = in_file.read() - in_file.close() - menu = parse_gophermap(source=gmap, - def_host=request.host, - def_port=request.advertised_port, - gophermap_dir=request.path, - pub_dir=pub_dir) + if os.path.isfile(f'{res_path}/gophermap'): + with open(f'{res_path}/gophermap', "r+") as in_file: + gmap = in_file.read() else: gmap = '?*\t\r\n' - menu = parse_gophermap(source=gmap, - def_host=request.host, - def_port=request.advertised_port, - gophermap_dir=request.path, - pub_dir=pub_dir) - return menu + return parse_gophermap( + source=gmap, + def_host=request.host, + def_port=request.advertised_port, + gophermap_dir=request.path, + pub_dir=pub_dir, + ) elif os.path.isfile(res_path): - in_file = open(res_path, "rb") - data = in_file.read() - in_file.close() + with open(res_path, "rb") as in_file: + data = in_file.read() return data if request.alt_handler: - alt = request.alt_handler(request) - if alt: + if alt := request.alt_handler(request): return alt e = errors['404'] @@ -536,7 +521,7 @@ def serve(host="127.0.0.1", port=70, advertised_port=None, """ if pub_dir is None or pub_dir == '': pub_dir = '.' - print('Gopher server is now running on', host + ':' + str(port) + '.') + print('Gopher server is now running on', f'{host}:{str(port)}.') class GopherProtocol(asyncio.Protocol): def connection_made(self, transport): diff --git a/examples/catenifer.py b/examples/catenifer.py index c737010..9e8e377 100644 --- a/examples/catenifer.py +++ b/examples/catenifer.py @@ -29,10 +29,9 @@ def go(url, itype=''): # req.type = '1' parse_url() now does this in Pituophis 1.0 if itype == '7': req.type = itype - print(bold('URL: ' + req.url())) - if req.type == '7': - if req.query == '': - req.query = input(bold('Search term: ')) + print(bold(f'URL: {req.url()}')) + if req.type == '7' and req.query == '': + req.query = input(bold('Search term: ')) if req.type in compatibleTypes: resp = req.get() if req.type in menuTypes: @@ -42,13 +41,13 @@ def go(url, itype=''): text = typeIcons['9'] if selector.type in typeIcons: text = typeIcons[selector.type] - text = text + ' ' + selector.text + text = f'{text} {selector.text}' if selector.type not in noLinkTypes: items += 1 requests[items] = selector.request() - text = text + ' (' + requests[items].url() + ') ' + bold('[#' + str(items) + ']') + text = f"{text} ({requests[items].url()}) {bold(f'[#{items}]')}" if selector.path.startswith('URL:'): - text = text + ' (' + selector.path.split('URL:')[1] + ')' + text = f'{text} (' + selector.path.split('URL:')[1] + ')' print(text) elif req.type == '0': print(resp.text()) diff --git a/examples/server_custom.py b/examples/server_custom.py index 6a9b8c0..45645b0 100644 --- a/examples/server_custom.py +++ b/examples/server_custom.py @@ -4,30 +4,37 @@ def handle(request): if request.path == '/txt': - text = """ + return """ This is plain text. Nothing fancy. """ - return text elif request.path == '/server.png': - in_file = open("server.png", "rb") # you'd need a file with the name server.png in the working directory, naturally - data = in_file.read() - in_file.close() + with open("server.png", "rb") as in_file: + data = in_file.read() return data else: - # Note that clients may send '.' or '' when they want the root of the server; - # the . behavior has been observed in Gophpup (an early Windows client) and may be the case for others. - menu = [ - Item(text="Path: " + request.path), - Item(text="Query: " + request.query), - Item(text="Host: " + request.host), - Item(text="Port: " + str(request.port)), - Item(text="Client: " + request.client), + return [ + Item(text=f"Path: {request.path}"), + Item(text=f"Query: {request.query}"), + Item(text=f"Host: {request.host}"), + Item(text=f"Port: {str(request.port)}"), + Item(text=f"Client: {request.client}"), Item(), - Item(itype="I", text="View server.png", path="/server.png", host=request.host, port=request.port), - Item(itype="0", text="View some text", path="/txt", host=request.host, port=request.port) + Item( + itype="I", + text="View server.png", + path="/server.png", + host=request.host, + port=request.port, + ), + Item( + itype="0", + text="View some text", + path="/txt", + host=request.host, + port=request.port, + ), ] - return menu # serve with custom handler diff --git a/examples/server_custom_comments.py b/examples/server_custom_comments.py index 410a113..65b8294 100644 --- a/examples/server_custom_comments.py +++ b/examples/server_custom_comments.py @@ -19,8 +19,7 @@ def handle(request): Item()] if len(comments) == 0: menu.append(Item(text="There are no messages yet.. be the first!")) - for entry in comments: - menu.append(Item(text=str(entry))) + menu.extend(Item(text=str(entry)) for entry in comments) return menu diff --git a/examples/tests_client.py b/examples/tests_client.py index 5cad205..aac20a1 100644 --- a/examples/tests_client.py +++ b/examples/tests_client.py @@ -18,7 +18,7 @@ choices = ['1', '2', '3', '4', '5', '6'] choice = '' -while not choice in choices: +while choice not in choices: choice = input('> ') host = 'gopher.floodgap.com' @@ -30,12 +30,10 @@ if choice == '1': menu = True -if choice == '2': - pass -if choice == '3': +elif choice == '3': path = '/v2/vs' query = 'test' -if choice == '4': +elif choice == '4': binary = True #path = '/archive/info-mac/edu/yng/kid-pix.hqx' path = '/gopher/clients/win/hgopher2_3.zip' @@ -47,10 +45,7 @@ binary = False if input('binary? (y/n): ') in yes: binary = True - menu = False - if not binary: - if input('menu? (y/n): ') in yes: - menu = True + menu = not binary and input('menu? (y/n): ') in yes if choice == '6': if input('binary? (y/n): ') in yes: binary = True @@ -65,20 +60,18 @@ """) choices = ['1', '2'] choice = '' - while not choice in choices: + while choice not in choices: choice = input('> ') if choice == '1': print(response.text()) - else: - if choice == '2': - suggested_filename = path.split('/')[len(path.split('/')) - 1] - filename = input('filename (' + suggested_filename + ')? ') - if filename == '': - filename = suggested_filename - with open(filename, "wb") as f: - f.write(response.binary) + elif choice == '2': + suggested_filename = path.split('/')[len(path.split('/')) - 1] + filename = input(f'filename ({suggested_filename})? ') + if filename == '': + filename = suggested_filename + with open(filename, "wb") as f: + f.write(response.binary) +elif menu: + print(response.menu()) else: - if menu: - print(response.menu()) - else: - print(response.text()) \ No newline at end of file + print(response.text()) \ No newline at end of file diff --git a/pituophis/__init__.py b/pituophis/__init__.py index 24dec3a..6af30fa 100644 --- a/pituophis/__init__.py +++ b/pituophis/__init__.py @@ -152,13 +152,11 @@ def url(self): """ protocol = 'gopher' path = self.path - query = '' - if not (self.query == ''): - query = '%09' + self.query + query = f'%09{self.query}' if self.query != '' else '' hst = self.host - if not self.port == 70: - hst += ':{}'.format(self.port) - return '{}://{}/{}{}{}'.format(protocol, hst, self.type, path, query) + if self.port != 70: + hst += f':{self.port}' + return f'{protocol}://{hst}/{self.type}{path}{query}' class Item: @@ -230,8 +228,7 @@ def parse_menu(source): line) > 4: # discard Gopher+ and other naughty stuff line = line[:-1] line = '\t'.join(line) - matches = re.match(r'^(.)(.*)\t(.*)\t(.*)\t(.*)', line) - if matches: + if matches := re.match(r'^(.)(.*)\t(.*)\t(.*)\t(.*)', line): item.type = matches[1] item.text = matches[2] item.path = matches[3] @@ -254,12 +251,12 @@ def parse_url(url): up = urlparse(url) if up.scheme == '': - up = urlparse('gopher://' + url) + up = urlparse(f'gopher://{url}') req.path = up.path if up.query: - req.path += '?{}'.format(up.query) # NOT to be confused with actual gopher queries, which use %09 - # this just combines them back into one string + req.path += f'?{up.query}' + # this just combines them back into one string req.host = up.hostname req.port = up.port if up.port is None: @@ -350,7 +347,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', if not path.startswith('URL:'): # fix relative path if not path.startswith('/'): - path = realpath(gophermap_dir + '/' + path) + path = realpath(f'{gophermap_dir}/{path}') # globbing if '*' in path: @@ -390,10 +387,12 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', while '' in splt: splt.remove('') s.text = splt[len(splt) - 1] - if os.path.exists(file + '/gophertag'): - s.text = ''.join(list(open( - file + '/gophertag'))).replace( - '\r\n', '').replace('\n', '') + if os.path.exists(f'{file}/gophertag'): + s.text = ( + ''.join(list(open(f'{file}/gophertag'))) + .replace('\r\n', '') + .replace('\n', '') + ) s.path = file.replace(pub_dir, '/', 1) s.path = re.sub(r'/{2}', r'/', s.path) s.host = host @@ -402,15 +401,12 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', s.path = '' s.host = '' s.port = '0' - if s.type == '1': - d = 0 - else: - d = 1 - if not s.path.endswith('gophermap'): - if not s.path.endswith( - 'gophertag'): - listing.append( - [file, s, s.text, d]) + d = 0 if s.type == '1' else 1 + if not s.path.endswith( + 'gophermap' + ) and not s.path.endswith('gophertag'): + listing.append( + [file, s, s.text, d]) listing = natsorted(listing, key=itemgetter(0)) @@ -419,8 +415,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', listing = natsorted(listing, key=itemgetter(3)) - for item in listing: - new_menu.append(item[1]) + new_menu.extend(item[1] for item in listing) else: new_menu.append(errors['403_glob']) @@ -441,10 +436,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', mime = mimetypes.guess_type( pub_dir + path)[0] if mime is None: # is directory or binary - if os.path.isdir(file): - s.type = '1' - else: - s.type = '9' + s.type = '1' if os.path.isdir(file) else '9' else: for sw in mime_starts_with.keys(): if mime.startswith(sw): @@ -453,7 +445,7 @@ def parse_gophermap(source, def_host='127.0.0.1', def_port='70', new_menu.append(item.source()) else: - item = 'i' + item + '\t\t\t0' + item = f'i{item}' + '\t\t\t0' new_menu.append(item) return new_menu @@ -489,7 +481,7 @@ def handle(request): request.path = '/' res_path = os.path.abspath( (pub_dir + request.path) - .replace('\\', '/').replace('//', '/')) + .replace('\\', '/').replace('//', '/')) print(res_path) if not res_path.startswith(os.path.abspath(pub_dir)): # Reject connections that try to break out of the publish directory @@ -497,32 +489,25 @@ def handle(request): if os.path.isdir(res_path): # is directory if os.path.exists(res_path): - if os.path.isfile(res_path + '/gophermap'): - in_file = open(res_path + '/gophermap', "r+") - gmap = in_file.read() - in_file.close() - menu = parse_gophermap(source=gmap, - def_host=request.host, - def_port=request.advertised_port, - gophermap_dir=request.path, - pub_dir=pub_dir) + if os.path.isfile(f'{res_path}/gophermap'): + with open(f'{res_path}/gophermap', "r+") as in_file: + gmap = in_file.read() else: gmap = '?*\t\r\n' - menu = parse_gophermap(source=gmap, - def_host=request.host, - def_port=request.advertised_port, - gophermap_dir=request.path, - pub_dir=pub_dir) - return menu + return parse_gophermap( + source=gmap, + def_host=request.host, + def_port=request.advertised_port, + gophermap_dir=request.path, + pub_dir=pub_dir, + ) elif os.path.isfile(res_path): - in_file = open(res_path, "rb") - data = in_file.read() - in_file.close() + with open(res_path, "rb") as in_file: + data = in_file.read() return data if request.alt_handler: - alt = request.alt_handler(request) - if alt: + if alt := request.alt_handler(request): return alt e = errors['404'] @@ -540,7 +525,7 @@ def serve(host="127.0.0.1", port=70, advertised_port=None, """ if pub_dir is None or pub_dir == '': pub_dir = '.' - print('Gopher server is now running on', host + ':' + str(port) + '.') + print('Gopher server is now running on', f'{host}:{str(port)}.') class GopherProtocol(asyncio.Protocol): def connection_made(self, transport): diff --git a/pituophis/cli.py b/pituophis/cli.py index faa3997..75c3424 100644 --- a/pituophis/cli.py +++ b/pituophis/cli.py @@ -20,59 +20,51 @@ print(' -v, --version\t\t\tPrint version') print('Fetch Options:') print(' -o, --output=FILE\t\tFile to write to (default: stdout)') -else: - # check if the user is serving or fetching - if sys.argv[1] == 'serve': - # check for arguments - # host - host = '127.0.0.1' - if '-H' in sys.argv or '--host' in sys.argv: - host = sys.argv[sys.argv.index('-H') + 1] - # port - port = 70 - if '-p' in sys.argv or '--port' in sys.argv: - port = int(sys.argv[sys.argv.index('-p') + 1]) - # advertised port - advertised_port = None - if '-a' in sys.argv or '--advertised-port' in sys.argv: - advertised_port = int(sys.argv[sys.argv.index('-a') + 1]) - # directory - pub_dir = 'pub/' - if '-d' in sys.argv or '--directory' in sys.argv: - pub_dir = sys.argv[sys.argv.index('-d') + 1] - # alternate handler - alt_handler = False - if '-A' in sys.argv or '--alt-handler' in sys.argv: - alt_handler = sys.argv[sys.argv.index('-A') + 1] - # get the function from the file - alt_handler = getattr( - importlib.import_module(alt_handler), 'handler') - - # send period - send_period = False - if '-s' in sys.argv or '--send-period' in sys.argv: - send_period = True - # debug - debug = False - if '-D' in sys.argv or '--debug' in sys.argv: - debug = True - # start the server - pituophis.serve(host=host, port=port, advertised_port=advertised_port, - handler=pituophis.handle, pub_dir=pub_dir, alt_handler=alt_handler, - send_period=send_period, debug=debug) - elif sys.argv[1] == 'fetch': - # check for arguments - # url - url = sys.argv[2] - # output file - output = 'stdout' - if '-o' in sys.argv or '--output' in sys.argv: - output = sys.argv[sys.argv.index('-o') + 1] - # start the fetch - o = pituophis.get(url) - if output == 'stdout': - sys.stdout.buffer.write(o.binary) - else: - with open(output, 'wb') as f: - f.write(o.binary) - f.close() \ No newline at end of file +elif sys.argv[1] == 'serve': + host = ( + sys.argv[sys.argv.index('-H') + 1] + if '-H' in sys.argv or '--host' in sys.argv + else '127.0.0.1' + ) + # port + port = 70 + if '-p' in sys.argv or '--port' in sys.argv: + port = int(sys.argv[sys.argv.index('-p') + 1]) + # advertised port + advertised_port = None + if '-a' in sys.argv or '--advertised-port' in sys.argv: + advertised_port = int(sys.argv[sys.argv.index('-a') + 1]) + # directory + pub_dir = 'pub/' + if '-d' in sys.argv or '--directory' in sys.argv: + pub_dir = sys.argv[sys.argv.index('-d') + 1] + # alternate handler + alt_handler = False + if '-A' in sys.argv or '--alt-handler' in sys.argv: + alt_handler = sys.argv[sys.argv.index('-A') + 1] + # get the function from the file + alt_handler = getattr( + importlib.import_module(alt_handler), 'handler') + + send_period = '-s' in sys.argv or '--send-period' in sys.argv + debug = '-D' in sys.argv or '--debug' in sys.argv + # start the server + pituophis.serve(host=host, port=port, advertised_port=advertised_port, + handler=pituophis.handle, pub_dir=pub_dir, alt_handler=alt_handler, + send_period=send_period, debug=debug) +elif sys.argv[1] == 'fetch': + # check for arguments + # url + url = sys.argv[2] + # output file + output = 'stdout' + if '-o' in sys.argv or '--output' in sys.argv: + output = sys.argv[sys.argv.index('-o') + 1] + # start the fetch + o = pituophis.get(url) + if output == 'stdout': + sys.stdout.buffer.write(o.binary) + else: + with open(output, 'wb') as f: + f.write(o.binary) + f.close() \ No newline at end of file