コード例 #1
0
ファイル: user.py プロジェクト: InTEGr8or/socli
def retrieve_saved_profile():
    """
    Retrieves the user's saved profile after a "socli -u" command.
    Asks the user to enter a User ID and saves it if a previous file is not found.

    :return: The user's ID as an integer
    """
    global data_file
    global app_data
    user = None
    try:
        load_datafile()
        if "user" in app_data:
            user = app_data["user"]
        else:
            raise FileNotFoundError  # Manually raising to get value
    except json.JSONDecodeError:
        # This maybe some write failures
        del_datafile()
        pr.print_warning(
            "Error in parsing the data file, it will be now deleted. Please rerun the "
            "socli -u command.")
        exit(1)
    except FileNotFoundError:
        pr.print_warning("Default user not set...\n")
        try:
            # Code to execute when first time user runs socli -u
            app_data['user'] = int(
                pr.inputs("Enter your Stackoverflow User ID: "))
            save_datafile()
            user = app_data['user']
            pr.print_green("\nUserID saved...\n")
        except ValueError:
            pr.print_warning("\nUser ID must be an integer.")
            print(
                "\nFollow the instructions on this page to get your User ID: http://meta.stackexchange.com/a/111130"
            )
            exit(1)
    return user
コード例 #2
0
def socli_browse_interactive_windows(query_tag):
    """
    Interactive mode for -b browse
    :param query_tag:
    :return:
    """
    try:
        search_res = requests.get(search.so_burl + query_tag)
        search.captcha_check(search_res.url)
        soup = BeautifulSoup(search_res.text, 'html.parser')
        try:
            soup.find_all("div", class_="question-summary")[0]  # For explicitly raising exception
            tmp = (soup.find_all("div", class_="question-summary"))
            i = 0
            question_local_url = []
            print(printer.bold("\nSelect a question below:\n"))
            while i < len(tmp):
                if i == 10:
                    break  # limiting results
                question_text = ' '.join((tmp[i].a.get_text()).split())
                question_text = question_text.replace("Q: ", "")
                printer.print_warning(str(i + 1) + ". " + printer.display_str(question_text))
                q_tag = (soup.find_all("div", class_="question-summary"))[i]
                answers = [s.get_text() for s in q_tag.find_all("a", class_="post-tag")][0:]
                ques_tags = " ".join(str(x) for x in answers)
                question_local_url.append(tmp[i].a.get("href"))
                print("  " + printer.display_str(ques_tags) + "\n")
                i = i + 1
            try:
                op = int(printer.inputs("\nType the option no to continue or any other key to exit:"))
                while 1:
                    if (op > 0) and (op <= i):
                        display_results(search.so_burl + question_local_url[op - 1])
                        cnt = 1  # this is because the 1st post is the question itself
                        while 1:
                            global tmpsoup
                            qna = printer.inputs(
                                "Type " + printer.bold("o") + " to open in browser, " + printer.bold(
                                    "n") + " to next answer, " + printer.bold(
                                    "b") + " for previous answer or any other key to exit:")
                            if qna in ["n", "N"]:
                                try:
                                    answer = (tmpsoup.find_all("div", class_="js-post-body")[cnt + 1].get_text())
                                    printer.print_green("\n\nAnswer:\n")
                                    print("-------\n" + answer + "\n-------\n")
                                    cnt = cnt + 1
                                except IndexError:
                                    printer.print_warning(" No more answers found for this question. Exiting...")
                                    sys.exit(0)
                                continue
                            elif qna in ["b", "B"]:
                                if cnt == 1:
                                    printer.print_warning(" You cant go further back. You are on the first answer!")
                                    continue
                                answer = (tmpsoup.find_all("div", class_="js-post-body")[cnt - 1].get_text())
                                printer.print_green("\n\nAnswer:\n")
                                print("-------\n" + answer + "\n-------\n")
                                cnt = cnt - 1
                                continue
                            elif qna in ["o", "O"]:
                                import webbrowser
                                printer.print_warning("Opening in your browser...")
                                webbrowser.open(search.so_burl + question_local_url[op - 1])
                            else:
                                break
                        sys.exit(0)
                    else:
                        op = int(input("\n\nWrong option. select the option no to continue:"))
            except Exception as e:
                printer.showerror(e)
                printer.print_warning("\n Exiting...")
                sys.exit(0)
        except IndexError:
            printer.print_warning("No results found...")
            sys.exit(0)

    except UnicodeEncodeError:
        printer.print_warning("\n\nEncoding error: Use \"chcp 65001\" command before using socli...")
        sys.exit(0)
    except requests.exceptions.ConnectionError:
        printer.print_fail("Please check your internet connectivity...")
    except Exception as e:
        printer.showerror(e)
        sys.exit(0)