Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python脚本将函数的输出与传递给脚本的参数进行比较_Python_Python 2.7 - Fatal编程技术网

Python脚本将函数的输出与传递给脚本的参数进行比较

Python脚本将函数的输出与传递给脚本的参数进行比较,python,python-2.7,Python,Python 2.7,我编写了一个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]

我编写了一个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))

您可以通过以下列表访问命令行参数:


首先,应该将脚本包装到一个函数中(例如,
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))
可能重复的
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))