Search code examples
pythonpip

Piping pip freeze and pip uninstall


I can clean my current python environment in two steps

pip freeze > requirements.txt
pip uninstall -r requirements.txt -y

I was wondering if it's possible to pipe these two commands to avoid creating the temporary file (and why or why not). The naive approach (below) does not seem to work

pip freeze | pip uninstall -y -r

Solution

  • pip uninstall -r requires an argument — a file, so you cannot do exactly this way. Even standard notation - (read stdin) doesn't work:

    $ pip freeze | pip uninstall -y -r
    
    Usage:   
      pip uninstall [options] <package> ...
      pip uninstall [options] -r <requirements file> ...
    
    -r option requires 1 argument
    
    $ pip freeze | pip uninstall -y -r -
    ERROR: Could not open requirements file: [Errno 2] No such file or directory: '-'
    

    On Linux you can do this trick to read stdin as a file:

    $ pip freeze | pip uninstall -y -r /dev/stdin
    

    Don't know if something like is available in different Unices.

    Finally, the most portable way is:

    $ pip freeze | xargs pip uninstall -y