wikicrawl/app/cli.py

88 lines
2.4 KiB
Python
Raw Normal View History

2017-08-17 01:27:05 -06:00
#!/usr/bin/env python
import baker
import logging
import readline # Needed for command history <up> and <down> arrows to work
import sys
from . import model
# Problem pages:
# Decision (from politics)
# Malaysia (goes inside parenthesis)
commander = baker.Baker()
settings = {}
def init(settings_obj):
global settings
settings = settings_obj
model.init(settings_obj)
def main():
user_interface = InteractiveInterface()
if len(sys.argv) > 1: # Command line arguments were passed in
# command-line when invoking python
user_interface.run(sys.argv)
else:
user_interface.start_command_loop()
class InteractiveInterface:
def __init__(self):
self.model = model.Model()
2017-08-17 01:45:07 -06:00
x = self.model.webdriver # Request the browser open immediately
2017-08-17 01:27:05 -06:00
def run(self, args, main=True):
try:
commander.run(argv=args, main=True, help_on_error=True,
instance=self)
except baker.CommandError as ex:
logging.warn('incorrect user input: %s' % ex)
commander.usage()
except baker.TopHelp as ex:
commander.usage()
except Exception as ex:
logging.error('caught general exception!!')
print(type(ex), ex)
def start_command_loop(self):
"""
Repeatedly asks the user what command to run until they exit.
"""
commander.usage()
while True:
print('$ ', end = '') # Display to the user a command prompt
try:
inp = input()
except EOFError: # <ctrl>+D will send "End Line" and exit the command loop
break
args = ['', ] + inp.split()
if "--help" in args:
args.remove("--help")
try:
commander.usage(args[1])
except Exception as ex:
print(type(ex), ex)
continue
self.run(args, main=False)
@commander.command
def do_random_page(self):
self.model.do_random_page()
@commander.command
def do_n_pages(self, n):
try:
n = int(n)
except ValueError as ex:
return False
for i in range(n):
self.model.do_random_page()
if __name__ == '__main__':
main()