简体   繁体   中英

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

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?

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.

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])

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

import sys
import subprocess

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM