From 2a07e0621fa6563bdb36b462a0ed15323f477d9a Mon Sep 17 00:00:00 2001 From: Stefan Weiher Date: Tue, 20 Jun 2017 13:05:03 +0200 Subject: [PATCH] Updated all wc_*.py scripts so that they can be called via command line as well as from another python script. Updated the README file. Extended the build script so that now all executables are in one directory, the bin directory. --- EXAMPLES | 3 + README | 24 +++++- __init__.py | 0 build_project.sh | 16 +++- wc_getReport.py | 215 +++++++++++++++++++++++++++-------------------- wc_getTrend.py | 185 ++++++++++++++++++++++++---------------- wc_getValue.py | 126 ++++++++++++++++----------- wc_query.py | 142 +++++++++++++++++++------------ 8 files changed, 437 insertions(+), 274 deletions(-) create mode 100644 __init__.py diff --git a/EXAMPLES b/EXAMPLES index 55ae1df..1ba324d 100644 --- a/EXAMPLES +++ b/EXAMPLES @@ -14,6 +14,7 @@ Children of "/trees/geographic/#geb_e/#kaltw_erzeuger_fel/#km_speicher_fel": [m032, m007, m008, m034, m033, m001, m005, m004, m003, m002, m006, ...] + ### wc_getValue - get the present value (the present_value attribute) of a m??? controller $ ./wc_getValue -u wsdl -n /trees/geographic/#geb_e/#kaltw_erzeuger_fel/#km_speicher_fel/m001 @@ -21,6 +22,7 @@ No password specified via -p. Please enter your WebCTRL login password: Present value of /trees/geographic/#geb_e/#kaltw_erzeuger_fel/#km_speicher_fel/m001 is: 15.600924 + ### wc_getReport - get a report for a node (one level lower than m???) $ ./wc_getReport -u wsdl -n /trees/geographic/#geb_e/#kaltw_erzeuger_fel/#km_speicher_fel/m001 @@ -39,6 +41,7 @@ No password specified via -p. Please enter your WebCTRL login password: | ... + ### wc_getTrend - get timestamps and data values of a specific controller for a specific time period ### If no time period and number of values to retrieve are specified you'll get the last ten values diff --git a/README b/README index a0b4ace..1ad84cf 100644 --- a/README +++ b/README @@ -15,11 +15,11 @@ Building the tools webctrl$ ./build_project.sh -The executables can be found in ./dist/wc_*/wc_* +The executables wc_* can be found in ./bin -Add the directory to the PATH environment variable (in your ~/.bashrc) in order to be able to +Add the bin directory to the PATH environment variable (in your ~/.bashrc) in order to be able to execute the wc_* commands everywhere: -PATH=$PATH:$HOME/.../webctrl/dist/wc_query:$HOME/.../webctrl/dist/wc_getValue:... +export PATH="$PATH:/path/to/webctrl/bin" Running the tools ----------------- @@ -39,4 +39,22 @@ wc_getValue : Retrieve the current value of a device wc_getTrend : Retrieve data and date for a given time period and device +Usage of the tools in another python script +------------------------------------------- + +Analogous to the command line usage + +./wc_query -u wsdl -n '/trees/geographic' -url 'https://webctrl.rz-berlin.mpg.de' + +wc_query can be used as follows in another python script, say, ~/test.py: + +import wc_query +myDictonary = {'username':'wsdl', 'password':'seife', 'node':'/trees/geographic', 'url':'https://webctrl.rz-berlin.mpg.de'} +wc_query.main(myDictonary) + +To be able to import the wc_* tools append to the PYTHONPATH the webctrl directory. There are two possible ways: + 1) Set the PYTHONPATH environment variable in the shell in which you run your python script that uses the tool(s): + export PYTHONPATH="$PYTHONPATH:/path/to/webctrl" + 2) Set the python path inside the python script before the import statement: + sys.path.append('/path/to/webctrl') diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build_project.sh b/build_project.sh index 82b8d0f..eff0331 100755 --- a/build_project.sh +++ b/build_project.sh @@ -1,11 +1,21 @@ #!/bin/bash PYDIR=. -INSTALLDIR=dist/. +INSTALLDIR=dist -for FILE in ${PYDIR}/*.py; do +cd ${PYDIR} + +if [ -d bin ]; then + rm -rf bin/* +else + mkdir bin +fi + +for FILE in wc_*.py; do pyinstaller --distpath ${INSTALLDIR} ${FILE} + cp ${INSTALLDIR}/wc_*/* bin + rm -rf ${INSTALLDIR}/wc_* done - +rm -rf ${INSTALLDIR} diff --git a/wc_getReport.py b/wc_getReport.py index b4d6ca8..688e67b 100644 --- a/wc_getReport.py +++ b/wc_getReport.py @@ -6,98 +6,129 @@ import getpass -if len(sys.argv) < 2: - print "You haven't specified any arguments. Use -h to get more details on how to use this command." - - -parser = argparse.ArgumentParser() -parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') -parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') -parser.add_argument('--node', '-n', type=str, default=None, - help='Path to the point or node for which you want to retrieve a report.') -parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', help="URL of the WebCTRL server as e.g. http://google.de") -args = parser.parse_args() - - -if args.username is None: - print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h' - sys.exit(1) -else: - username = args.username -if args.password is None: - password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') -else: - password = args.password -if args.node is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) -if args.url is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' - sys.exit(1) -else: - wsdlFile = args.url + '/_common/webservices/Report?wsdl' - - -try: - client = suds.client.Client(wsdlFile, username=username, password=password) -except AttributeError: - print 'Error: Incorrect username and/or password' -except xml.sax._exceptions.SAXParseException: - print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' - sys.exit(1) -except: - print("Unexpected error:", sys.exc_info()[0]) - sys.exit(1) - - -# Get the report -try: - report = client.service.runReport(args.node, '~point-list-report', 'csv') -except suds.WebFault as fault: - print fault - sys.exit(1) - -# Split the report into separate lines and calculate the number of columns -lines = report.split("\n") -nColumns = len(lines[0].split(",")) - -# Declare arrays -maxColumnWidth = [0 for i in range(nColumns)] -emptyColumns = numpy.full(nColumns, True, dtype=bool) - -# Initialize the maximum column widths by the width of the column headers -column = lines[0].replace('"', '').split(",") -for i, col in enumerate(column): - maxColumnWidth[i] = len(col) - -# Calculate the maximum column width taking into account all entries of each column and check whether a column is completely empty. -# If only one entry of a specific column is not empty the whole column will be marked as not empty. -for l, line in enumerate(lines): - if l > 0 and len(line) > 0: - column = line.replace('"', '').split(",") - for i, col in enumerate(column): - if len(col) > maxColumnWidth[i]: - maxColumnWidth[i] = len(col) - if col.strip() != "": - emptyColumns[i] = False - -# Print the report in column format skipping those columns that are marked as completely empty. -for l, line in enumerate(lines): - if len(line) > 0: - column = line.replace('"', '').split(",") - c = '|' - for i, col in enumerate(column): - if not emptyColumns[i]: - formatStr = ' {:<'+str(maxColumnWidth[i])+'}' - c = c + formatStr.format(col) + ' |' - print c - if l == 0: +def main(args): + # Check all arguments + try: + if args['username'] is None: + print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + username = args['username'] + except KeyError: + print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + sys.exit(1) + + try: + if args['password'] is None: + print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + password = args['password'] + except KeyError: + print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + sys.exit(1) + + try: + if args['node'] is None: + print 'No path to a node specified. Check all options for this command via -h' + sys.exit(1) + except KeyError: + print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + sys.exit(1) + + try: + if args['url'] is None: + print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + sys.exit(1) + else: + wsdlFile = args['url'] + '/_common/webservices/Report?wsdl' + except KeyError: + print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + sys.exit(1) + + + # Connect to the webCTRL server + try: + client = suds.client.Client(wsdlFile, username=username, password=password) + except AttributeError: + print 'Error: Incorrect username and/or password' + except xml.sax._exceptions.SAXParseException: + print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' + sys.exit(1) + except: + print("Unexpected error:", sys.exc_info()[0]) + print('Perhaps your URL to the WSDL file is not correct.') + sys.exit(1) + + + # Get the report + try: + report = client.service.runReport(args['node'], '~point-list-report', 'csv') + except suds.WebFault as fault: + print fault + sys.exit(1) + + + # Split the report into separate lines and calculate the number of columns + lines = report.split("\n") + nColumns = len(lines[0].split(",")) + + # Declare arrays + maxColumnWidth = [0 for i in range(nColumns)] + emptyColumns = numpy.full(nColumns, True, dtype=bool) + + # Initialize the maximum column widths by the width of the column headers + column = lines[0].replace('"', '').split(",") + for i, col in enumerate(column): + maxColumnWidth[i] = len(col) + + # Calculate the maximum column width taking into account all entries of each column and check whether a column is completely empty. + # If only one entry of a specific column is not empty the whole column will be marked as not empty. + for l, line in enumerate(lines): + if l > 0 and len(line) > 0: + column = line.replace('"', '').split(",") + for i, col in enumerate(column): + if len(col) > maxColumnWidth[i]: + maxColumnWidth[i] = len(col) + if col.strip() != "": + emptyColumns[i] = False + + # Print the report in column format skipping those columns that are marked as completely empty. + for l, line in enumerate(lines): + if len(line) > 0: + column = line.replace('"', '').split(",") c = '|' - for i, n in enumerate(maxColumnWidth): + for i, col in enumerate(column): if not emptyColumns[i]: - c = c + n * '-' + '---' + formatStr = ' {:<'+str(maxColumnWidth[i])+'}' + c = c + formatStr.format(col) + ' |' print c - - -sys.exit(0) - + if l == 0: + c = '|' + for i, n in enumerate(maxColumnWidth): + if not emptyColumns[i]: + c = c + n * '-' + '---' + print c + + +if __name__=='__main__': + if len(sys.argv) < 2: + print "You haven't specified any arguments. Use -h to get more details on how to use this command." + sys.exit(1) + + parser = argparse.ArgumentParser() + parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + parser.add_argument('--node', '-n', type=str, default=None, + help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') + parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', + help="URL of the WebCTRL server as e.g. http://google.de") + args = parser.parse_args() + + # Get the password if it hasn't been passed as argument + if args.password is None: + args.password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') + + # Convert the argparse.Namespace to a dictionary via vars(args) + main(vars(args)) + sys.exit(0) diff --git a/wc_getTrend.py b/wc_getTrend.py index 81dfb98..dd2f3dc 100644 --- a/wc_getTrend.py +++ b/wc_getTrend.py @@ -5,76 +5,115 @@ import getpass -if len(sys.argv) < 2: - print "You haven't specified any arguments. Use -h to get more details on how to use this command." - - -parser = argparse.ArgumentParser() -parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') -parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') -parser.add_argument('--node', '-n', type=str, default=None, - help='The full path to the point or trend log node whose trend data is desired.') -parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") -parser.add_argument('--sTime', '-s', type=str, default=None, - help="Start Time. Returns trend data values starting with this time. Like this: 'MM/DD/YYYY HH:MM:SS AM'.") -parser.add_argument('--eTime', '-e', type=str, default=None, - help="End Time. Returns trend data values until this time. Like this: 'MM/DD/YYYY HH:MM:SS PM'.") -parser.add_argument('--limit', '-l', action='store_true', default=False, - help='If specified maxRecords are retrieved from the start. If not specified maxRecords are retrieved from the end.') -parser.add_argument('--maxRec', '-m', type=int, default=10, - help='Maximum number of records desired. Use a number >0 to limit records; use 0 to retrieve unlimited records.') -args = parser.parse_args() - - -if args.username is None: - print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h' - sys.exit(1) -else: - username = args.username -if args.password is None: - password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') -else: - password = args.password -if args.sTime is None: - print 'Start time is undefined. Use -s to define date and time.' -if args.eTime is None: - print 'End time is undefined. Use -e to define date and time.' -if args.node is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) -if args.url is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' - sys.exit(1) -else: - wsdlFile = args.url + '/_common/webservices/Trend?wsdl' - - -try: - client = suds.client.Client(wsdlFile, username=username, password=password) -except AttributeError: - print 'Error: Incorrect username and/or password' -except xml.sax._exceptions.SAXParseException: - print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' - sys.exit(1) -except: - print("Unexpected error:", sys.exc_info()[0]) - sys.exit(1) - - -try: - trendData = client.service.getTrendData(args.node, args.sTime, args.eTime, args.limit, args.maxRec) -except suds.WebFault as fault: - print fault - sys.exit(1) - - -if trendData: - for x in range(0, len(trendData) - 1, 2): - print trendData[x] + ' ' + trendData[x + 1] -else: - print 'No data caught. Check your -s and -e time specifications. Perhaps the end time is before the start time.' - sys.exit(1) - - -sys.exit(0) +def main(args): + # Check all arguments + try: + if args['username'] is None: + print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + username = args['username'] + except KeyError: + print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + sys.exit(1) + + try: + if args['password'] is None: + print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + password = args['password'] + except KeyError: + print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + sys.exit(1) + + try: + if args['node'] is None: + print 'No path to a node specified. Check all options for this command via -h' + sys.exit(1) + except KeyError: + print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + sys.exit(1) + + try: + if args['url'] is None: + print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + sys.exit(1) + else: + wsdlFile = args['url'] + '/_common/webservices/Trend?wsdl' + except KeyError: + print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + sys.exit(1) + + try: + if args['sTime'] is None: + print 'Use -s to define start date and time yourself. Now, a default is used.' + except KeyError: + print 'No "sTime" key specified. Use -s to define start date and time yourself. Now, a default is used.' + + try: + if args['eTime'] is None: + print 'Use -e to define end date and time yourself. Now, a default is used.' + except KeyError: + print 'No "eTime" key specified. Use -e to define end date and time yourself. Now, a default is used.' + + + # Connect to the webCTRL server + try: + client = suds.client.Client(wsdlFile, username=username, password=password) + except AttributeError: + print 'Error: Incorrect username and/or password' + except xml.sax._exceptions.SAXParseException: + print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' + sys.exit(1) + except: + print("Unexpected error:", sys.exc_info()[0]) + print('Perhaps your URL to the WSDL file is not correct.') + sys.exit(1) + + + # Get the answer from the server and print the output + try: + trendData = client.service.getTrendData(args['node'], args['sTime'], args['eTime'], args['limit'], args['maxRec']) + except suds.WebFault as fault: + print fault + sys.exit(1) + + if trendData: + for x in range(0, len(trendData) - 1, 2): + print trendData[x] + ' ' + trendData[x + 1] + else: + print 'No data caught. Check your -s and -e time specifications. Perhaps the end time is before the start time.' + sys.exit(1) + + +# The argument parser is only called if this script is called as a script/executable (via command line) but not when imported by another script +if __name__=='__main__': + if len(sys.argv) < 2: + print "You haven't specified any arguments. Use -h to get more details on how to use this command." + sys.exit(1) + + parser = argparse.ArgumentParser() + parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + parser.add_argument('--node', '-n', type=str, default=None, + help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') + parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', + help="URL of the WebCTRL server as e.g. http://google.de") + parser.add_argument('--sTime', '-s', type=str, default=None, + help="Start Time. Returns trend data values starting with this time. Like this: 'MM/DD/YYYY HH:MM:SS AM'.") + parser.add_argument('--eTime', '-e', type=str, default=None, + help="End Time. Returns trend data values until this time. Like this: 'MM/DD/YYYY HH:MM:SS PM'.") + parser.add_argument('--limit', '-l', action='store_true', default=False, + help='If specified maxRecords are retrieved from the start. If not specified maxRecords are retrieved from the end.') + parser.add_argument('--maxRec', '-m', type=int, default=10, + help='Maximum number of records desired. Use a number >0 to limit records; use 0 to retrieve unlimited records.') + args = parser.parse_args() + + # Get the password if it hasn't been passed as argument + if args.password is None: + args.password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') + + # Convert the argparse.Namespace to a dictionary via vars(args) + main(vars(args)) + sys.exit(0) diff --git a/wc_getValue.py b/wc_getValue.py index 7290cfb..a271d8c 100644 --- a/wc_getValue.py +++ b/wc_getValue.py @@ -5,62 +5,94 @@ import getpass -if len(sys.argv) < 2: - print "You haven't specified any arguments. Use -h to get more details on how to use this command." +def main(args): + # Check all arguments + try: + if args['username'] is None: + print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + username = args['username'] + except KeyError: + print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + sys.exit(1) + try: + if args['password'] is None: + print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + password = args['password'] + except KeyError: + print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + sys.exit(1) -parser = argparse.ArgumentParser() -parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') -parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') -parser.add_argument('--node', '-n', type=str, default=None, - help='Path to the point or node for which you want to retrieve the present value.') -parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', help="URL of the WebCTRL server as e.g. http://google.de") -args = parser.parse_args() + try: + if args['node'] is None: + print 'No path to a node specified. Check all options for this command via -h' + sys.exit(1) + except KeyError: + print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + sys.exit(1) + try: + if args['url'] is None: + print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + sys.exit(1) + else: + wsdlFile = args['url'] + '/_common/webservices/Eval?wsdl' + except KeyError: + print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + sys.exit(1) -if args.username is None: - print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h' - sys.exit(1) -else: - username = args.username -if args.password is None: - password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') -else: - password = args.password -if args.node is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) -if args.url is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' - sys.exit(1) -else: - wsdlFile = args.url + '/_common/webservices/Eval?wsdl' + # Connect to the webCTRL server + try: + client = suds.client.Client(wsdlFile, username=username, password=password) + except AttributeError: + print 'Error: Incorrect username and/or password' + except xml.sax._exceptions.SAXParseException: + print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' + sys.exit(1) + except: + print("Unexpected error:", sys.exc_info()[0]) + print('Perhaps your URL to the WSDL file is not correct.') + sys.exit(1) -try: - client = suds.client.Client(wsdlFile, username=username, password=password) -except AttributeError: - print 'Error: Incorrect username and/or password' -except xml.sax._exceptions.SAXParseException: - print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' - sys.exit(1) -except: - print("Unexpected error:", sys.exc_info()[0]) - sys.exit(1) + # Get the answer from the server and print the output + try: + value = client.service.getValue(args['node']) + except suds.WebFault as fault: + print fault + sys.exit(1) -try: - value = client.service.getValue(args.node) -except suds.WebFault as fault: - print fault - sys.exit(1) + if value is None: + print "You haven't specified a particular controller. The command could look like this:" + print '$ wc_getValue "#controller/m001"' + else: + print "Present value of " + args['node'] + " is: " + value -if value is None: - print "You haven't specified a particular controller. The command could look like this:" - print '$ wc_getValue "#controller/m001"' -else: - print "Present value of " + args.node + " is: " + value +# The argument parser is only called if this script is called as a script/executable (via command line) but not when imported by another script +if __name__=='__main__': + if len(sys.argv) < 2: + print "You haven't specified any arguments. Use -h to get more details on how to use this command." + sys.exit(1) + parser = argparse.ArgumentParser() + parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + parser.add_argument('--node', '-n', type=str, default=None, + help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') + parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', + help="URL of the WebCTRL server as e.g. http://google.de") + args = parser.parse_args() -sys.exit(0) + # Get the password if it hasn't been passed as argument + if args.password is None: + args.password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') + + # Convert the argparse.Namespace to a dictionary via vars(args) + main(vars(args)) + sys.exit(0) diff --git a/wc_query.py b/wc_query.py index 11d9083..5b43833 100644 --- a/wc_query.py +++ b/wc_query.py @@ -5,59 +5,89 @@ import getpass -if len(sys.argv) < 2: - print "You haven't specified any arguments. Use -h to get more details on how to use this command." - sys.exit(1) - - -parser = argparse.ArgumentParser() -parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') -parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') -parser.add_argument('--node', '-n', type=str, default=None, - help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') -parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', - help="URL of the WebCTRL server as e.g. http://google.de") -args = parser.parse_args() - - -if args.username is None: - print 'No user name specified. Login to WebCTRL needs a user name and password. Check all options for this command via -h' - sys.exit(1) -else: - username = args.username -if args.password is None: - password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') -else: - password = args.password -if args.node is None: - print 'No path to a node specified. Check all options for this command via -h' - sys.exit(1) -if args.url is None: - print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' - sys.exit(1) -else: - wsdlFile = args.url + '/_common/webservices/Eval?wsdl' - - -try: - client = suds.client.Client(wsdlFile, username=username, password=password) -except AttributeError: - print 'Error: Incorrect username and/or password' -except xml.sax._exceptions.SAXParseException: - print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' - sys.exit(1) -except: - print("Unexpected error:", sys.exc_info()[0]) - print('Perhaps your URL to the WSDL file is not correct.') - sys.exit(1) - - -try: - print 'Children of "' + args.node + '":' - print client.service.getChildren(args.node) -except suds.WebFault as fault: - print fault - sys.exit(1) - - -sys.exit(0) +def main(args): + # Check all arguments + try: + if args['username'] is None: + print 'No username specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + username = args['username'] + except KeyError: + print 'No "username" key specified. Please provide the key-value pair: \'username\':\'myUsername\'' + sys.exit(1) + + try: + if args['password'] is None: + print 'No password specified. Login to WebCTRL needs a username and a password. Check all options for this command via -h' + sys.exit(1) + else: + password = args['password'] + except KeyError: + print 'No "password" key specified. Please provide the key-value pair: \'password\':\'myPassword\'' + sys.exit(1) + + try: + if args['node'] is None: + print 'No path to a node specified. Check all options for this command via -h' + sys.exit(1) + except KeyError: + print 'No "node" key specified. Please provide the key-value pair: \'node\':\'/my/node\'' + sys.exit(1) + + try: + if args['url'] is None: + print 'No URL given. Specify the URL to the WebCTRL server analogous to http://google.de' + sys.exit(1) + else: + wsdlFile = args['url'] + '/_common/webservices/Eval?wsdl' + except KeyError: + print 'No "url" key specified. Please provide the key-value pair: \'url\':\'http://myURL.de\'' + sys.exit(1) + + + # Connect to the webCTRL server + try: + client = suds.client.Client(wsdlFile, username=username, password=password) + except AttributeError: + print 'Error: Incorrect username and/or password' + except xml.sax._exceptions.SAXParseException: + print 'Error: Incorrect/Misspelled WSDL file. It should be: http(s)://URL?wsdl' + sys.exit(1) + except: + print("Unexpected error:", sys.exc_info()[0]) + print('Perhaps your URL to the WSDL file is not correct.') + sys.exit(1) + + + # Get the answer from the server and print the output + try: + print 'Children of "' + args['node'] + '":' + print client.service.getChildren(args['node']) + except suds.WebFault as fault: + print fault + sys.exit(1) + + +# The argument parser is only called if this script is called as a script/executable (via command line) but not when imported by another script +if __name__=='__main__': + if len(sys.argv) < 2: + print "You haven't specified any arguments. Use -h to get more details on how to use this command." + sys.exit(1) + + parser = argparse.ArgumentParser() + parser.add_argument('--username', '-u', type=str, default=None, help='Username for the login to the WebCTRL server') + parser.add_argument('--password', '-p', type=str, default=None, help='Password for the login to the WebCTRL server') + parser.add_argument('--node', '-n', type=str, default=None, + help='Path to the point or node whose children you want to retrieve. Start querying at the lowest level with "-n /trees/geographic"') + parser.add_argument('-url', type=str, default='https://webctrl.rz-berlin.mpg.de', + help="URL of the WebCTRL server as e.g. http://google.de") + args = parser.parse_args() + + # Get the password if it hasn't been passed as argument + if args.password is None: + args.password = getpass.getpass('No password specified via -p. Please enter your WebCTRL login password: ') + + # Convert the argparse.Namespace to a dictionary via vars(args) + main(vars(args)) + sys.exit(0)