2009-06-09 6 views
7

Existe-t-il un moyen de rechercher un package/une fonction particulier à l'aide de mots-clés dans la console Python? Par exemple, je souhaite rechercher "pdf" pour des tâches liées au pdf.Comment rechercher de l'aide à l'aide de la console python

+0

Je dois être en mesure de « rechercher » les paquets ... pdf est simplement utilisé comme exemple ici ... en utilisant la fonction « help » ou « dir » seulement aider si je savoir quel paquet utiliser en premier lieu. –

+0

J'avais besoin de quelque chose comme "module docs" fourni avec la distribution de Windows .. cependant je dois le faire avec la console. –

Répondre

8

Le drapeau pydoc -k recherche dans la documentation.

pydoc -k <keyword> 
    Search for a keyword in the synopsis lines of all available modules. 

A partir d'un terminal, exécutez ..

$ pydoc -k pdf 

..par exemple:

$ pydoc -k pdf 
PdfImagePlugin 
wx.lib.pdfwin 
PIL.PdfImagePlugin 

Il ne recherche pas le contenu de la documentation, mais il recherche tous les noms de modules - si cela ne suffit pas, je suggère d'utiliser Google ou StackOverflow pour rechercher « module PDF Python » ou similaires

+2

'pydoc' n'est pas reconnu comme commande interne ou externe, programme utilisable ou fichier batch. (Win) –

0

Essayez help() ou dir(). AFAIR il n'y a pas de support intégré pour les tâches liées au pdf dans l'installation de Python. Une autre façon de trouver de l'aide pour les modules Python est à google;)

Docs:

http://docs.python.org/library/functions.html#help

http://docs.python.org/library/functions.html#dir

EDIT:

>>> import os 
>>> def search_help(keyword): 
...  os.system('python Lib/pydoc.py -k %s' % keyword) 
... 
>>> search_help('math') 
cmath - This module is always available. It provides access to mathematical 
math - This module is always available. It provides access to the 
test.test_cmath 
test.test_math 
>>> search_help('pdf') 
>>> _ 

Vous devez avoir répertoire principal python dans ton chemin. Et cela ne fonctionnera pas sous IDLE. HTH.

+0

@Umair - utilise le système d'aide fourni avec votre installation python. Vous pouvez aussi essayer ceci - http://pypi.python.org/pypi?:action=browse - c'est une liste de modules python, triés par sujet. @Jaime - vous pouvez utiliser l'aide ('math') sans importer quoi que ce soit. – uolot

1

Aide de type console (objet):

Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on 
win32 
Type "help", "copyright", "credits" or "license" for more information. 
>>> help(dir) 
Help on built-in function dir in module __builtin__: 

dir(...) 
    dir([object]) -> list of strings 
....  

Unfortunatelly il n'y a pas d'aide pour pdf:

>>> help(pdf) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'pdf' is not defined 
>>> 

Comme paffnucy dit essayer Internet la recherche (fonctionne SO Wery bien :)

Ce site peut être utile aussi: http://www.gotapi.com/python

8

Vous pouvez utiliser l'aide pour accéder aux docstrings des différents modules que vous avez importés, par exemple, les opérations suivantes:

help(math) 

et vous obtiendrez une erreur,

import math 
help(math) 

et vous obtiendrez une liste des méthodes disponibles dans le module, mais seulement après l'avoir importé. Il fonctionne également avec des fonctions individuelles, par ex. après avoir importé des maths, essayez:

help(math.sin) 

Pour traiter le pdf, vous devrez probablement installer un module tiers. Une recherche rapide m'a conduit à ce résultat, que je ne l'ai pas essayé:

http://www.devshed.com/c/a/Python/Python-for-PDF-Generation/

5

aide ("modules")

>>> help("modules") 

Please wait a moment while I gather a list of all available modules... 

C:\Program Files\Python26\lib\pkgutil.py:110: DeprecationWarning: The wxPython compatibility package is no longer automatically generated or actively maintained. Please switch to the wx package as soon 
    __import__(name) 
