Skip to content

Instantly share code, notes, and snippets.

@sj26
Created March 16, 2011 06:47
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sj26/872112 to your computer and use it in GitHub Desktop.
Save sj26/872112 to your computer and use it in GitHub Desktop.
Python 3 command line interface to http://upcdatabase.com
#!/usr/bin/env python3
import os, sys
import xmlrpc.client
rpc_key = '...' # replace with your RPC Key from http://upcdatabase.com/user
server = xmlrpc.client.ServerProxy('http://www.upcdatabase.com/xmlrpc')
lookup_keys = {12: 'upc', 13: 'ean'}
def print_usage():
print("Usage: %s <upc|ean> | <method> <key1> <value1> [<key2> <value2> ...]" % (sys.argv[0],))
if __name__ == '__main__':
if rpc_key == "...":
print("Error: Please edit this script to add your RPC Key")
print()
print("Hint: %s %s" % (os.environ['EDITOR'] or 'vim', __file__))
sys.exit(-1)
elif len(sys.argv) < 2:
print_usage()
print()
print("Stuck? Try: %s help" % (sys.argv[0],))
sys.exit(-2)
elif len(sys.argv) == 2 and sys.argv[1] in ('-h', '--help', 'help', '--version', '--usage'):
print_usage()
print()
print("This utility substitutes your RPC key for you. Here's some help from the server detailing the available methods:")
print()
print(server.help({'rpc_key': rpc_key})['help'].strip())
else:
if len(sys.argv) == 2 and sys.argv[1].isdigit() and len(sys.argv[1]) in lookup_keys:
method = 'lookup'
params = {lookup_keys[len(sys.argv[1])]: sys.argv[1]}
else:
method = sys.argv[1]
params = dict(zip(sys.argv[2::2], sys.argv[3::2]))
params['rpc_key'] = rpc_key
try:
response = getattr(server, method)(params)
except xmlrpc.client.Error as error:
print("Fault %s: %s" % (error.faultCode, error.faultString.strip()))
sys.exit(1)
except xmlrpc.client.Error as error:
print("Error:", error, repr(error.args))
sys.exit(2)
for key in response:
print("%s: %s" % (key, response[key]))
if 'status' in response and response['status'] == 'fail':
sys.exit(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment