How to find which pip package owns a file?

2019-04-04 04:55发布

I have a file that I suspect was installed by pip. How can I find which package installed that file?

In other words, I'm looking for a command similar to pacman -Qo filename or dpkg -S filename, but for pip. Does it exist? Or should I use some combination of pip and grep? In that case, I don't know how to list all the file installed.

标签: python pip
3条回答
不美不萌又怎样
2楼-- · 2019-04-04 05:12

Try this!

find_pkg_by_filename(){ for pkg in $(pip list | cut -d" " -f1) ; do if pip show -f "$pkg" | grep "$1" ; then echo "=== Above files found in package $pkg ===" ; fi ; done ; }

find_pkg_by_filename somefilename

Note that if you add -q to the grep, it will exit as soon as there's a match, and then pip will complain about broken pipes.

查看更多
时光不老,我们不散
3楼-- · 2019-04-04 05:21

You could try with

pip list | tail -n +3 | cut -d" " -f1 | xargs pip show -f | grep "filename"

Then search through the results looking for that file.

查看更多
Anthone
4楼-- · 2019-04-04 05:35

You can use a python script like this:

#! /usr/bin/env python

import sys
import pip.utils
MYPATH=sys.argv[1]
for dist in pip.utils.get_installed_distributions():
    # RECORDs should be part of .dist-info metadatas
    if dist.has_metadata('RECORD'):
        lines = dist.get_metadata_lines('RECORD')
        paths = [l.split(',')[0] for l in lines]
    # Otherwise use pip's log for .egg-info's
    elif dist.has_metadata('installed-files.txt'):
        paths = dist.get_metadata_lines('installed-files.txt')
    else:
        paths = []

    if MYPATH in paths:
        print(dist.project_name)

Usage looks like this:

$ python lookup_file.py requests/__init__.py 
requests

I wrote a more complete version here, with absolute paths:

https://github.com/nbeaver/pip_file_lookup

查看更多
登录 后发表回答