我写了一个python脚本来进行api调用。该脚本返回一个整数(数字)。我想将此输出与将要传递给脚本的参数进行比较。
例如,如果x是脚本返回的数字,我想按如下方式执行脚本python test.py 20并将x与20进行比较。
请帮忙。
以下是剧本:
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))
答案 0 :(得分:1)
您可以通过sys.argv
列表访问命令行参数:
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))
答案 1 :(得分:0)
首先,您应该将脚本包装到函数(例如main()
)中,该函数返回要比较的值。其次,您必须使用sys.argv
获取命令行参数。您需要的模板可能如下所示:
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))