ArgImagePlugin  WmfImagePlugin  dbhash    pyclbr 
BaseHTTPServer  XVThumbImagePlugin decimal    pydoc 
Bastion    XbmImagePlugin  difflib    pydoc_topics 
BdfFontFile   XpmImagePlugin  dircache   pyexpat 
BmpImagePlugin  _LWPCookieJar  dis     quopri 
BufrStubImagePlugin _MozillaCookieJar distutils   random 
CGIHTTPServer  __builtin__   doctest    re 
Canvas    __future__   dumbdbm    repr 
ConfigParser  _abcoll    dummy_thread  rexec 
ContainerIO   _ast    dummy_threading  rfc822 
Cookie    _bisect    email    rlcompleter 
CurImagePlugin  _bsddb    encodings   robotparser 
DcxImagePlugin  _bytesio   errno    runpy 
Dialog    _codecs    exceptions   sched 
DocXMLRPCServer  _codecs_cn   filecmp    select 
EpsImagePlugin  _codecs_hk   fileinput   sets 
ExifTags   _codecs_iso2022  fnmatch    sgmllib 
FileDialog   _codecs_jp   formatter   sha 
FitsStubImagePlugin _codecs_kr   fpformat   shelve 
FixTk    _codecs_tw   fractions   shlex 
FliImagePlugin  _collections  ftplib    shutil 
FontFile   _csv    functools   signal 
FpxImagePlugin  _ctypes    future_builtins  site 
GbrImagePlugin  _ctypes_test  gc     smtpd 
GdImageFile   _elementtree  genericpath   smtplib 
GifImagePlugin  _fileio    getopt    sndhdr 
GimpGradientFile _functools   getpass    socket 
GimpPaletteFile  _hashlib   gettext    sqlite3 
GribStubImagePlugin _heapq    glob    sre 
HTMLParser   _hotshot   gzip    sre_compile 
Hdf5StubImagePlugin _imaging   hashlib    sre_constants 
IcnsImagePlugin  _imagingft   heapq    sre_parse 
IcoImagePlugin  _imagingmath  hmac    ssl 
ImImagePlugin  _imagingtk   hotshot    stat 
Image    _json    htmlentitydefs  statvfs 
ImageChops   _locale    htmllib    string 
ImageColor   _lsprof    httplib    stringold 
ImageDraw   _md5    idlelib    stringprep 
ImageDraw2   _msi    ihooks    strop 
ImageEnhance  _multibytecodec  imageop    struct 
ImageFile   _multiprocessing imaplib    subprocess 
ImageFileIO   _random    imghdr    sunau 
ImageFilter   _sha    imp     sunaudio 
ImageFont   _sha256    imputil    symbol 
ImageGL    _sha512    inspect    symtable 
ImageGrab   _socket    io     sys 
ImageMath   _sqlite3   itertools   tabnanny 
ImageMode   _sre    json    tarfile 
ImageOps   _ssl    keyword    telnetlib 
ImagePalette  _strptime   lib2to3    tempfile 
ImagePath   _struct    linecache   test 
ImageQt    _subprocess   locale    textwrap 
ImageSequence  _symtable   logging    this 
ImageStat   _testcapi   macpath    thread 
ImageTk    _threading_local macurl2path   threading 
ImageTransform  _tkinter   mailbox    time 
ImageWin   _warnings   mailcap    timeit 
ImtImagePlugin  _weakref   markupbase   tkColorChooser 
IptcImagePlugin  _winreg    marshal    tkCommonDialog 
JpegImagePlugin  abc     math    tkFileDialog 
McIdasImagePlugin aifc    md5     tkFont 
MicImagePlugin  anydbm    mhlib    tkMessageBox 
MimeWriter   array    mimetools   tkSimpleDialog 
MpegImagePlugin  ast     mimetypes   toaiff 
MspImagePlugin  asynchat   mimify    token 
OleFileIO   asyncore   mmap    tokenize 
PIL     atexit    modulefinder  trace 
PSDraw    audiodev   msilib    traceback 
PaletteFile   audioop    msvcrt    tty 
PalmImagePlugin  base64    multifile   turtle 
PcdImagePlugin  bdb     multiprocessing  types 
PcfFontFile   binascii   mutex    unicodedata 
PcxImagePlugin  binhex    netrc    unittest 
PdfImagePlugin  bisect    new     update_manifest 
PixarImagePlugin bsddb    nntplib    urllib 
PngImagePlugin  bz2     nt     urllib2 
PpmImagePlugin  cPickle    ntpath    urlparse 
PsdImagePlugin  cProfile   nturl2path   user 
Queue    cStringIO   numbers    uu 
ScrolledText  calendar   opcode    uuid 
SgiImagePlugin  cgi     operator   warnings 
SimpleDialog  cgitb    optparse   wave 
SimpleHTTPServer chunk    os     weakref 
SimpleXMLRPCServer cmath    os2emxpath   webbrowser 
SocketServer  cmd     parser    whichdb 
SpiderImagePlugin code    pdb     winsound 
StringIO   codecs    pickle    wsgiref 
SunImagePlugin  codeop    pickletools   wx 
TarIO    collections   pipes    wxPython 
TgaImagePlugin  colorsys   pkgutil    wxversion 
TiffImagePlugin  commands   platform   xdrlib 
TiffTags   compileall   plistlib   xml 
Tix     compiler   popen2    xmllib 
Tkconstants   contextlib   poplib    xmlrpclib 
Tkdnd    cookielib   posixfile   xxsubtype 
Tkinter    copy    posixpath   zipfile 
UserDict   copy_reg   pprint    zipimport 
UserList   csv     profile    zlib 
UserString   ctypes    pstats 
WalImageFile  curses    pty 
WbmpImagePlugin  datetime   py_compile 

