1

I wrote a python script to make an api call. The script returns a integer(number). I want to compare this output with a parameter that is going to pass to the script.

for example if x is the number returned by the script, I would to like to execute script as follows python test.py 20 and compare x with 20.

Please help.

Below is the script:

import json
import os, sys
import urllib2

def main():
    data = json.load(urllib2.urlopen('some url'))
    val = data.keys()[0]
    print(val)

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print ('!!FAIL {0}!!!'.format(e))
mhawke
  • 84,695
  • 9
  • 117
  • 138
sudhir kumar
  • 115
  • 1
  • 11

2 Answers2

1

You can access the command line arguments via the sys.argv list:

import json
import os, sys
import urllib2

def main(expected_value):
    data = json.load(urllib2.urlopen('some url'))
    matched = data.keys()[0] == expected_value
    print('expected value {}'.format('matched' if matched else 'mismatch'))
    # and you could return a bool...
    return matched

if __name__ == "__main__":
    try:
        main(sys.argv[1])    # pass the first command line argument to main()
    except Exception as e:
        print('!!FAIL {0}!!!'.format(e))
mhawke
  • 84,695
  • 9
  • 117
  • 138
0

First, you should wrap your script into a function (main() for example) that returns a value to compare. Second, you have to get the command line argument with sys.argv. The template of what you need may look like this:

import sys

def main():
    # do something you need ...
    return 5

if __name__ == "__main__":
    returned = main()
    correct_returned = int(sys.argv[1])
    if returned == correct_returned:
        print("Everything is fine.")
    else:
        print("Error: the script returned {0} instead of {1}".format(returned, correct_returned))
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95