How can I use a pip requirements file to uninstall as well as install packages?

前端 未结 10 1190
猫巷女王i
猫巷女王i 2021-01-30 04:48

I have a pip requirements file that changes during development.

Can pip be made to uninstall packages that do not appear in the requirement

相关标签:
10条回答
  • 2021-01-30 05:30

    Piggybacking off @stephen-j-fuhry here is a powershell equivalent I use:

    pip freeze | ? { $_ -notmatch ((gc req.txt) -join "|") }
    
    0 讨论(0)
  • 2021-01-30 05:35

    You can now pass the -r requirements.txt argument to pip uninstall.

    pip uninstall -r requirements.txt -y
    

    At least as of pip 8.1.2, pip help uninstall shows:

    ...
    Uninstall Options:
      -r, --requirement <file>    Uninstall all the packages listed in the given requirements file.  This option can be
                                  used multiple times.
    ...
    
    0 讨论(0)
  • 2021-01-30 05:36

    Here's a simple solution that works:

    pip uninstall $(pip freeze) -y

    0 讨论(0)
  • 2021-01-30 05:43

    This should uninstall anything not in requirements.txt:

    pip freeze | grep -v -f requirements.txt - | grep -v '^#' | xargs pip uninstall -y
    

    Although this won't work quite right with packages installed with -e, i.e. from a git repository or similar. To skip those, just filter out packages starting with the -e flag:

    pip freeze | grep -v -f requirements.txt - | grep -v '^#' | grep -v '^-e ' | xargs pip uninstall -y
    

    Then, obviously:

    pip install -r requirements.txt
    

    Update for 2016: You probably don't really want to actually use the above approach, though. Check out pip-tools and pip-sync which accomplish what you are probably looking to do in a much more robust way.

    https://github.com/nvie/pip-tools

    Update for May, 2016:

    You can now also use pip uninstall -r requirements.txt, however this accomplishes basically the opposite - it uninstalls everything in requirements.txt

    Update for May, 2019:

    Check out pipenv. A lot has happened in the world of package management that makes this sort of question a bit obsolete. I'm actually still quite happily using pip-tools, though.

    0 讨论(0)
提交回复
热议问题