#! /usr/bin/env python3
import sys
MOBILE_EXAMPLE_STRING = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) FxiOS/8.3b5826 Mobile/14G60 Safari/603.3.8' # noqa
DESKTOP_EXAMPLE_STRING = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36' # noqa
def print_help_and_exit(error_msg=None, error_code=0, print_help=True):
if error_msg:
print('ERROR:', f' {error_msg}', '\n', sep='\n')
if print_help:
msg = f''' user_agent accepts a user agent string from a browser and attempts to parse system information from it
USAGE: $ user_agent "{DESKTOP_EXAMPLE_STRING}"
>>> Chrome (60, 0, 3112) | Windows 7
HELP:
"Other () | Other" was returned - the user agent string you passed to this function was not recognized
'''
print(msg)
sys.exit(error_code)
def parse(user_agent_raw_string):
from user_agents import parse
ua = parse(user_agent_raw_string)
is_mobile = ': is mobile' if ua.is_mobile else ''
return f'{ua.browser.family} {ua.browser.version} | {ua.os.family}{is_mobile}'
def run():
try:
print(parse(sys.argv[1]))
except IndexError:
print_help_and_exit(error_msg='argument is required', error_code=1)
except ImportError:
error_message = '''user_agents python package is required
TRY:
$ pip install user_agents
'''
print_help_and_exit(error_msg=error_message, error_code=2)
if __name__ == '__main__':
run()