Enter any module name to get more help. Or, type "modules spam" to search 
for modules whose descriptions contain the word "spam". 

>>> 
2

(années plus tard) J'utilise maintenant pip search
et yolk -M ou -H packagename: -M pour les métadonnées, -H pour naviguer sur sa page web.


Pour rechercher info package PyPI (pypi) localement, essayez pypi-grep. Un exemple: pypi-grep 'pyqt' ->

# day status packagename version homepage summary 
2009-06-07 3 "pydee" 0.4.11 http://code.google.com/p/pydee/ 
    Pydee development environment and its PyQt4-based IDE tools: ... 
2009-06-05 4 "Sandbox" 0.9.5 http://www.qtrac.eu/sandbox.html 
    A PyQt4-based alternative to IDLE 
... 

pypi-grep est juste un fichier avec une longue ligne par paquet PyPI, avec les informations que vous voyez ci-dessus, plus un script bash trivial pour egrep le fichier.
Pourquoi? Grepping un fichier local est très rapide et très simple, pour les vieux gars Unix et des recherches simples: "qu'est-ce que XYZ?"

hg clone http://bitbucket.org/denisb/pypi-grep/ doit télécharger pypi-grep et pypi-grepfile-2009-06-08 ou similaire; déplacez-les dans un répertoire de votre PATH. (. Tout d'abord easy_install hg si vous n'avez pas hg)

Notes:

le pypi-grepfile a qu'une seule version par paquet, le plus récent; résumés multilignes sont pliés à une longue ligne (que je coupe avec pypi-grep | less -iS).

pypi-grep -h énumère quelques options

Les données proviennent de http://pypi.python.org/pypi xmlrpc, mais méfiez-vous: quelques paquets list_packages ont pas package_releases ou pas releasedata, et quelques releasedatas Délai d'attente (timeout_xmlrpclib); ce que vous voyez est tout ce que vous obtenez.

Vos commentaires sont les bienvenus.

+0

Désolé, j'ai omis de mentionner que j'utilise Windows ... Je vais essayer de trouver une solution similaire pour Windows. –

4

Vous pouvez rechercher des modules contenant "pdf" dans leur description en exécutant la commande help("modules pdf").

1

Penser récursive:

>>> help(help) 

Help on _Helper in module site object: 

class _Helper(builtins.object) 
| Define the builtin 'help'. 
| This is a wrapper around **pydoc.help** (with a twist). 
| 

... 

d'ici:

>>> import pydoc 
>>> help(pydoc) 
Help on module pydoc: .... 

beaucoup d'informations essentielles sur la recherche en python là-bas docs.

3

pip est une excellente ressource. Si pip est installé (si vous ne l'avez pas, les instructions sont here), puis en utilisant l'interpréteur de commandes de Windows, vous pouvez effectuer les opérations suivantes:

pip search pdf 

Il retourne une pléthore d'options.

C:\Python27\Scripts>pip search pdf 
mwlib.rl     - generate pdfs from mediawiki markup 
slc.publications   - A content type to store and parse pdf publications 
PyPDFLite     - Simple PDF Writer. 
pdfminer     - PDF parser and analyzer 
zopyx.convert    - A Python interface to XSL-FO libraries (Conversion 
          HTML to PDF, RTF, DOCX, WML and ODT) 
WeasyPrint    - WeasyPrint converts web documents to PDF. 
zopyx.convert2   - A Python interface for the conversion of HTML to 
          PDF, RTF, DOCX, WML and ODT) - belongs to 
          zopyx.smartprintng.core 
collective.pdfpeek  - A Plone 4 product that generates image thumbnail 
          previews of PDF files stored on ATFile based 
          objects. 
pisa      - PDF generator using HTML and CSS 

etc.

Questions connexes