Open In App

Making automatic module installer in Python

Prerequisites: 

Many times the task of installing a module not already available in built-in Python can seem frustrating. This article focuses on removing the task of opening command-line interface and type the pip install module name to download some python modules. In this article, we will try to automate this process.



Approach:

Return Code(P) Connect Function Result
1 False Internet Off
1 True Internet is On but some other problem occurred
0 True Module Installed Successfully

Function used:

The connect() function is used for the following purposes:

  1. To check whether internet is on or off.
  2. Reach a specific URL using urllib.request.urlopen(host) command.
    • If reached successfully, return True
    • Else if not reached i.e internet is off, return false.

Given below is the implementation to achieve our functionality using the above approach.



Example:




# importing subprocess module
import subprocess
  
# importing urllib.requests for internet checking functions
import urllib.request
  
# initializing host to gfg.
def connect(host='https://www.geeksforgeeks.org/'):
  
    # trying to open gfg
    try:
        urllib.request.urlopen(host)
        return True
  
    # trying to catch exception when internet is not ON.
    except:
        return False
  
  
def main(module_name):
  
    # updating pip to latest version
    subprocess.run('python -m pip install --upgrade pip')
  
    # commanding terminal to pip install
    p = subprocess.run('pip3 install '+module_name)
  
    # internet off
    if(p.returncode == 1 and connect() == False):
        print("error!! occurred check\nInternet conection")
  
    # Every thing worked fine
    elif(p.returncode == 0):
        print("It worked", module_name, " is installed")
  
    # Name of module wrong
    elif(p.returncode == 1 and connect() == True):
        print("error!! occurred check\nName of module")
  
  
module_name = input("Enter the module name: ")
main(module_name)

Output:


Article Tags :