Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upgrading python module within code

Tags:

python

pip

My question relates to this question: Installing python module within code, but involves upgrading the module.

I've tried

packages=['apscheduler','beautifulsoup4','gdata']

def upgrade(packages):
    for package in packages:
        pip.main(['install --upgrade', package])

and

def upgrade(packages):
    for package in packages:
        pip.main(['install', package + ' --upgrade'])
like image 412
jason Avatar asked Sep 16 '14 06:09

jason


2 Answers

Try pip.main(['install', '--upgrade', package]).

"--upgrade" is a separate command-line argument, so you need to pass it separately to main.

like image 193
BrenBarn Avatar answered Sep 22 '22 23:09

BrenBarn


BrenBarn's answer matches the style of OP's code, but Richard Wheatley's answer is closer to my code.

Richard's answer has a couple of issues I'd like to fix, though, and I didn't want to edit his because the differences are reasonably significant.

from subprocess import call

my_packages = ['apscheduler', 'beautifulsoup4', 'gdata']

def upgrade(package_list):
    call(['pip', 'install', '--upgrade'] + package_list)

Notes:

  • No need to import the pip module (subprocess calls the pip binary found in its path)
  • Unecessary use of shell=True in call() (and other subprocess functions) should be be avoided, as it puts responsibility on the programmer to protect against shell injection vulnerabilities. (Not really an issue here, but good as a general rule.)
  • A single invocation of pip install accepts an arbitrary number of package names, and a single use of --upgrade will apply to all of them.
  • We can leverage the previous fact and Python's list concatenation to avoid writing a loop.
like image 43
Peter Henry Avatar answered Sep 20 '22 23:09

Peter Henry