'Check if pip is installed on Windows using python subprocess

I am using python to check whether pip is installed on the system or not. The code I have written is :

subprocess.run(["pip"],shell=True)

and I am getting the following error:

'pip' is not recognized as an internal or external command, operable program or batch file.

I have tried passing my system env to run using

env = os.environ.copy()
subprocess.run(["pip"],shell=True,env=env)

but still no luck. I installed pip on my Windows machine using get-pip.py



Solution 1:[1]

If CreateProcess (that subproces.run invokes) does not recognize pip as a command, it may recognize python? So you could do: subprocess.run(['python3', '-m', 'pip']) maybe?

Solution 2:[2]

You need to add the path of your pip installation to your PATH system variable. Type echo $PATH$ to check if it already there or not.

Solution 3:[3]

On Windows, pip will not necessarily be in the PATH environment variable, so a simple run of pip may not find it.

If pip is installed in the currently running Python, you should be able to import its module:

pip_present = True
try:
    import pip
except ImportError:
    pip_present = False

If you want to run it using subprocess, you can get its usual location relative to the currently running Python using things in sys:

pip_path = os.path.join(os.path.dirname(sys.executable), "Scripts", "pip.exe")
subprocess.run([pip_path])

Solution 4:[4]

You can check the return code of the command as such:

def pip_installed():
    pip_check = subprocess.run([sys.executable, "-m", "pip"])
    return not bool(pip_check.returncode)

This will check the returncode. If returncode is 0, that means pip is installed and will return True For any other value it will return False

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alper
Solution 2 Bayko
Solution 3 rakslice
Solution 4 Harsh