简体   繁体   中英

Unable to automatically install python packages from script

I am in need of installing Python packages directly from a script. I know this is generally viewed as bad practice, but the script needs to be entirely self-contained. I tried this option which I found quite handy:

import subprocess
import sys    
list_of_packages=['package_1', 'package_2', ... 'package_n']    
def install(package):
    subprocess.check_call([sys.executable, "-m", "pip", "install", package]
for package in list_of_packages:
    install(package)

This works on a machine with Python 3.8.3 installed. However, when I try to execute the script on another machine with Python 3.10.0 installed, I get the following error:

subprocess.CalledProcessError: Command '['[PYTHONPATH]\\pythonw.exe', '-m', 'pip', 'install', 'package_1']' returned non-zero exit status 2.

I don't understand whether this is due to the different Python versions (perhaps the subprocess and sys modules have been modified) or whether there is some other module in my old machine which makes it work ( Python 3.10.0 has been just recently installed in the new machine and no external packages have been installed yet).

EDIT: After @Passi 's answer I tried reinstalling Python and checking the required box to add pip to the PATH variable. Unfortunately this did not work. I am able to manually install packages on command prompt typing:

python -m pip install 'package_name'

but when I run the script, either from IDLE or command prompt I always get the same error. Changing pip to pip3 did not solve this either.

You can try pip3. It is important that pip or pip3 is as a PATH variable. There is a "bug" that after installing Python version 3.10 that the Python3 PATH variable is removed.

epython 安装程序 img

Check the box and your pip will be in the PATH variable

It would be better when you do something like that with a PoweShell oder Bash script.

I managed to solve the issue by downgrading to Python 3.8. It seems like there are clashes between some of the packages and Python 3.10.

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