Auto Search StackOverflow for Errors in Code using Python - GeeksforGeeks

09 Dec, 2021
Ever faced great difficulty in copying the error you’re stuck with, opening the browser, pasting it, and opening the right Stack Overflow Answer?  Worry Not, Here’s the solution! What we are going to do is to write a Python script, which automatically detects the error from code, search about it on Stack Overflow, and opens up the few tabs related to our error that were previously been answered also.
The subprocess module is used to run new applications or programs through Python code by creating new processes. The subprocess module was created with the intention of replacing several methods available in the os module, which were not considered to be very efficient.
The requests module allows you to send HTTP requests using Python.
The webbrowser module allows us to launch the web browser.
Approach: We will divide the script into three parts, i.e. we will create three functions as follows: 
execute_return(cmd): On the first function, we are going to write code to read and run python file, and store its output or error.mak_req(error): This function will make an HTTP request using Stack Overflow API and the error we get from the 1st function and finally returns the JSON file.get_urls(json_dict): This function takes the JSON from the 2nd function, and fetches and stores the URLs of those solutions which are marked as “answered” by StackOverflow. And then finally open up the tabs containing answers from StackOverflow on the browser.
execute_return(cmd): On the first function, we are going to write code to read and run python file, and store its output or error.
mak_req(error): This function will make an HTTP request using Stack Overflow API and the error we get from the 1st function and finally returns the JSON file.
get_urls(json_dict): This function takes the JSON from the 2nd function, and fetches and stores the URLs of those solutions which are marked as “answered” by StackOverflow. And then finally open up the tabs containing answers from StackOverflow on the browser.
Note: One more thing, before we jump into the code, you should be clear with the concept of the strip and split function.
Python3
# Import dependenciesfrom subprocess import Popen, PIPEimport requestsimport webbrowser # We are going to write code to read and run python# file, and store its output or error.def execute_return(cmd):    args = cmd.split()    proc = Popen(args, stdout=PIPE, stderr=PIPE)    out, err = proc.communicate()    return out, err # This function will make an HTTP request using StackOverflow# API and the error we get from the 1st function and finally# returns the JSON file.def mak_req(error):    resp = requests.get("https://api.stackexchange.com/" +                        "/2.2/search?order=desc&tagged=python&sort=activity&intitle={}&site=stackoverflow".format(error))    return resp.json() # This function takes the JSON from the 2nd function, and# fetches and stores the URLs of those solutions which are# marked as "answered" by StackOverflow. And then finally# open up the tabs containing answers from StackOverflow on# the browser.def get_urls(json_dict):    url_list = []    count = 0         for i in json_dict['items']:        if i['is_answered']:            url_list.append(i["link"])        count += 1        if count == 3 or count == len(i):            break         for i in url_list:        webbrowser.open(i)  # Below line will go through the provided python file# And stores the output and error.out, err = execute_return("python C:/Users/Saurabh/Desktop/test.py") # This line is used to store that part of error we are interested in.error = err.decode("utf-8").strip().split("\r\n")[-1]print(error)  # A simple if condition, if error is found then execute 2nd and# 3rd function, otherwise print "No error".if error:    filter_error = error.split(":")    json1 = mak_req(filter_error[0])    json2 = mak_req(filter_error[1])    json = mak_req(error)    get_urls(json1)    get_urls(json2)    get_urls(json)     else:    print("No error")
Output:
Media error: Format(s) not supported or source(s) not found
sweetyty
Python-requests
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python