Python-将控制流传递回脚本顶部

时间:2014-10-15 16:15:01

标签: python function control-flow

我正在尝试使用Requests获取页面内容.URL有3个参数:

  1. 唯一网页ID

  2. 用户名

  3. 密码
  4. 我的初始代码块如下所示:

    import requests
    
    id = raw_input("Enter the unique id:")
    user = raw_input("Enter your username:")
    password = raw_input("Enter corresponding password:")
    
    try:
        r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
        if r.status_code == 404:
            print "No such page exists.Please check the ID and try again"
            ## Ask for input again
        else:
            print r.text 
    except requests.ConnectionError:
        print "Server is refusing connections.Please try after sometime"
        sys.exit(1)
    

    我的问题是在注释行上,我希望再次提示用户输入。如何将控制流传递回脚本的顶部。

    我有一种模糊的感觉,我可能会以非常粗暴的方式这样做,并且可能会有更优雅的解决方案使用函数。如果有,请赐教我。

3 个答案:

答案 0 :(得分:3)

这将做你想要的。

import requests

def user_input():
    id1 = raw_input("Enter the unique id:")
    user = raw_input("Enter your username:")
    password = raw_input("Enter corresponding password:")

    try:
        r = requests.get('http://test.com/request.pl?id='+ id1 + user + password)
        if r.status_code == 404:
            print "No such page exists.Please check the ID and try again"
        ## Ask for input again
            user_input()
        else:
            print r.text
    except requests.ConnectionError:
        print "Server is refusing connections.Please try after sometime"
        sys.exit(1)
user_input()

答案 1 :(得分:2)

最简单(但不一定是最具扩展性)的方法是将所有内容放在while True循环中。

import requests

while True:
    id = raw_input("Enter the unique id:")
    user = raw_input("Enter your username:")
    password = raw_input("Enter corresponding password:")

    try:
        r = requests.get('http://test.com/request.pl?id=' + id, auth=(user, password))
        if r.status_code == 404:
            print "No such page exists.Please check the ID and try again"
            ## control flow will reach the bottom and return to the top
        else:
            print r.text
            break
    except requests.ConnectionError:
        print "Server is refusing connections.Please try after sometime"
        sys.exit(1) ## Exit condition of the loop

答案 2 :(得分:2)

我会将此代码放在while循环中,该循环始终在True时执行:并且有一个标志,允许您适当地突破循环。